<?php include '../header.php'; ?>
<?php include '../sidemenu.php'; ?>

<style>
.table-responsive {
    overflow-x: auto;
    position: relative; /* needed for the table scroll */
}

.table-responsive .dropdown-menu {
    position: absolute; /* allow menu to overflow */
    z-index: 1050;      /* Bootstrap dropdown default z-index */
}

</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">Completed Returns</h2>
            </div>
        </div>
    </div>
</div>

<div class="container" id="alertContainer1"></div>
<div class="page-body">
    <div class="container-xl">
        <div class="row row-cards">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table id="myTable" class="table card-table table-vcenter text-nowrap datatable ">
                                <thead>
                                    <tr>
                                        <th>Booking No.</th>
                                        <th>Invoice No.</th>
                                        <th>Driver Name</th>
                                        <th>Customer Name</th>
                                        <th>Vehicle No.</th>
                                        <th>Pickup</th>
                                        <th>Return</th>
                                        <th>Rental Days</th>
                                        <th>Total</th>
                                        <th>Deposit</th>
                                        <th>Booking Created At</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Dynamic content here -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Deposit Modal -->
<div class="modal fade" id="depositModal" tabindex="-1" aria-labelledby="depositModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="depositModalLabel">Security Deposit</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="depositForm">
                    <div class="mb-3">
                        <label for="depositDate" class="form-label">Date</label>
                        <input type="text" class="form-control" id="depositDate" value="<?php echo date('Y-m-d'); ?>" required>
                    </div>
                    <div class="mb-3">
                        <label for="depositType" class="form-label">Deposit Method</label>
                        <select class="form-control" id="depositType" required>
                            <option value="Online">Online</option>
                            <option value="Cash">Cash</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="depositAmount" class="form-label">Deposit Amount</label>
                        <input type="number" class="form-control" id="depositAmount" required>
                    </div>
                    <input type="hidden" id="reservationId" value="">
                    <input type="hidden" id="roomNo" value="">
                </form>
                <div class="mb-5 table-responsive" style="overflow-y: auto;height: 200px;">
                    <table class="table table-vcenter card-table" id="depositTable">
                        <thead style="position: sticky; top: 0; z-index: 10;">
                            <tr>
                                <th>Date</th>
                                <th>Deposit Type</th>
                                <th>Deposit Amount</th>
                                <th class="w-1"></th>
                            </tr>
                        </thead>
                        <tbody class="stay-grid">
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="confirmDeposit">Submit</button>
            </div>
        </div>
    </div>
</div>

<!-- Reservation Items Modal -->
<div id="detailModal" class="modal fade" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Booking Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p><strong>Date Time:</strong> <span id="dateTimeD"></span></p>
                <p><strong>Booking No:</strong> <span id="reservationNoD"></span></p>
                <p><strong>Invoice No:</strong> <span id="invoiceNoD"></span></p>
                <p><strong>Driver Name:</strong> <span id="agentNameD"></span></p>
                <p><strong>Customer Name:</strong> <span id="guestNameD"></span></p>
                <p><strong>Vehicle No.:</strong> <span id="roomNoD"></span></p>
                <p><strong>Pickup:</strong> <span id="checkInDateD"></span></p>
                <p><strong>Return:</strong> <span id="checkOutDateD"></span></p>
                <p><strong>Remark:</strong> <span id="remarkD"></span></p>
                <!-- <p><strong>Deposit:</strong> <span id="depositD"></span></p> -->
                <!-- <p><strong>Status:</strong> <span id="statusD"></span></p> -->
                <table class="table table-striped" id="reservationItemsTable">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Vehicle No</th>
                            <th>Rental Rate</th>
                            <th>Add-on Qty</th>
                            <th>Add-on Rate</th>
                            <th>Extra Driver</th>
                            <th>Extra Driver Rate</th>
                            <th>Total</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>

                <div class="row mt-3 text-end">
                    <div class="col-auto">
                        <div class="text-end  p-2">
                            <strong>Net Total:</strong> <span id="netTotalD"></span>
                        </div>
                    </div>
                    <!-- <div class="col-auto">
                        <div class="text-end p-2 ">
                            <strong>Deposit:</strong> <span id="depositD"></span>
                        </div>
                    </div>
                    <div class="col-auto">
                        <div class="text-end  p-2">
                            <strong>Balance:</strong> <span id="balanceD"></span>
                        </div>
                    </div> -->
                </div>
            </div>
        </div>
    </div>
</div>




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

<script>
    $(document).ready(function() {
        // document.querySelector('#myTable_filter input[type="search"]').classList.add('form-control', 'form-control-sm');
        flatpickr("#depositDate", {
            dateFormat: "Y-m-d", // Specify the date format
            defaultDate: "<?php echo date('Y-m-d'); ?>", // Set today's date as default
            maxDate: "today", // Optional: restrict the date to today's date or earlier
        });
        getAllCheckOut();
    });

    function getAllCheckOut() {
    $('#myTable').DataTable().destroy(); // Destroy existing DataTable instance

    let table = $('#myTable').DataTable({
        ajax: {
            url: APP_URL + "api/reservation/get_today_check_out.php",
            method: "GET",
            dataType: "json",
            dataSrc: 'records'
        },
        columns: [
            {
                data: 0, // Reservation Number
                render: function(data, type, row) {
                    return `<span class="reservation-number" style="color: blue;cursor:pointer;">${data}</span>`;
                }
            },
            { data: 1 }, // Invoice No
            { data: 2 }, // Driver Name
            { data: 3 }, // Customer Name
            { data: 4 }, // Vehicle No
            { data: 5, className: "text-end" }, // Pickup
            { data: 6, className: "text-end" }, // Return
            { data: 7, className: "text-end" }, // Rental days
            { data: 8, className: "text-end" }, // Total
            { data: 9, className: "text-end" }, // Deposit
            { data: 10, className: "text-end" }, // Created at
            { data: 11, className: "text-end", visible: false }, // Remark
            {
                data: null, className: "text-end",
                render: function (data, type, row) {

                    return `
                        <div class="btn-group dropend">
                            <button type="button" class="btn btn-outline-primary btn-sm dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                                Actions
                            </button>
                            <ul class="dropdown-menu">
                                <li>
                                    <a class="dropdown-item" href="#" onclick="deposit('${row[0]}', '${row[4]}')">Deposit</a>
                                </li>
                                <li>
                                    <a class="dropdown-item text-primary" href="#" onclick="edit('${row[0]}', '${row[4]}')">Edit</a>
                                </li>
                                <li>
                                    <a class="dropdown-item text-danger" href="#" onclick="del('${row[0]}', '${row[4]}', this)">Delete</a>
                                </li>
                            </ul>
                        </div>
                    `;
                }
            }
        ],
        columnDefs: [
            {
                targets: [0, 1, 2, 3, 4], // searchable columns
                searchable: true
            },
            {
                targets: '_all',
                searchable: false
            }
        ],
        "order": [[0, "desc"]],
        paging: true,
        // scrollX: true,
        // scrollY: false,
        // language: {
        //     emptyTable: "No reservations found",
        //     info: "Showing _START_ to _END_ of _TOTAL_ entries",
        //     lengthMenu: "Show _MENU_ entries",
        //     search: "Search:",
        //     zeroRecords: "No matching records found"
        // },
        lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
        createdRow: function (row, data, dataIndex) {
            $(row).attr('data-reservation', JSON.stringify(data));
        },

    });

    // Handle reservation details modal
    $('#myTable tbody').on('click', 'td:nth-child(1)', function () {
        const row = $(this).closest('tr');
        const data = JSON.parse(row.attr('data-reservation'));

        $('#reservationNoD').text(data[0]);
        $('#invoiceNoD').text(data[1]);
        $('#agentNameD').text(data[2]);
        $('#guestNameD').text(data[3]);
        $('#roomNoD').text(data[4]);
        $('#checkInDateD').text(data[5]);
        $('#checkOutDateD').text(data[6]);
        $('#dateTimeD').text(data[10]);
        $('#remarkD').text(data[11]);

        const items = data[12];
        const itemsTableBody = $('#reservationItemsTable tbody');
        itemsTableBody.empty();

        items.forEach(item => {
            const rowHtml = `
                <tr>
                    <td>${item.date}</td>
                    <td>${item.room_no}</td>
                    <td>${item.room_rate}</td>
                    <td>${item.extra_bed}</td>
                    <td>${item.extra_bed_rate}</td>
                    <td>${item.extra_person}</td>
                    <td>${item.extra_person_rate}</td>
                    <td>${item.total}</td>
                </tr>`;
            itemsTableBody.append(rowHtml);
        });
        $('#netTotalD').text(parseFloat(data[8] || 0).toFixed(2));
        $('#detailModal').modal('show');
    });

}

function checkOut(reservationId, roomNo) {
        // Show the SweetAlert confirmation dialog
        Swal.fire({
            title: 'Are you sure?',
            text: `You are about to return vehicle ${roomNo} for booking ${reservationId}.`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, Confirm Return!'
        }).then((result) => {
            if (result.isConfirmed) {
                // Perform the deletion if confirmed
                $.ajax({
                    type: "POST",
                    url: APP_URL + "api/reservation/update_check_out.php",
                    data: JSON.stringify({ reservation_no: reservationId, room_no: roomNo }),
                    success: function(data) {
                        if (data.message === "updated") {
                            getAllCheckOut();
                            showAlert("Return completed successfully!", "success");
                        } else {
                            showAlert("An error occurred on the server!", "error");
                        }
                    },
                    error: function() {
                        showAlert("An error occurred while saving!", "error");
                    }
                });
            }
        });
    }

    // function checkIn(reservationId, roomNo) {
    //     const url = `reserve_check_in.php?reservationNo=${reservationId}&roomNo=${roomNo}`;
    //     window.location.href = url; // This will navigate in the same tab
    // }

    function edit(reservationNo, roomNo) {
        const url = `edit_return.php?reservationNo=${reservationNo}&roomNo=${roomNo}`;
        window.location.href = url; // This will navigate in the same tab
    }


    function del(reservationNo, roomNo) {
        // Show the SweetAlert confirmation dialog
        Swal.fire({
            title: 'Are you sure?',
            text: `You are about to delete the return record for vehicle ${roomNo}.`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                // Perform the deletion if confirmed
                $.ajax({
                    type: "POST",
                    url: APP_URL + "api/check_out/update_check_out.php",
                    data: JSON.stringify({ room_no: roomNo, reservation_no: reservationNo }),
                    success: function(data) {
                        if (data.message === "updated") {
                            getAllCheckOut();
                            // Optionally, you could remove the row from the table here
                            showAlert("Return record deleted successfully!", "success");
                        } else {
                            showAlert("An error occurred on the server!", "error");
                        }
                    },
                    error: function() {
                        showAlert("An error occurred while saving!", "error");
                    }
                });
            }
        });
    }

    function showAlert(message, type) {
        Swal.fire({
            title: type === 'success' ? 'Success!' : 'Oops!',
            text: message,
            icon: type,
            // confirmButtonText: 'OK',
            timer: 1000, // Auto close after 3000 milliseconds (3 seconds)
            timerProgressBar: true, // Optional: Show a progress bar
            willClose: () => {
                // Optional: Execute code just before the alert closes
                console.log('Alert closed');
            }
        });
    }

    function deposit(reservationId, roomNo) {
        $('#reservationId').val(reservationId);
        $('#roomNo').val(roomNo);
        getDeposit();
        $('#depositModal').modal('show');
    }

    $('#confirmDeposit').click(function() {
        var reservationId = $('#reservationId').val();
        var roomNo = $('#roomNo').val();
        var depositDate = $('#depositDate').val();
        var depositType = $('#depositType').val();
        var depositAmount = $('#depositAmount').val();
        
        if (depositAmount && depositAmount > 0) {
            $.ajax({
                type: "POST",
                url: APP_URL + "api/deposit/createFromReservation.php",
                data: JSON.stringify({ 
                    reservation_no: reservationId, 
                    room_no: roomNo, 
                    deposit_date: depositDate, 
                    deposit_type: depositType, 
                    deposit_amount: depositAmount 
                }),
                success: function(data) {
                    if (data === "created") {
                        showAlert("Security deposit added successfully!", "success");
                        $('#depositModal').modal('hide'); // Hide the modal after success
                        getAllCheckOut();
                    } else {
                        showAlert("An error occurred while processing the deposit.", "error");
                    }
                },
                error: function() {
                    showAlert("An error occurred while saving the deposit.", "error");
                }
            });
        } else {
            showAlert("Please enter a valid deposit amount.", "warning");
        }
    });

    function getDeposit(id){
        var reservationId = $('#reservationId').val();
        var roomNo = $('#roomNo').val();
        $("#depositTable").find("tbody").find("tr").remove();
        $.ajax({
            url: APP_URL + "api/deposit/get_all_rows.php",
            type: "POST",
            data: JSON.stringify({ reservation_no: reservationId, room_no: roomNo })
        }).done(function(data) {
            console.log(data);
            $.each(data.records, function(i, v) {
                console.log(v);
                $("#depositTable").find("tbody")
                .append($('<tr>')
                    .append("<td>" + v.deposit_date + "</td>")
                    .append("<td>" + v.deposit_type + "</td>")
                    .append("<td>" + v.deposit_amount + "</td>")
                    .append("<td><button type='button' class='btn btn-outline-danger btn-sm remove-btn' onclick='delDeposit(" + v.id + ", this)'>Remove</button></td>")
                    // .append("<td><button type='button' class='btn btn-block btn-danger btn-sm' onclick='delDeposit(" + v.id + ", this)' style='padding: 0px 10px;font-size: 20px; min-width: 35px'>&times;</button></td>")
                    )
            });
            calculate();
        });
    }

    function delDeposit(id) {
        Swal.fire({
            title: 'Are you sure?',
            text: `You are about to delete deposit`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    type: "POST",
                    url: APP_URL + "api/deposit/delete.php",
                    data: JSON.stringify({ id: id }),
                    success: function(data) {
                        if (data=== "deleted") {
                            getDeposit();
                            getAllCheckOut();
                            showAlert("Security deposit deleted successfully!", "success");
                        } else {
                            showAlert("An error occurred on the server!", "error");
                        }
                    },
                    error: function() {
                        showAlert("An error occurred while saving!", "error");
                    }
                });
            }
        });
    }
</script>
