@extends('layouts.dashboard.superadminapp')

@section('title', 'Bill Report')

@section('styles')
<style>
    div.dt-buttons {
        float: left;
        display: flex !important;
    }
    .dataTable {
        overflow-x: auto !important;
        display: table !important;
    }
    .dt-buttons .btn {
        margin-right: 0.5rem !important;
        padding: 0.25rem 0.75rem !important;
        font-size: 0.95rem !important;
    }
    .stat-card {
        border-radius: 10px;
        padding: 20px;
        text-align: center;
        color: #fff;
        transition: transform 0.2s;
    }
    .stat-card:hover {
        transform: translateY(-3px);
    }
    .stat-card .stat-value {
        font-size: 1.8rem;
        font-weight: bold;
    }
    .stat-card .stat-label {
        font-size: 0.85rem;
        opacity: 0.9;
    }
    .bg-total { background: linear-gradient(135deg, #4e73df 0%, #224abe 100%); }
    .bg-paid { background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%); }
    .bg-pending { background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%); }
    .bg-amount { background: linear-gradient(135deg, #36b9cc 0%, #258391 100%); }
</style>
@endsection

@section('content')

<!-- Page Heading -->
<x-layout.page-header title="UEPL | Bill (Tax Invoice) Report" icon="chart-bar" iconColor="info" />

<!-- Alerts -->
@if(session('success'))
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle mr-2"></i>{{ session('success') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif
@if(session('error'))
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle mr-2"></i>{{ session('error') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif

<!-- Filter Card -->
<div class="card shadow mb-4">
    <div class="card-header py-3" style="background: linear-gradient(135deg, #6c757d 0%, #495057 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-filter mr-2"></i> Filter Options
        </h6>
    </div>
    <div class="card-body">
        <form id="billReportFilters" method="POST" action="{{ route('superadmin.report.billreport') }}">
            @csrf
            <div class="row align-items-end">
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Company</label>
                    <select name="company_id" class="form-control">
                        <option value="">All Companies</option>
                        @foreach($companies as $id => $name)
                            <option value="{{ $id }}" {{ $selectedCompany == $id ? 'selected' : '' }}>
                                {{ $name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2 mb-3">
                    <label class="small font-weight-bold">From Date</label>
                    <input type="date" name="from_date" class="form-control" value="{{ $fromDate }}">
                </div>
                <div class="col-md-2 mb-3">
                    <label class="small font-weight-bold">To Date</label>
                    <input type="date" name="to_date" class="form-control" value="{{ $toDate }}">
                </div>
                <div class="col-md-3 mb-3">
                    <button type="submit" class="btn btn-primary btn-sm mr-2">
                        <i class="fas fa-search mr-1"></i> Apply Filter
                    </button>
                    <a href="{{ route('superadmin.report.billreport') }}" class="btn btn-secondary btn-sm">
                        <i class="fas fa-redo mr-1"></i> Reset
                    </a>
                </div>
                <div class="col-md-2 mb-3">
                    <button type="button" class="btn btn-success btn-sm" id="exportExcelBtn">
                        <i class="fas fa-file-excel mr-1"></i> Export Excel
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

@php
    $totalInvoices = $invoices->count();
    $totalAmount = $invoices->sum('total_amount');
    $totalItems = $invoices->sum(fn($inv) => $inv->items->count());
    $avgAmount = $totalInvoices > 0 ? round($totalAmount / $totalInvoices, 2) : 0;
@endphp

<!-- Summary Stats -->
<div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="stat-card bg-total">
            <div class="stat-value">{{ $totalInvoices }}</div>
            <div class="stat-label"><i class="fas fa-file-invoice mr-1"></i> Total Invoices</div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="stat-card bg-amount">
            <div class="stat-value">{{ number_format($totalAmount, 2) }}</div>
            <div class="stat-label"><i class="fas fa-rupee-sign mr-1"></i> Total Amount</div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="stat-card bg-paid">
            <div class="stat-value">{{ $totalItems }}</div>
            <div class="stat-label"><i class="fas fa-box mr-1"></i> Total Items</div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="stat-card bg-pending">
            <div class="stat-value">{{ number_format($avgAmount, 2) }}</div>
            <div class="stat-label"><i class="fas fa-chart-line mr-1"></i> Avg Invoice Amount</div>
        </div>
    </div>
</div>

<!-- Bill Details Card -->
<div class="card shadow mb-4">
    <div class="card-header py-3" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-file-invoice-dollar mr-2"></i> Invoice Details
        </h6>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table id="billTable" class="table table-bordered table-striped table-sm" width="100%">
                <thead class="thead-light">
                    <tr class="text-center">
                        <th>Invoice No</th>
                        <th>Invoice Date</th>
                        <th>Company</th>
                        <th>GST</th>
                        <th>Phone</th>
                        <th>Email</th>
                        <th>Item Description</th>
                        <th>HSN</th>
                        <th>Qty</th>
                        <th>Rate</th>
                        <th>SGST</th>
                        <th>CGST</th>
                        <th>IGST</th>
                        <th>Amount</th>
                        <th>Total</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($invoices as $inv)
                        @if($inv->items->count())
                            @foreach($inv->items as $index => $item)
                                <tr class="text-center">
                                    <td>{{ $inv->invoice_no }}</td>
                                    <td>{{ $inv->invoice_date ? \Carbon\Carbon::parse($inv->invoice_date)->format('d-m-Y') : '-' }}</td>
                                    <td class="text-left">{{ $inv->company->company ?? '-' }}</td>
                                    <td>{{ $inv->gst ?? '-' }}</td>
                                    <td>{{ $inv->phone ?? '-' }}</td>
                                    <td>{{ $inv->email ?? '-' }}</td>
                                    <td class="text-left">{{ $item->description ?? '-' }}</td>
                                    <td>{{ $item->hsn ?? '-' }}</td>
                                    <td>{{ $item->quantity ?? 0 }}</td>
                                    <td>{{ number_format($item->rate ?? 0, 2) }}</td>
                                    <td>{{ number_format($item->sgst ?? 0, 2) }}</td>
                                    <td>{{ number_format($item->cgst ?? 0, 2) }}</td>
                                    <td>{{ number_format($item->igst ?? 0, 2) }}</td>
                                    <td>{{ number_format($item->amount ?? 0, 2) }}</td>
                                    <td><strong>{{ number_format($inv->total_amount ?? 0, 2) }}</strong></td>
                                </tr>
                            @endforeach
                        @else
                            <tr class="text-center">
                                <td>{{ $inv->invoice_no }}</td>
                                <td>{{ $inv->invoice_date ? \Carbon\Carbon::parse($inv->invoice_date)->format('d-m-Y') : '-' }}</td>
                                <td class="text-left">{{ $inv->company->company ?? '-' }}</td>
                                <td>{{ $inv->gst ?? '-' }}</td>
                                <td>{{ $inv->phone ?? '-' }}</td>
                                <td>{{ $inv->email ?? '-' }}</td>
                                <td colspan="8" class="text-center text-muted">No items</td>
                                <td><strong>{{ number_format($inv->total_amount ?? 0, 2) }}</strong></td>
                            </tr>
                        @endif
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Invoice Summary by Company -->
<div class="row">
    <div class="col-md-6">
        <div class="card shadow mb-4">
            <div class="card-header py-3" style="background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%);">
                <h6 class="m-0 font-weight-bold text-white">
                    <i class="fas fa-building mr-2"></i> Top Companies by Invoice Amount
                </h6>
            </div>
            <div class="card-body p-0">
                <table class="table table-sm mb-0">
                    <thead class="thead-light">
                        <tr>
                            <th>Company</th>
                            <th class="text-center">Invoices</th>
                            <th class="text-right">Total Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        @php
                            $companyTotals = $invoices->groupBy(fn($inv) => $inv->company->company ?? 'Unknown')
                                ->map(fn($group) => [
                                    'count' => $group->count(),
                                    'total' => $group->sum('total_amount')
                                ])
                                ->sortByDesc('total')
                                ->take(5);
                        @endphp
                        @forelse($companyTotals as $company => $data)
                            <tr>
                                <td>{{ $company }}</td>
                                <td class="text-center">
                                    <span class="badge badge-primary">{{ $data['count'] }}</span>
                                </td>
                                <td class="text-right">
                                    <span class="badge badge-success">{{ number_format($data['total'], 2) }}</span>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="3" class="text-center text-muted py-3">No data available</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card shadow mb-4">
            <div class="card-header py-3" style="background: linear-gradient(135deg, #36b9cc 0%, #258391 100%);">
                <h6 class="m-0 font-weight-bold text-white">
                    <i class="fas fa-calendar-alt mr-2"></i> Recent Invoices
                </h6>
            </div>
            <div class="card-body p-0">
                <table class="table table-sm mb-0">
                    <thead class="thead-light">
                        <tr>
                            <th>Invoice No</th>
                            <th>Date</th>
                            <th class="text-right">Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($invoices->sortByDesc('invoice_date')->take(5) as $inv)
                            <tr>
                                <td>{{ $inv->invoice_no }}</td>
                                <td>{{ $inv->invoice_date ? \Carbon\Carbon::parse($inv->invoice_date)->format('d-m-Y') : '-' }}</td>
                                <td class="text-right">
                                    <span class="badge badge-info">{{ number_format($inv->total_amount ?? 0, 2) }}</span>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="3" class="text-center text-muted py-3">No recent invoices</td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script>
$(document).ready(function() {
    $('#billTable').DataTable({
        dom: 'Bfrtip',
        buttons: [
            { extend: 'copy', className: 'btn btn-secondary btn-sm' },
            { extend: 'csv', className: 'btn btn-secondary btn-sm' },
            { extend: 'excel', className: 'btn btn-secondary btn-sm' },
            { extend: 'pdf', className: 'btn btn-secondary btn-sm' },
            { extend: 'print', className: 'btn btn-secondary btn-sm' },
            { extend: 'colvis', className: 'btn btn-secondary btn-sm' }
        ],
        pageLength: 25,
        responsive: true,
        order: [[1, 'desc']],
        language: {
            emptyTable: "No invoice records found"
        }
    });

    // Export Excel logic
    $('#exportExcelBtn').click(function() {
        let form = $('#billReportFilters');
        let originalAction = form.attr('action');
        form.attr('action', '{{ route("superadmin.report.billreport.export") }}');
        form.attr('target', '_blank');
        form.submit();
        setTimeout(function() {
            form.attr('action', originalAction);
            form.removeAttr('target');
        }, 100);
    });
});
</script>
@endsection
