<?php include '../header.php'; ?> 
<?php include '../sidemenu.php'; ?> 
<style>
.table-responsive {
    overflow: visible !important;
}

.dropdown {
    position: relative !important;
}

</style>
<div class="page-header d-print-none">
    <div class="container-xl">
        <div class="row g-2 align-items-center">
            <div class="col d-flex justify-content-between">
                <h2 class="page-title">Return Report</h2>
            </div>
        </div>
    </div>
</div>

<div class="page-body">
    <div class="container-xl">
        <div class="row row-cards">
            <div class="col-12">
                <div class="row">
                    <div class="col-3 mb-3 row">
                        <label class="col-4 col-form-label text-end">Return From</label>
                        <div class="col">
                            <input type="text" class="flatpickr flatpickr-input active form-control" id="dateFrom" required>
                        </div>
                    </div>
                    <div class="col-3 mb-3 row">
                        <label class="col-4 col-form-label text-end">Return To</label>
                        <div class="col">
                            <input type="text" class="flatpickr flatpickr-input active form-control" id="dateTo" required>
                        </div>
                    </div>
                </div>
                <div class="card">
                    <div class="card-body">
                        <div class="export-buttons-container" style="margin-bottom: 10px;">
                            <button id="exportCSV" class="btn btn-outline-primary">Export to CSV</button>
                            <button id="exportExcel" class="btn btn-outline-primary">Export to Excel</button>
                            <button id="exportPDF" class="btn btn-outline-primary">Export to PDF</button>
                            <button id="printTable" class="btn btn-outline-primary">Print Table</button>
                        </div>
                        <div class="table-responsive">
                            <table id="myTable" class="table card-table table-vcenter text-nowrap datatable" >
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Invoice ID</th>
                                        <th style="text-align: left;">Booking No.<span class="searchable">🔍</span></th>
                                        <th style="text-align: left;">Driver Name<span class="searchable">🔍</span></th>
                                        <th style="text-align: left;">Vehicle No.<span class="searchable">🔍</span></th>
                                        <th>Customer Name<span class="searchable">🔍</span></th>
                                        <th>Pickup</th>
                                        <th>Return</th>
                                        <th>Total Gross</th>
                                        <th>VAT (7%)</th>
                                        <th>Balance</th>
                                        <th>Driver ID</th>
                                        <!-- <th class="w-1">Action</th> -->
                                    </tr>
                                </thead>
                                <tbody>

                                </tbody>
                                <tfoot>
                                    <tr>
                                        <th colspan="8">Total</th>
                                        <th id="totalCharges">0.00</th>
                                        <th id="totalAgentFee">0.00</th>
                                        <th id="totalBalance">0.00</th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                        <!-- <div style="display: flex; flex-direction: column; align-items: flex-end; font-weight: bold;">
                            <div style="display: flex; justify-content: space-between; width: 300px;">
                                <span>Total Charges</span>
                                <span><span id="totalCharges">0.00</span></span>
                            </div>
                            <div style="display: flex; justify-content: space-between; width: 300px;">
                                <span>Total Tax Charges</span>
                                <span><span id="totalAgentFee">0.00</span></span>
                            </div>
                            <div style="display: flex; justify-content: space-between; width: 300px;">
                                <span>Total Balance</span>
                                <span><span id="totalBalance">0.00</span></span>
                            </div>
                        </div> -->
                        <div id="groupedTotals" style="display:none;"></div>
                    </div>
                </div>

                <!-- Modal Structure -->
                <div class="modal fade" id="checkinModal" tabindex="-1" aria-labelledby="checkinModalLabel" aria-hidden="true">
                    <div class="modal-dialog modal-xl">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="checkinModalLabel">Check-Out Details</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Date</th>
                                            <th>Rental Rate</th>
                                            <th>Add-on Qty</th>
                                            <th>Add-on Rate</th>
                                            <th>Extra Driver</th>
                                            <th>Extra Driver Fee</th>
                                            <th>Total</th>
                                        </tr>
                                    </thead>
                                    <tbody id="modalTableBody">
                                        <!-- Rows will be added here dynamically -->
                                    </tbody>
                                </table>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                            </div>
                        </div>
                    </div>
                </div>



            </div>
        </div>
    </div>
</div>

 
<?php include '../footer.php'; ?>

<script>
	var today = new Date().toISOString().split('T')[0];
$(function() {
	flatpickr("#dateFrom", {
        dateFormat: "Y-m-d", 
        defaultDate: today,  
        maxDate: today,      
    });
	flatpickr("#dateTo", {
        dateFormat: "Y-m-d", 
        defaultDate: today,  
        maxDate: today,      
    });
    getAll();
});

$("#dateFrom, #dateTo").change(function() {
    getAll();
});


function getAll() {
    var df = $("#dateFrom").val();
    var dt = $("#dateTo").val();

    // Destroy previous DataTable instance if it exists
    $('#myTable').DataTable().destroy();

    var table = $('#myTable').DataTable({
        ajax: {
            url: APP_URL + "api/check_out/search.php",
            method: "GET",
            dataType: "json",
            data: {
                df: df,
                dt: dt
            },
            dataSrc: function(json) {
                return json.records;
            }
        },
        columns: [
            { data: 0, visible: false },
            { data: 1 },
            { data: 2 },
            { data: 3 },
            { data: 4 },
            { data: 5 },
            { data: 6 },
            { data: 7 },
            { data: 8 },
            { data: 9 },
            { data: 10 },
            { data: 11, visible: false },
        ],

        columnDefs: [
            {
                targets: 4,
                createdCell: function(td, cellData, rowData, row, col) {
                    $(td).css({
                        'text-align': 'left',
                        'cursor': 'pointer',
                        'color': '#007bff',
                        'text-decoration': 'underline'
                    });
                    $(td).attr('title', 'Click to view details');
                    $(td).on('click', function() {
                        $.ajax({
                            url: APP_URL + "api/check_in/get_one_for_checkin_report.php",
                            type: "POST",
                            contentType: "application/json",
                            data: JSON.stringify({ checkin_id: rowData[0] })
                        }).done(function(data) {
                            $("#modalTableBody").empty();
                            data.records.forEach(function(record) {
                                $("#modalTableBody").append(`
                                    <tr>
                                        <td>${record.date}</td>
                                        <td>${parseFloat(record.room_rate).toLocaleString(undefined, { minimumFractionDigits: 2 })}</td>
                                        <td>${record.extra_bed}</td>
                                        <td>${parseFloat(record.extra_bed_rate).toLocaleString(undefined, { minimumFractionDigits: 2 })}</td>
                                        <td>${record.extra_person}</td>
                                        <td>${parseFloat(record.extra_person_rate).toLocaleString(undefined, { minimumFractionDigits: 2 })}</td>
                                        <td>${parseFloat(record.total).toLocaleString(undefined, { minimumFractionDigits: 2 })}</td>
                                    </tr>
                                `);
                            });
                            $("#checkinModal").modal("show");
                        });
                    });
                }
            }
        ],

        paging: true,
        scrollX: true,
        language: {
            emptyTable: "No records found",
            info: "Showing _START_ to _END_ of _TOTAL_ entries",
            lengthMenu: "Show _MENU_ entries",
            search: "Search:",
            zeroRecords: "No records found"
        },
        lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
        buttons: [
            {
                extend: 'csv',
                text: 'Export to CSV',
                className: 'buttons-csv',
                filename: 'ReturnReport ' + df + ' to ' + dt,
                exportOptions: {
                    columns: ':visible',
                    modifier: {
                    page: 'all',  // Include all pages
                    search: 'none' // Don't filter by search
                }
                }
            },
            {
                extend: 'excel',
                text: 'Export to Excel',
                className: 'buttons-excel',
                exportOptions: {
                    columns: ':visible',
                    modifier: {
                    page: 'all',  // Include all pages
                    search: 'none' // Don't filter by search
                }
                }
            },
            {
                extend: 'pdf',
                text: 'Export to PDF',
                className: 'buttons-pdf',
                exportOptions: {
                    columns: ':visible',
                    modifier: {
                    page: 'all',  // Include all pages
                    search: 'none' // Don't filter by search
                }
                }
            },
            {
                extend: 'print',
                text: 'Print Table',
                className: 'buttons-print',
                exportOptions: {
                    columns: ':visible',
                    modifier: {
                    page: 'all',  // Include all pages
                    search: 'none' // Don't filter by search
                }
                }
            }
        ],
        drawCallback: function(settings) {
            let api = this.api();
            let data = api.rows({ search: 'applied' }).data();  // Get filtered data

            let totalCharges = 0;
            let totalAgentFee = 0;
            let totalBalance = 0;

            // Loop through the filtered data and calculate totals
            data.each(function(record) {
                let charge = parseFloat(record[8] || 0);  // Assuming total_charges is at index 8
                let commission = parseFloat(record[9] || 0);  // Assuming commission is at index 9

                // Apply the formulas
                totalCharges += charge;
                totalAgentFee += commission;
                totalBalance += charge - commission;
            });

            // Update the totals on the frontend
            $("#totalCharges").text(totalCharges.toLocaleString(undefined, { minimumFractionDigits: 2 }));
            $("#totalAgentFee").text(totalAgentFee.toLocaleString(undefined, { minimumFractionDigits: 2 }));
            $("#totalBalance").text(totalBalance.toLocaleString(undefined, { minimumFractionDigits: 2 }));

            let groupedData = {};  // Object to store sums and names grouped by record[11]

            // Loop through the filtered data and group by record[11]
            data.each(function(record) {
                let groupKey = record[11];  // Group by record[11]
                let commission = parseFloat(record[9] || 0);  // Assuming commission is at index 9
                let name = record[3];  // Assuming name is at index 3

                // If the groupKey doesn't exist in groupedData, initialize it
                if (!groupedData[groupKey]) {
                    groupedData[groupKey] = {
                        totalCommission: 0,
                        name: name
                    };
                }

                // Add the commission to the group's total commission
                groupedData[groupKey].totalCommission += commission;
            });

            // Now, display the results
            let outputHtml = '';  // String to hold the HTML output

            // Loop through the grouped data and display the results
            $.each(groupedData, function(groupKey, groupData) {
                outputHtml += '<div>';
                outputHtml += '<strong>' + groupData.name + '</strong>';
                outputHtml += ' - Total Driver Fee: ' + groupData.totalCommission.toLocaleString(undefined, { minimumFractionDigits: 2 }) + '<br>';
                outputHtml += '</div>';
            });

            // Update the frontend with the grouped totals
            $("#groupedTotals").html(outputHtml);
        }
    });
    // Manually handle custom export buttons
    $('#exportCSV').on('click', function() {
        table.button('.buttons-csv').trigger();
    });

    $('#exportExcel').on('click', function() {
        table.button('.buttons-excel').trigger();
    });

    $('#exportPDF').on('click', function() {
        table.button('.buttons-pdf').trigger();
    });

    $('#printTable').on('click', function() {
        table.button('.buttons-print').trigger();
    });
}





// Function to show the modal
function showModal(roomNo, rowData) {
    // Example: Populate modal content
    $("#modalRoomNo").text("Vehicle No: " + roomNo);
    // $("#modalDetails").text(JSON.stringify(rowData)); // Display additional details if needed

    // // Show the modal
    $("#myModal").modal('show');
}


</script>
