@extends('layouts.app')
@section('title', 'Invoice & Payment Status Report')

@section('content')
<section class="content-header no-print">
    <h1><i class="fa fa-file-invoice"></i> Invoice & Payment Status Report</h1>
</section>

<section class="content no-print">
    <div class="box box-solid box-primary" id="accordion">
        <div class="box-header with-border" style="cursor: pointer;">
            <h3 class="box-title">
                <a data-toggle="collapse" data-parent="#accordion" href="#collapseFilter">
                    <i class="fa fa-filter" aria-hidden="true"></i> Filters
                </a>
            </h3>
        </div>
        <div id="collapseFilter" class="panel-collapse active collapse in" aria-expanded="true">
            <div class="box-body">
                <form id="invoice_payment_filter_form" method="GET" action="{{ route('reports.invoice_payment_status') }}">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="form-group">
                                <label for="date_range">Date Range:</label>
                                <input type="text" name="date_range" id="date_range" class="form-control" readonly placeholder="Select a date range" value="{{ request('date_range') ?: 'Last 30 Days' }}">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label for="location_id">Business Location:</label>
                                <select name="location_id" id="location_id" class="form-control select2">
                                    <option value="">All Locations</option>
                                    @foreach($business_locations as $id => $name)
                                        <option value="{{ $id }}" {{ request('location_id') == $id ? 'selected' : '' }}>{{ $name }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label for="customer_id">Customer:</label>
                                <select name="customer_id" id="customer_id" class="form-control select2">
                                    <option value="">All Customers</option>
                                    @foreach($customers as $id => $name)
                                        <option value="{{ $id }}" {{ request('customer_id') == $id ? 'selected' : '' }}>{{ $name }}</option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label for="payment_status">Payment Status:</label>
                                <select name="payment_status" id="payment_status" class="form-control select2">
                                    <option value="">All Statuses</option>
                                    <option value="paid" {{ request('payment_status') == 'paid' ? 'selected' : '' }}>Paid</option>
                                    <option value="partial" {{ request('payment_status') == 'partial' ? 'selected' : '' }}>Partially Paid</option>
                                    <option value="due" {{ request('payment_status') == 'due' ? 'selected' : '' }}>Due</option>
                                    <option value="overdue" {{ request('payment_status') == 'overdue' ? 'selected' : '' }}>Overdue</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label for="invoice_type">Invoice Type:</label>
                                <select name="invoice_type" id="invoice_type" class="form-control select2">
                                    <option value="">All Types</option>
                                    <option value="final" {{ request('invoice_type') == 'final' ? 'selected' : '' }}>Final</option>
                                    <option value="draft" {{ request('invoice_type') == 'draft' ? 'selected' : '' }}>Draft</option>
                                    <option value="quotation" {{ request('invoice_type') == 'quotation' ? 'selected' : '' }}>Quotation</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <label for="overdue_days">Overdue Days:</label>
                                <select name="overdue_days" id="overdue_days" class="form-control select2">
                                    <option value="">All</option>
                                    <option value="1-7" {{ request('overdue_days') == '1-7' ? 'selected' : '' }}>1-7 Days</option>
                                    <option value="8-30" {{ request('overdue_days') == '8-30' ? 'selected' : '' }}>8-30 Days</option>
                                    <option value="31-90" {{ request('overdue_days') == '31-90' ? 'selected' : '' }}>31-90 Days</option>
                                    <option value="90+" {{ request('overdue_days') == '90+' ? 'selected' : '' }}>90+ Days</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-12 text-right">
                            <button type="submit" class="btn btn-primary"><i class="fa fa-search"></i> Apply Filters</button>
                            <a href="{{ route('reports.invoice_payment_status') }}" class="btn btn-default"><i class="fa fa-refresh"></i> Clear Filters</a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="row" style="margin-top: 20px;">
        <div class="col-md-3">
            <div class="info-box bg-gradient-green">
                <span class="info-box-icon"><i class="fa fa-check-circle"></i></span>
                <div class="info-box-content">
                    <span class="info-box-text">Paid Invoices</span>
                    <span class="info-box-number">{{ $paid_invoices_count }}</span>
                    <span class="info-box-text">{{ number_format($paid_invoices_amount, session('business.currency_precision', 2), session('currency')['decimal_separator'], session('currency')['thousand_separator']) }}</span>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="info-box bg-gradient-yellow">
                <span class="info-box-icon"><i class="fa fa-exclamation-triangle"></i></span>
                <div class="info-box-content">
                    <span class="info-box-text">Overdue Invoices</span>
                    <span class="info-box-number">{{ $overdue_invoices_count }}</span>
                    <span class="info-box-text">{{ number_format($overdue_invoices_amount, session('business.currency_precision', 2), session('currency')['decimal_separator'], session('currency')['thousand_separator']) }}</span>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="info-box bg-gradient-blue">
                <span class="info-box-icon"><i class="fa fa-clock"></i></span>
                <div class="info-box-content">
                    <span class="info-box-text">Due Invoices</span>
                    <span class="info-box-number">{{ $due_invoices_count }}</span>
                    <span class="info-box-text">{{ number_format($due_invoices_amount, session('business.currency_precision', 2), session('currency')['decimal_separator'], session('currency')['thousand_separator']) }}</span>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="info-box bg-gradient-red">
                <span class="info-box-icon"><i class="fa fa-percentage"></i></span>
                <div class="info-box-content">
                    <span class="info-box-text">Collection Rate</span>
                    <span class="info-box-number">{{ number_format($collection_rate, 1) }}%</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Payment Status Summary -->
    <div class="box box-primary" style="margin-top: 20px;">
        <div class="box-header with-border">
            <h3 class="box-title">Payment Status Summary</h3>
        </div>
        <div class="box-body">
            <div class="table-responsive">
                <table id="payment_status_summary_table" class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>Status</th>
                            <th>Count</th>
                            <th>Total Amount</th>
                            <th>Percentage</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($payment_status_summary as $status)
                            <tr>
                                <td>
                                    @if($status->payment_status == 'paid')
                                        <span class="label label-success"><i class="fa fa-check"></i> Paid</span>
                                    @elseif($status->payment_status == 'partial')
                                        <span class="label label-warning"><i class="fa fa-clock"></i> Partial</span>
                                    @elseif($status->payment_status == 'due')
                                        <span class="label label-info"><i class="fa fa-calendar"></i> Due</span>
                                    @else
                                        <span class="label label-danger"><i class="fa fa-exclamation-triangle"></i> Overdue</span>
                                    @endif
                                </td>
                                <td>{{ $status->count }}</td>
                                <td>{{ number_format($status->total_amount, session('business.currency_precision', 2), session('currency')['decimal_separator'], session('currency')['thousand_separator']) }}</td>
                                <td>{{ number_format($status->percentage, 1) }}%</td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="4" class="text-center">
                                    <div class="alert alert-info">
                                        <i class="fa fa-info-circle"></i> No payment status data found for the selected criteria.
                                    </div>
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Invoice Details Table -->
    <div class="box box-primary" style="margin-top: 20px;">
        <div class="box-header with-border">
            <h3 class="box-title">Invoice Details</h3>
        </div>
        <div class="box-body">
            <div class="table-responsive">
                <table id="invoice_details_table" class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>Invoice #</th>
                            <th>Date</th>
                            <th>Customer</th>
                            <th>Location</th>
                            <th>Total Amount</th>
                            <th>Paid Amount</th>
                            <th>Due Amount</th>
                            <th>Payment Status</th>
                            <th>Due Date</th>
                            <th>Overdue Days</th>
                            {{-- <th>Actions</th> --}}
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($invoice_details as $invoice)
                            <tr>
                                <td>{{ $invoice->invoice_no }}</td>
                                <td>{{ \Carbon\Carbon::parse($invoice->transaction_date)->format('Y-m-d') }}</td>
                                <td>{{ $invoice->customer_name }}</td>
                                <td>{{ $invoice->location_name }}</td>
                                <td>{{ number_format($invoice->final_total, session('business.currency_precision', 2), session('currency')['decimal_separator'], session('currency')['thousand_separator']) }}</td>
                                <td>{{ number_format($invoice->paid_amount, session('business.currency_precision', 2), session('currency')['decimal_separator'], session('currency')['thousand_separator']) }}</td>
                                <td>{{ number_format($invoice->due_amount, session('business.currency_precision', 2), session('currency')['decimal_separator'], session('currency')['thousand_separator']) }}</td>
                                <td>
                                    @if($invoice->payment_status == 'paid')
                                        <span class="label label-success"><i class="fa fa-check"></i> Paid</span>
                                    @elseif($invoice->payment_status == 'partial')
                                        <span class="label label-warning"><i class="fa fa-clock"></i> Partial</span>
                                    @elseif($invoice->payment_status == 'due')
                                        <span class="label label-info"><i class="fa fa-calendar"></i> Due</span>
                                    @else
                                        <span class="label label-danger"><i class="fa fa-exclamation-triangle"></i> Overdue</span>
                                    @endif
                                </td>
                                <td>{{ $invoice->due_date ? \Carbon\Carbon::parse($invoice->due_date)->format('Y-m-d') : '-' }}</td>
                                <td>
                                    @if($invoice->overdue_days > 0)
                                        <span class="badge bg-red">{{ $invoice->overdue_days }} days</span>
                                    @else
                                        <span class="text-muted">-</span>
                                    @endif
                                </td>
                                {{-- <td>
                                    <a href="{{ route('sell.show', $invoice->id) }}" class="btn btn-info btn-xs" title="View" target="_blank">
                                        <i class="fa fa-eye"></i>
                                    </a>
                                    <a href="{{ route('sell.edit', $invoice->id) }}" class="btn btn-warning btn-xs" title="Edit">
                                        <i class="fa fa-edit"></i>
                                    </a>
                                    <a href="{{ route('sell.printInvoice', $invoice->id) }}" class="btn btn-primary btn-xs" title="Print" target="_blank">
                                        <i class="fa fa-print"></i>
                                    </a>
                                </td> --}}
                            </tr>
                        @empty
                            <tr>
                                <td colspan="11" class="text-center">
                                    <div class="alert alert-info">
                                        <i class="fa fa-info-circle"></i> No invoice data found for the selected criteria.
                                    </div>
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</section>
@stop

@section('javascript')
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
<script src="https://cdn.jsdelivr.net/npm/moment@2.29.1/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<script>
    $(function() {
        // Date range picker
        $('#date_range').daterangepicker({
            locale: {
                format: 'YYYY-MM-DD',
                separator: ' ~ ',
                applyLabel: 'Apply',
                cancelLabel: 'Cancel',
                fromLabel: 'From',
                toLabel: 'To',
                customRangeLabel: 'Custom',
                weekLabel: 'W',
                daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
                monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
                firstDay: 1
            },
            autoUpdateInput: false,
            showDropdowns: true,
            opens: 'left',
            ranges: {
                'Today': [moment(), moment()],
                'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Last 7 Days': [moment().subtract(6, 'days'), moment()],
                'Last 30 Days': [moment().subtract(29, 'days'), moment()],
                'This Month': [moment().startOf('month'), moment().endOf('month')],
                'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
            }
        });
        
        $('#date_range').on('apply.daterangepicker', function(ev, picker) {
            $(this).val(picker.startDate.format('YYYY-MM-DD') + ' ~ ' + picker.endDate.format('YYYY-MM-DD'));
            $('#invoice_payment_filter_form').submit();
        });
        
        $('#date_range').on('cancel.daterangepicker', function(ev, picker) {
            $(this).val('');
            $('#invoice_payment_filter_form').submit();
        });
        
        $('.select2').select2();
        
        // Auto-submit form when other filters change
        $('#location_id, #customer_id, #payment_status, #invoice_type, #overdue_days').on('change', function() {
            $('#invoice_payment_filter_form').submit();
        });

        // Initialize DataTables
        $('#payment_status_summary_table').DataTable({
            "pageLength": 25,
            "order": [[2, "desc"]], // Sort by total amount descending
            "language": {
                "search": "Search:",
                "lengthMenu": "Show _MENU_ entries",
                "info": "Showing _START_ to _END_ of _TOTAL_ entries",
                "infoEmpty": "Showing 0 to 0 of 0 entries",
                "infoFiltered": "(filtered from _MAX_ total entries)",
                "emptyTable": "No data available in table",
                "zeroRecords": "No matching records found",
                "paginate": {
                    "first": "First",
                    "last": "Last",
                    "next": "Next",
                    "previous": "Previous"
                }
            },
            "dom": '<"row"<"col-sm-6"l><"col-sm-6"f>>rtip',
            "responsive": true,
            "autoWidth": false
        });

        $('#invoice_details_table').DataTable({
            "pageLength": 25,
            "order": [[9, "desc"]], // Sort by overdue days descending
            "language": {
                "search": "Search:",
                "lengthMenu": "Show _MENU_ entries",
                "info": "Showing _START_ to _END_ of _TOTAL_ entries",
                "infoEmpty": "Showing 0 to 0 of 0 entries",
                "infoFiltered": "(filtered from _MAX_ total entries)",
                "emptyTable": "No data available in table",
                "zeroRecords": "No matching records found",
                "paginate": {
                    "first": "First",
                    "last": "Last",
                    "next": "Next",
                    "previous": "Previous"
                }
            },
            "dom": '<"row"<"col-sm-6"l><"col-sm-6"f>>rtip',
            "responsive": true,
            "autoWidth": false
        });
        
        // Using direct links for view and print
    });
</script>
@stop
