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

<?php
// Include the database connection file
include 'layouts/dbconn.php';

// Fetch cargo bookings data from the database
$cargoQuery = "SELECT booking_number, total_amount FROM cargo_bookings WHERE payment_status != 'Paid'";
$cargoBookings = $conn->query($cargoQuery)->fetch_all(MYSQLI_ASSOC);
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Add Payment')); ?>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <?php include 'layouts/head-css.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</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' => 'Add Payment')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Add Payment</h4>
                                </div>
                                <div class="card-body">
                                    <form method="POST" action="save_cargo_payment.php" id="paymentForm">
                                        <div class="live-preview">
                                            <div class="row gy-4">
                                                <!-- Cargo Tracking Code -->
                                                <div class="col-xxl-4 col-md-6">
                                                    <div>
                                                        <label for="cargoTrackingCode" class="form-label">Cargo Tracking Code</label>
                                                        <select class="js-example-basic-single" name="cargo_tracking_code" id="cargoTrackingCode" required>
                                                            <option value="">Select Cargo Tracking Code</option>
                                                            <?php foreach ($cargoBookings as $booking): ?>
                                                                <option value="<?php echo $booking['booking_number']; ?>"><?php echo $booking['booking_number']; ?></option>
                                                            <?php endforeach; ?>
                                                        </select>
                                                    </div>
                                                </div>

                                                <!-- Cargo Details -->
                                                <div class="col-xxl-4 col-md-6">
                                                    <div>
                                                        <label for="totalAmount" class="form-label">Total Amount</label>
                                                        <input type="text" class="form-control" id="totalAmount" name="total_amount" readonly>
                                                    </div>
                                                </div>

                                                <!-- Payment Amount -->
                                                <div class="col-xxl-4 col-md-6">
                                                    <div>
                                                        <label for="paymentAmount" class="form-label">Payment Amount</label>
                                                        <input type="number" step="0.01" class="form-control" id="paymentAmount" name="payment_amount" required>
                                                    </div>
                                                </div>

                                                <!-- Submit Button -->
                                                <div class="col-12 mt-4">
                                                    <button type="submit" class="btn btn-success btn-label waves-effect waves-light rounded-pill">
                                                        <i class="ri-check-double-line label-icon align-middle rounded-pill fs-16 me-2"></i>
                                                        Add Payment
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

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

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

    <!-- prismjs plugin -->
    <script src="assets/libs/prismjs/prism.js"></script>
    <script src="assets/js/app.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <!--select2 cdn-->
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="assets/js/pages/select2.init.js"></script>

    <script>
document.addEventListener('DOMContentLoaded', function() {
    // Log that script is loaded
    writeToConsole('Script initialized');

    // Function to write to console with timestamp
    function writeToConsole(message) {
        const timestamp = new Date().toISOString();
        console.log(`[${timestamp}] ${message}`);
    }

    // Check if required elements exist
    const cargoTrackingCodeSelect = document.getElementById('cargoTrackingCode');
    const totalAmountInput = document.getElementById('totalAmount');
    
    if (!cargoTrackingCodeSelect) {
        writeToConsole('ERROR: cargoTrackingCode select element not found');
        return;
    }
    if (!totalAmountInput) {
        writeToConsole('ERROR: totalAmount input element not found');
        return;
    }

    writeToConsole('Required elements found');

    // Initialize Select2
    try {
        $(cargoTrackingCodeSelect).select2();
        writeToConsole('Select2 initialized');
    } catch (error) {
        writeToConsole('ERROR initializing Select2: ' + error.message);
    }

    // Add both change handlers to ensure we catch the event
    // Native change event
    cargoTrackingCodeSelect.addEventListener('change', function(e) {
        writeToConsole('Native change event fired');
        handleCargoSelection(this.value);
    });

    // Select2 change event
    $(cargoTrackingCodeSelect).on('select2:select', function(e) {
        writeToConsole('Select2 change event fired');
        handleCargoSelection(e.target.value);
    });

    function handleCargoSelection(selectedValue) {
        writeToConsole(`Handling cargo selection: ${selectedValue}`);
        
        if (!selectedValue) {
            writeToConsole('No value selected, clearing total amount');
            totalAmountInput.value = '';
            return;
        }

        // Show loading state
        totalAmountInput.value = 'Loading...';
        writeToConsole('Starting AJAX request');

        // Make the AJAX request
        $.ajax({
            url: 'fetch_cargo_details.php',
            type: 'GET',
            data: { booking_number: selectedValue },
            dataType: 'json',
            beforeSend: function() {
                writeToConsole('AJAX request starting...');
            },
            success: function(response) {
                writeToConsole('AJAX response received: ' + JSON.stringify(response));
                
                if (response.success && response.total_amount) {
                    writeToConsole(`Setting total amount to: ${response.total_amount}`);
                    totalAmountInput.value = response.total_amount;
                } else {
                    writeToConsole('Error in response: ' + (response.error || 'Unknown error'));
                    totalAmountInput.value = '';
                    alert('Error fetching cargo details: ' + (response.error || 'Unknown error'));
                }
            },
            error: function(xhr, status, error) {
                writeToConsole('AJAX error occurred:');
                writeToConsole('Status: ' + status);
                writeToConsole('Error: ' + error);
                writeToConsole('Response: ' + xhr.responseText);
                
                totalAmountInput.value = '';
                alert('Failed to fetch cargo details. Please check the console for more information.');
            },
            complete: function() {
                writeToConsole('AJAX request completed');
            }
        });
    }

    // Test if jQuery and Select2 are available
    writeToConsole('jQuery version: ' + (typeof $ !== 'undefined' ? $.fn.jquery : 'not loaded'));
    writeToConsole('Select2 version: ' + (typeof $.fn.select2 !== 'undefined' ? 'loaded' : 'not loaded'));
});
    </script>
    <script>
        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>
</body>
</html>
