<?php include 'layouts/session.php'; ?>
<?php include 'layouts/main.php'; ?>
<?php include 'layouts/dbconn.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'All Cargo')); ?>

    <!--datatable css-->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css" />
    <!--datatable responsive css-->
    <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.2.9/css/responsive.bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.2.2/css/buttons.dataTables.min.css">
    
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Manage Cargo', 'title' => 'All Cargo')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">All Cargo</h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table id="buttons-datatables" class="display table table-bordered" style="width:100%">
                                            <thead>
                                                <tr>
                                                    <th>Booking Number</th>
                                                    <th>Sender Name</th>
                                                    <th>Receiver Name</th>
                                                    <th>Cargo Type</th>
                                                    <th>Weight</th>
                                                    <th>Estimated Delivery Date</th>
                                                    <th>Rate</th>
                                                    <th>Total Amount</th>
                                                    <th>Payment Status</th>
                                                    <th>Package Status</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                // Include the database connection file
                                                include('layouts/dbconn.php');
                                                
                                                // Modified query to include booking_status
                                                $query = "
                                                    SELECT
                                                        cb.booking_number,
                                                        CONCAT(sc.first_name, ' ', sc.last_name) AS sender_name,
                                                        CONCAT(rc.first_name, ' ', rc.last_name) AS receiver_name,
                                                        cb.cargo_type,
                                                        cb.weight,
                                                        cb.estimated_delivery_date,
                                                        cb.rate,
                                                        cb.total_amount,
                                                        cb.currency,
                                                        cb.payment_status,
                                                        cb.booking_status,
                                                        cb.booking_id
                                                    FROM
                                                        cargo_bookings cb
                                                    LEFT JOIN
                                                        customers sc ON cb.sender_customer_id = sc.customer_id
                                                    LEFT JOIN
                                                        customers rc ON cb.receiver_customer_id = rc.customer_id
                                                ";
                                                
                                                $result = $conn->query($query);
                                                
                                                if ($result->num_rows > 0) {
                                                    while ($row = $result->fetch_assoc()) {
                                                        echo "<tr ondblclick=\"openFileData('{$row['booking_number']}')\">";
                                                        echo "<td><a href='cargo_view.php?booking_number={$row['booking_number']}'>{$row['booking_number']}</a></td>";
                                                        echo "<td>{$row['sender_name']}</td>";
                                                        echo "<td>{$row['receiver_name']}</td>";
                                                        echo "<td>{$row['cargo_type']}</td>";
                                                        echo "<td>{$row['weight']}</td>";
                                                        echo "<td>{$row['estimated_delivery_date']}</td>";
                                                        echo "<td>{$row['rate']}</td>";
                                                        echo "<td>{$row['currency']} {$row['total_amount']}</td>";
                                                        echo "<td>{$row['payment_status']}</td>";
                                                        
                                                        // Add delivery status column with appropriate styling
                                                        $status_class = '';
                                                        $status_text = ucfirst(str_replace('_', ' ', $row['booking_status']));
                                                        
                                                        switch($row['booking_status']) {
                                                            case 'delivered':
                                                                $status_class = 'badge bg-success';
                                                                break;
                                                            case 'in_transit':
                                                                $status_class = 'badge bg-info';
                                                                break;
                                                            case 'pending':
                                                                $status_class = 'badge bg-warning';
                                                                break;
                                                            case 'cancelled':
                                                                $status_class = 'badge bg-danger';
                                                                break;
                                                            default:
                                                                $status_class = 'badge bg-secondary';
                                                        }
                                                        
                                                        echo "<td><span class='{$status_class}'>{$status_text}</span></td>";
                                                        
                                                        // Actions column with conditional buttons
                                                        echo '<td>
                                                            <ul class="list-inline hstack gap-2 mb-0">';
                                                        
                                                        // Check payment status and show appropriate button
                                                        if ($row['payment_status'] == 'paid') {
                                                            echo '<li class="list-inline-item edit" data-bs-toggle="tooltip" data-bs-trigger="hover" data-bs-placement="top" title="Print Payment">
                                                                    <a href="javascript:void(0);" onclick="openThermalReceipt(' . $row['booking_id'] . ')" class="text-muted d-inline-block">
                                                                        <i class="ri-printer-line fs-16"></i>
                                                                    </a>
                                                                  </li>';
                                                        } else {
                                                            echo '<li class="list-inline-item edit" data-bs-toggle="tooltip" data-bs-trigger="hover" data-bs-placement="top" title="Add Payment">
                                                                    <a href="add_cargo_payment.php?booking_number=' . $row['booking_number'] . '" class="text-muted d-inline-block">
                                                                        <i class="ri-refund-2-line fs-16"></i>
                                                                    </a>
                                                                  </li>';
                                                        }
                                                
                                                        // Rest of the action buttons
                                                        echo '
                                                            <li class="list-inline-item" data-bs-toggle="tooltip" data-bs-trigger="hover" data-bs-placement="top" title="View">
                                                                <a href="cargo_view.php?booking_number=' . $row['booking_number'] . '" class="text-muted d-inline-block">
                                                                    <i class="ri-eye-fill align-bottom me-2 text-muted"></i> 
                                                                </a>
                                                            </li>
                                                            <li class="list-inline-item" data-bs-toggle="tooltip" data-bs-trigger="hover" data-bs-placement="top" title="Print Label">
                                                                <a href="print_cargo_label.php?booking_number=' . $row['booking_number'] . '" target="_blank" class="text-muted d-inline-block">
                                                                    <i class="ri-printer-fill fs-16"></i>
                                                                </a>
                                                            </li>
                                                            <li class="list-inline-item" data-bs-toggle="tooltip" data-bs-trigger="hover" data-bs-placement="top" title="View Invoice">
                                                                <a class="edit-item-btn" href="cargo_payment_view.php?booking_id=' . $row['booking_id'] . '">
                                                                    <i class="ri-printer-line fs-16"></i>
                                                                </a>
                                                            </li>';
                                                        
                                                        // Only show status update button if not delivered
                                                        if ($row['booking_status'] !== 'delivered') {
                                                            echo '<li class="list-inline-item edit" data-bs-toggle="tooltip" data-bs-trigger="hover" data-bs-placement="top" title="Update Status">
                                                                    <a href="javascript:void(0);" onclick="showStatusModal(' . $row['booking_id'] . ', \'' . $row['booking_status'] . '\')" class="text-muted d-inline-block">
                                                                        <i class="ri-exchange-line fs-16"></i>
                                                                    </a>
                                                                  </li>';
                                                        }
                                                        
                                                        echo '<li class="list-inline-item" data-bs-toggle="tooltip" data-bs-trigger="hover" data-bs-placement="top" title="Delete">
                                                                <a class="remove-item-btn" href="javascript:void(0);" onclick="showDeleteModal(' . $row['booking_id'] . ')">
                                                                    <i class="ri-delete-bin-fill align-bottom text-muted"></i>
                                                                </a>
                                                            </li>
                                                        
                                                        </ul>
                                                        </td>';
                                                        echo "</tr>";
                                                    }
                                                } else {
                                                    echo "<tr><td colspan='10'>No cargo bookings found</td></tr>";
                                                }
                                                
                                                $conn->close();
                                                ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div><!--end row-->
                </div>
                <!-- container-fluid -->
                <!-- Delete Modal -->
                <div class="modal fade" id="deleteRecordModal" tabindex="-1" role="dialog" aria-labelledby="deleteRecordLabel" aria-hidden="true">
                    <div class="modal-dialog modal-dialog-centered">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="deleteRecordLabel">Confirm Delete</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <p>Are you sure you want to delete this booking?</p> 
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-dark btn-label waves-effect waves-light rounded-pill" data-bs-dismiss="modal"><i class="ri-close-circle-line label-icon align-middle rounded-pill fs-16 me-2"></i>Cancel</button>
                                <button type="button" class="btn btn-danger btn-label waves-effect waves-light rounded-pill" id="delete-record"><i class="ri-delete-bin-6-line label-icon align-middle rounded-pill fs-16 me-2"></i>Yes, Delete</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal fade" id="statusUpdateModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Update Cargo Status</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="updateStatusForm" action="update_cargo_status.php" method="post">
                <div class="modal-body">
                    <input type="hidden" name="booking_id" id="modal_booking_id">
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select name="booking_status" class="form-select" required>
                            <option value="pending">Pending</option>
                            <option value="confirmed">Confirmed</option>
                            <option value="picked_up">Picked Up</option>
                            <option value="in_office">In Office</option>
                            <option value="in_transit">In Transit</option>
                            <option value="arrived_destination">Arrived at Destination</option>
                            <option value="out_for_delivery">Out for Delivery</option>
                            <option value="delivered">Delivered</option>
                            <option value="failed_delivery">Failed Delivery</option>
                            <option value="on_hold">On Hold</option>
                            <option value="cancelled">Cancelled</option>
                            <option value="returned">Returned</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Notes</label>
                        <textarea name="status_notes" class="form-control" rows="3" placeholder="Enter any notes about this status update"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Status</button>
                </div>
            </form>
        </div>
    </div>
</div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <?php include 'layouts/vendor-scripts.php'; ?>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

    <!--datatable js-->
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.2.9/js/dataTables.responsive.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.2.2/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.2.2/js/buttons.print.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.2.2/js/buttons.html5.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="assets/js/pages/datatables.init.js"></script>
    <!-- App js -->
    <script src="assets/js/app.js"></script>

    <script>
        function openThermalReceipt(bookingId) {
            // Open the thermal receipt in a new window
            var receiptWindow = window.open('thermal_receipt.php?booking_id=' + bookingId, 'thermalReceipt', 'width=400,height=800');
        }

        document.addEventListener('DOMContentLoaded', function() {
            <?php if (isset($_SESSION['success_message'])): ?>
                Swal.fire({
                    title: 'Success!',
                    text: '<?php echo addslashes($_SESSION['success_message']); ?>',
                    icon: 'success',
                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                    buttonsStyling: false
                });
                <?php unset($_SESSION['success_message']); ?>
            <?php endif; ?>

            <?php if (isset($_SESSION['error_message'])): ?>
                Swal.fire({
                    title: 'Error!',
                    text: '<?php echo addslashes($_SESSION['error_message']); ?>',
                    icon: 'error',
                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                    buttonsStyling: false
                });
                <?php unset($_SESSION['error_message']); ?>
            <?php endif; ?>
        });
    </script>
    <script>
let bookingIdToDelete = null;

function showDeleteModal(bookingId) {
    bookingIdToDelete = bookingId;
    var deleteModal = new bootstrap.Modal(document.getElementById('deleteRecordModal'));
    deleteModal.show();
}

document.getElementById('delete-record').addEventListener('click', function() {
    if (bookingIdToDelete) {
        // Send delete request
        fetch('delete_booking.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'booking_id=' + bookingIdToDelete
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                Swal.fire({
                    title: 'Deleted!',
                    text: 'Booking has been deleted successfully.',
                    icon: 'success',
                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                }).then(() => {
                    window.location.reload();
                });
            } else {
                Swal.fire({
                    title: 'Error!',
                    text: data.message || 'Something went wrong!',
                    icon: 'error',
                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                });
            }
        })
        .catch(error => {
            console.error('Error:', error);
            Swal.fire({
                title: 'Error!',
                text: 'Something went wrong!',
                icon: 'error',
                confirmButtonClass: 'btn btn-primary w-xs mt-2',
            });
        });
    }
});
</script>
<script>
function showStatusModal(bookingId, currentStatus) {
    document.getElementById('modal_booking_id').value = bookingId;
    var statusSelect = document.querySelector('#statusUpdateModal select[name="booking_status"]');
    statusSelect.value = currentStatus;
    
    var modal = new bootstrap.Modal(document.getElementById('statusUpdateModal'));
    modal.show();
}

// Add form submit handler if you want to handle it via AJAX
document.getElementById('updateStatusForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    fetch('update_cargo_status.php', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        return response.text().then(text => {
            console.log('Raw server response:', text); // Debug log
            try {
                return JSON.parse(text);
            } catch (e) {
                console.error('JSON Parse Error:', e);
                console.error('Response text:', text);
                throw new Error('Server response format error. Check console for details.');
            }
        });
    })
    .then(data => {
        if (data.success) {
            Swal.fire({
                title: 'Success!',
                text: data.message || 'Status updated successfully',
                icon: 'success',
                confirmButtonClass: 'btn btn-primary w-xs mt-2'
            }).then(() => {
                window.location.reload();
            });
        } else {
            Swal.fire({
                title: 'Error!',
                text: data.message || 'Failed to update status',
                icon: 'error',
                confirmButtonClass: 'btn btn-primary w-xs mt-2'
            });
        }
    })
    .catch(error => {
        console.error('Error details:', error);
        Swal.fire({
            title: 'Error!',
            text: error.message,
            icon: 'error',
            confirmButtonClass: 'btn btn-primary w-xs mt-2'
        });
    });
});
</script>
</body>
</html>