@extends('template.app')

@section('meta') @endsection
@section('title') Customer Outstanding Report @endsection

@section('styles')
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/jquery.dataTables.min.css">
    <style>
        .table-responsive {
            overflow-x: auto;
            max-width: 100%;
        }

        .dataTables_scrollHeadInner,
        .dataTables_scrollBody table {
            width: 100% !important;
        }

        .dataTables_scrollHead {
            overflow: hidden;
        }
        .dataTables_scrollBody {
            max-height: 400px; 
            overflow-y: auto;
        }


        #data-table {
            width: 100% !important;
            border-collapse: collapse;
        }

        #data-table thead th {
            white-space: nowrap;
        }

        #data-table_wrapper {
            width: 100%;
            overflow-x: auto;
        }

        td, th {
            border: 1px solid #dddddd;
            text-align: left;
            padding: 8px;
        }

        tr:nth-child(even) {
            background-color: #313762;
        }
        .daterangepicker {
            background-color: #fff !important;
            color: #000 !important;
            border: 1px solid #ccc;
            z-index: 9999;
        }

        .daterangepicker .calendar-table,
        .daterangepicker td,
        .daterangepicker th {
            background-color: #fff !important;
            color: #000 !important;
        }

        .daterangepicker td.active,
        .daterangepicker td.active:hover {
            background-color: #007bff !important;
            color: #fff !important;
        }

        .daterangepicker .drp-buttons .btn {
            background-color: #007bff;
            color: #fff;
        }

        .daterangepicker .drp-buttons .btn:hover {
            background-color: #0056b3;
        }

        .width_150 {
            width: 150px;
        }
        .width_200 {
            width: 200px;
        }
        .width_250 {
            width: 250px;
        }
        .width_300 {
            width: 300px;
        }

    </style>
@endsection

@section('content')
<div class="page-breadcrumb">
    <div class="row">
        <div class="col-7 align-self-center">
            <h4 class="page-title text-truncate text-dark font-weight-medium mb-1">Customer Outstanding Report</h4>
            <div class="d-flex align-items-center">
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb m-0 p-0">
                        <li class="breadcrumb-item"><a href="{{ route('dashboard') }}" class="text-muted">Dashboard</a></li>
                        <li class="breadcrumb-item"><a href="{{ route('allReport') }}" class="text-muted">Mis Report</a></li>
                        <li class="breadcrumb-item text-muted active" aria-current="page">Customer Outstanding Report</li>
                    </ol>
                </nav>
            </div>
        </div>
        <div class="col-5 align-self-center">
            <div class="customize-input float-right">
                <button class="btn waves-effect waves-light btn-rounded btn-outline-primary pull-right" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
                    Export
                </button>
            </div>
        </div>
        <div class="col-sm-8"></div>
        <div class="col-sm-4">
            <div class="col-md-12 align-self-center collapse" id="collapseExample">
                <div class="customize-input float-right">
                    <form action="{{ route('customeroutstandingExport') }}" method="get">
                        @csrf
                        <div class="row">
                            <div class="form-group col-md-6">
                                <select name="slug" class="form-control" required>
                                    <option value="">Select Status</option>
                                    <option value="all">All</option>
                                </select>
                            </div>
                            <div class="form-group col-md-6">
                                <button class="btn btn-primary" type="submit">Submit</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="container-fluid">
  <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-body table-responsive" style="text-align: center;">
                   <table class="table table-bordered data-table tables" id="data-table"> 
    <thead>
        <!-- Column Headings -->
        <tr>
            <th>No</th>
            <th>Date</th>
            <th>Location</th>
            <th>Team Leader</th>
            <th>Customer Name (Bill To)</th>
            <th>Model</th>
            <th>Variant</th>
            <th>VIN Number</th>
            <th>Invoice No.</th>
            <th>Invoice Date</th>
            <th>On Road Price (A)</th>
            <th>Discount (G(-))</th>
            <th>On Road after dis (A-B=C)</th>
            <th>Booking Amount (B(+))</th>
            <th>DP Amount Received (C(+))</th>
            <th>Net Disbursement Amount (D(+))</th>
            <th>Exchange Amount (E(+))</th>
            <th>Total Received Amount (B+C+D+E=F)</th>
            <th>Access / Sort Amount</th>
            <th>Due Amount (A-H=I)</th>
            <th>OBF Status</th>
            <!--<th>GST No</th>-->
            <!--<th>Customer Name (Ship To)</th>-->
            <!--<th>KEC Name</th>-->
            <!--<th>Exterior Color</th>-->
            <!--<th>Finance Amount</th>-->
            <!--<th>Net Amount Received (F-G=H)</th>-->
            <!--<th>OBF Approval Status</th>-->
        </tr>

        <!-- Filters Row -->
        <tr>
            <th></th>

            <!-- Date -->
            <th>
                <div class="search-box-container datatable-form-filter width_150">
                    <div class="form-group">
                        <!-- ADDED id="booking_date" so JS selector $('#booking_date') works -->
                        <input id="booking_date" type="text" name="booking_date" value="{{ request()->get('booking_date', '') }}" class="form-control" placeholder="DD-MM-YYYY to DD-MM-YYYY">
                    </div>
                </div>
            </th>

            <!-- Location -->
            <th>
                <div class="search-box-container datatable-form-filter width_300">
                    <input type="text" name="branch_name" value="{{ request()->get('branch_name', '') }}" class="form-control text-capitalize" placeholder="Location">
                </div>
            </th>

            <!-- Team Leader -->
            <th>
                <div class="search-box-container datatable-form-filter width_200">
                    <input type="text" name="team_name" value="{{ request()->get('team_name', '') }}" class="form-control text-capitalize" placeholder="Team Leader">
                </div>
            </th>

            <!-- Customer Name (Bill To) -->
            <th>
                <div class="search-box-container datatable-form-filter width_300">
                    <input type="text" name="customer_name" value="{{ request()->get('customer_name', '') }}" class="form-control text-capitalize" placeholder="Customer Name">
                </div>
            </th>

            <!-- Model -->
            <th>
                <div class="search-box-container datatable-form-filter width_150">
                    <input type="text" name="product" value="{{ request()->get('product', '') }}" class="form-control text-capitalize" placeholder="Model">
                </div>
            </th>

            <!-- Variant -->
            <th>
                <div class="search-box-container datatable-form-filter width_200">
                    <input type="text" name="car_varient_name" value="{{ request()->get('car_varient_name', '') }}" class="form-control text-capitalize" placeholder="Variant">
                </div>
            </th>

            <!-- VIN Number -->
            <th>
                <div class="search-box-container datatable-form-filter width_200">
                    <input type="text" name="vin_number" value="{{ request()->get('vin_number', '') }}" class="form-control" placeholder="VIN Number">
                </div>
            </th>

            <!-- Invoice No -->
            <th>
                <div class="search-box-container datatable-form-filter width_150">
                    <input type="text" name="invoice_no" value="{{ request()->get('invoice_no', '') }}" class="form-control" placeholder="Invoice No">
                </div>
            </th>

            <!-- Invoice Date -->
            <th>
                <div class="search-box-container datatable-form-filter width_150">
                    <input type="text" name="invoice_date" value="{{ request()->get('invoice_date', '') }}" class="form-control" placeholder="Invoice Date">
                </div>
            </th>

            <!-- On Road Price -->
            <th>
                <div class="search-box-container datatable-form-filter width_150">
                    <input type="text" name="on_road_price" value="{{ request()->get('on_road_price', '') }}" class="form-control" placeholder="On Road Price">
                </div>
            </th>

            <!-- Discount -->
            <th>
                <div class="search-box-container datatable-form-filter width_150">
                    <input type="text" name="finance_discount" value="{{ request()->get('finance_discount', '') }}" class="form-control" placeholder="Discount">
                </div>
            </th>

            <!-- On Road After Discount -->
            <th></th>

            <!-- Booking Amount -->
            <th>
                <div class="search-box-container datatable-form-filter width_150">
                    <input type="text" name="booking_amount" value="{{ request()->get('booking_amount', '') }}" class="form-control" placeholder="Booking Amount">
                </div>
            </th>

            <!-- DP Amount -->
            <th>
                <div class="search-box-container datatable-form-filter width_150">
                    <input type="text" name="dp_amount" value="{{ request()->get('dp_amount', '') }}" class="form-control" placeholder="DP Amount">
                </div>
            </th>

            <!-- Net Disbursement -->
            <th>
                <div class="search-box-container datatable-form-filter width_150">
                    <input type="text" name="net_disbusment" value="{{ request()->get('net_disbusment', '') }}" class="form-control" placeholder="Net Disbursement">
                </div>
            </th>

            <!-- Exchange Amount -->
            <th>
                <div class="search-box-container datatable-form-filter width_150">
                    <input type="text" name="total_exchange_amount" value="{{ request()->get('total_exchange_amount', '') }}" class="form-control" placeholder="Exchange">
                </div>
            </th>

            <!-- Total Received -->
            <th>
                <div class="search-box-container datatable-form-filter width_150">
                    <input type="text" name="final_total" value="{{ request()->get('final_total', '') }}" class="form-control" placeholder="Total Received">
                </div>
            </th>

            <!-- Access / Sort -->
            <th>
                <div class="search-box-container datatable-form-filter width_150">
                    <input type="text" name="access_sort_amount" value="{{ request()->get('access_sort_amount', '') }}" class="form-control" placeholder="Access/Sort">
                </div>
            </th>

            <!-- Due Amount -->
            <th>
                <div class="search-box-container datatable-form-filter width_150">
                    <input type="text" name="due_amount" value="{{ request()->get('due_amount', '') }}" class="form-control" placeholder="Due Amount">
                </div>
            </th>

            <!-- OBF Status -->
            <th>
                <select name="status" class="form-control text-capitalize">
                    <option value="">-- Select --</option>
                    <option value="pending">Pending</option>
                    <option value="accepted">Accepted</option>
                    <option value="completed">Completed</option>
                    <option value="cancel">Cancel</option>
                </select>
            </th>

            <!-- GST -->
            <!--<th>-->
            <!--    <div class="search-box-container datatable-form-filter width_150">-->
            <!--        <input type="text" name="gst" value="{{ request()->get('gst', '') }}" class="form-control" placeholder="GST No">-->
            <!--    </div>-->
            <!--</th>-->

            <!-- Customer Name (Ship To) -->
            <!--<th>-->
            <!--    <div class="search-box-container datatable-form-filter width_300">-->
            <!--        <input type="text" name="ship_to_customer_name" value="{{ request()->get('ship_to_customer_name', '') }}" class="form-control text-capitalize" placeholder="Ship To">-->
            <!--    </div>-->
            <!--</th>-->

            <!-- KEC Name -->
            <!--<th>-->
            <!--    <div class="search-box-container datatable-form-filter width_200">-->
            <!--        <input type="text" name="sales_person_name" value="{{ request()->get('sales_person_name', '') }}" class="form-control text-capitalize" placeholder="KEC Name">-->
            <!--    </div>-->
            <!--</th>-->

            <!-- Exterior Color -->
            <!--<th>-->
            <!--    <div class="search-box-container datatable-form-filter width_200">-->
            <!--        <input type="text" name="exterior_color" value="{{ request()->get('exterior_color', '') }}" class="form-control text-capitalize" placeholder="Color">-->
            <!--    </div>-->
            <!--</th>-->

            <!-- Finance Amount -->
            <!--<th>-->
            <!--    <div class="search-box-container datatable-form-filter width_150">-->
            <!--        <input type="text" name="loan_amount" value="{{ request()->get('loan_amount', '') }}" class="form-control" placeholder="Finance Amount">-->
            <!--    </div>-->
            <!--</th>-->

            <!-- Net Amount Received -->
            <!--<th>-->
            <!--    <div class="search-box-container datatable-form-filter width_150">-->
            <!--        <input type="text" name="net_total" value="{{ request()->get('net_total', '') }}" class="form-control" placeholder="Net Amount">-->
            <!--    </div>-->
            <!--</th>-->

            <!-- OBF Approval Status -->
            <!--<th>-->
            <!--    <select name="approval_status" class="form-control text-capitalize">-->
            <!--        <option value="">-- Select --</option>-->
            <!--        <option value="pending">Pending</option>-->
            <!--        <option value="obf_tl_accepted">OBF TL Accepted</option>-->
            <!--        <option value="obf_gm_accepted">OBF GM Accepted</option>-->
            <!--        <option value="obf_accountant_rejected">OBF Acc. Rejected</option>-->
            <!--    </select>-->
            <!--</th>-->
        </tr>
    </thead>

    <!-- Footer Totals -->
    <tfoot>
        <tr>
            <!-- Fix: total columns must equal table columns (21). Here we use colspan to group first 10 and then provide one <th> per remaining column -->
            <th colspan="10" style="text-align:right">Total:</th>
            <!-- These <th> correspond to columns with indexes 10..19 (10 items) -->
            <th></th> {{-- index 10 on_road_price --}}
            <th></th> {{-- index 11 finance_discount --}}
            <th></th> {{-- index 12 on_road_after_discount (dynamic) --}}
            <th></th> {{-- index 13 booking_amount --}}
            <th></th> {{-- index 14 dp_amount --}}
            <th></th> {{-- index 15 net_disbusment --}}
            <th></th> {{-- index 16 total_exchange_amount --}}
            <th></th> {{-- index 17 final_total --}}
            <th></th> {{-- index 18 access_sort_amount --}}
            <th></th> {{-- index 19 due_amount --}}
            <!-- last column (index 20) -->
            <th></th> {{-- index 20 status --}}
        </tr>
    </tfoot>
</table>

                </div>
            </div>
        </div>
@endsection

@section('scripts')
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
    <script src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>


    <script type="text/javascript">
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
    </script>

    <script type="text/javascript">
        $(document).ready(function() {
            // NOTE: booking_date input now has id="booking_date" in the markup above
            $('#booking_date').daterangepicker({
                autoUpdateInput: false,
                locale: {
                    format: 'DD-MM-YYYY',
                    cancelLabel: 'Clear'
                }
            });

            $('#booking_date').on('apply.daterangepicker', function(ev, picker) {
                $(this).val(picker.startDate.format('DD-MM-YYYY') + ' to ' + picker.endDate.format('DD-MM-YYYY'));
                $('#data-table').DataTable().draw();
            });

            $('#booking_date').on('cancel.daterangepicker', function(ev, picker) {
                $(this).val('');
                $('#data-table').DataTable().draw();
            });

            $('.js-example-basic-single').select2();

                var tableColumns = [
            { data: 'id', name: 'id', class: 'text-center', title: 'No.', orderable: false },
            { data: 'booking_date', name: 'booking_date', class: 'text-center', title: 'Date' },
            { data: 'branch_name', name: 'branch_name', class: 'text-center', title: 'Location' },
            { data: 'team_name', name: 'team_name', class: 'text-center', title: 'Team Leader' },
            { data: 'customer_name', name: 'customer_name', class: 'text-center', title: 'Customer Name (Bill To)' },
            { data: 'product', name: 'product', class: 'text-center', title: 'Model' },
            { data: 'car_varient_name', name: 'car_varient_name', class: 'text-center', title: 'Variant' },
            { data: 'vin_number', name: 'vin_number', class: 'text-center', title: 'VIN Number' },
            { data: 'invoice_no', name: 'invoice_no', class: 'text-center', title: 'Invoice No.' },
            { data: 'invoice_date', name: 'invoice_date', class: 'text-center', title: 'Invoice Date' },
            { data: 'on_road_price', name: 'on_road_price', class: 'text-center', title: 'On Road Price (A)' },
            { data: 'finance_discount', name: 'finance_discount', class: 'text-center', title: 'Discount (G(-))' },

            // ✅ Dynamically calculated column
            {
                data: null,
                class: 'text-center',
                title: 'On Road after dis (A-B=C)',
                render: function (data, type, row) {
                    let a = parseFloat(row.on_road_price) || 0;
                    let b = parseFloat(row.finance_discount) || 0;
                    let c = a - b;
                    return '₹ ' + c.toLocaleString();
                }
            },

            { data: 'booking_amount', name: 'booking_amount', class: 'text-center', title: 'Booking Amount (B(+))' },
            { data: 'dp_amount', name: 'dp_amount', class: 'text-center', title: 'DP Amount Received (C(+))' },
            { data: 'net_disbusment', name: 'net_disbusment', class: 'text-center', title: 'Net Disbursement Amount (D(+))' },
            { data: 'total_exchange_amount', name: 'total_exchange_amount', class: 'text-center', title: 'Exchange Amount (E(+))' },
            { data: 'final_total', name: 'final_total', class: 'text-center', title: 'Total Received (F)' },
            { data: 'access_sort_amount', name: 'access_sort_amount', class: 'text-center', title: 'Access / Sort Amount' },
            { data: 'due_amount', name: 'due_amount', class: 'text-center', title: 'Due Amount (A-H=I)' },
            { data: 'status', name: 'status', class: 'text-center', title: 'OBF Status' },
            // { data: 'gst', name: 'gst', class: 'text-center', title: 'GST No' },
            // { data: 'ship_to_customer_name', name: 'ship_to_customer_name', class: 'text-center', title: 'Customer Name (Ship To)' },
            // { data: 'sales_person_name', name: 'sales_person_name', class: 'text-center', title: 'KEC Name' },
            // { data: 'exterior_color', name: 'exterior_color', class: 'text-center', title: 'Exterior Color' },
            // { data: 'loan_amount', name: 'loan_amount', class: 'text-center', title: 'Finance Amount' },
            // { data: 'net_total', name: 'net_total', class: 'text-center', title: 'Net Amount Received (F-G=H)' },
            // { data: 'approval_status', name: 'approval_status', class: 'text-center', title: 'OBF Approval Status' },
        ];

            (function(window, $) {
                window.LaravelDataTables = window.LaravelDataTables || {};
                window.LaravelDataTables["dataTableBuilder"] = $("#data-table").DataTable({
                    processing: true,
                    serverSide: true,
                    language: {
                        "info": "_START_ - _END_ of _TOTAL_",
                        "lengthMenu": "_MENU_ ",
                        "infoFiltered": ""
                    },
                    scrollX: true,
                    scrollY: '750px',
                    scrollCollapse: true,
                    paging: true,
                    fixedHeader: false,
                    searching: false,
                    autoWidth: false,
                    bSortCellsTop : true,
                    ajax: {
                        url: '{!! route("customeroutstandingfetch") !!}',
                        method: "POST",
                       data: function (d) {
                    $(".datatable-form-filter").find("input, select").each(function () {
                        d[$(this).attr("name")] = $(this).val();
                    });
                },
                        error : function(d) {}
                    },
                    columns: tableColumns,
                    lengthMenu: [
                        [25, 50,100, -1 ],['25', '50','100', 'Show all' ]
                    ],
                    order: [ [0,'DESC'] ],
                    responsive: true,
                    colReorder:{
                        enable: false,
                    },
                    dom: '<"top"f>rt<"bottom"ipl><"clear">',
                    fnInitComplete: function(settings, json) {
                        jQuery('table.table input:checkbox').map(function() {
                            if(jQuery(this).prop("checked") != true){
                                var column = table.column( jQuery(this).attr('data-column') );
                                column.visible(false);
                            }
                        });
                    },
                    footerCallback: function (row, data, start, end, display) {
                        var api = this.api();

                        function intVal(i) {
                            return typeof i === 'string' ?
                                parseFloat(i.replace(/[\₹,]/g, '')) || 0 :
                                typeof i === 'number' ? i : 0;
                        }

                        // ✅ Define which column indexes to total (match tableColumns indexes)
                        // indexes: 10:on_road_price, 11:finance_discount, 12:on_road_after_discount (dynamic),
                        // 13:booking_amount, 14:dp_amount, 15:net_disbusment, 16:total_exchange_amount,
                        // 17:final_total, 18:access_sort_amount, 19:due_amount
                        const totalColumns = [10,11,12,13,14,15,16,17,18,19];

                        totalColumns.forEach(function(index) {
                            var pageTotal = api
                                .column(index, { page: 'current' })
                                .data()
                                .reduce(function (a, b) {
                                    return intVal(a) + intVal(b);
                                }, 0);

                            // write total into footer cell for that column
                            $(api.column(index).footer()).html('₹ ' + pageTotal.toLocaleString());
                        });
                    },
                    pageLength: 25,
                });
            })(window, jQuery);

            $("#min").flatpickr({ onSelect: function () { window.LaravelDataTables["dataTableBuilder"].draw(); }, changeMonth: true, changeYear: true });

            $(document).on("change", "#min", function () {
                window.LaravelDataTables["dataTableBuilder"].draw();
            });



        jQuery('.datatable-form-filter input').on('keyup', function (e) {
            if(jQuery(this).val().length >= 3 || e.keyCode == 13 || !jQuery(this).val()) {
                window.LaravelDataTables["dataTableBuilder"].draw();
                e.preventDefault();
            }
        });

        jQuery('.datatable-form-filter select').on('change', function (e) {
            window.LaravelDataTables["dataTableBuilder"].draw();
            e.preventDefault();
        });

        jQuery('input:checkbox[name="name_sort_asc"],input:checkbox[name="name_sort_desc"]').on('click', function (e) {
            window.LaravelDataTables["dataTableBuilder"].draw();
            e.preventDefault();
        });
    }); 
    </script>
@endsection
