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

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

// Fetch airports data from the database
//$query = "SELECT airport_id, airport_name FROM airports";
//$result = $conn->query($query);

// Load customers
$customersQuery = "SELECT * FROM customers ORDER BY first_name, last_name";
$customers = $conn->query($customersQuery)->fetch_all(MYSQLI_ASSOC);


// Close the database connection
//$conn->close();
?>
<?php
// Fetch the last booking number from the database
$query = "SELECT booking_number FROM cargo_bookings ORDER BY booking_id DESC LIMIT 1";
$result = $conn->query($query);

if ($result && $result->num_rows > 0) {
    $row = $result->fetch_assoc();
    preg_match('/AWT(\d+)/', $row['booking_number'], $matches);
    $lastNumber = intval($matches[1]);
    $newNumber = $lastNumber + 1;
} else {
    $newNumber = 1;
}

$booking_number = 'AWT' . str_pad($newNumber, 6, '0', STR_PAD_LEFT);
?>

<head>

    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Add Cargo')); ?>
    
    <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 Cargo Booking')); ?>
            
                    <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 Cargo Booking</h4>
                                </div>
                                <div class="card-body">
                                    <form method="POST" action="save_cargo_booking.php">
                                        <div class="live-preview">
                                            <div class="row gy-4">
                                                <!-- Sender Information -->
                                                <div class="col-12">
                                                    <h5 class="text-muted mb-3">Sender Information</h5>
                                                </div>
                                                <div class="col-xxl-4 col-md-6">
                                                    <div>
                                                        <label for="bookingNumber" class="form-label">Cargo Tracking Code</label>
                                                        <input type="text" class="form-control" id="bookingNumber" name="bookingNumber" value="<?php echo $booking_number; ?>" readonly>
                                                    </div>
                                                </div>
                                                <div class="col-xxl-4 col-md-6">
                                                    
                                                </div>
                                                <div class="col-xxl-4 col-md-6">
                                                    
                                                </div>
                                                <div class="col-xxl-4 col-md-6">
                                                    <div>
                                                        <label for="senderCustomer" class="form-label">Select Sender</label>
                                                        <div class="form-icon d-flex align-items-center">
                                                           <select class="js-example-basic-single" name="sender_customer_id" id="senderCustomer" required>
                                                               <option value="">Select Sender</option>
                                                                <?php foreach ($customers as $customer): ?>
                                                                    <option value="<?php echo $customer['customer_id']; ?>"><?php echo $customer['first_name']; ?> <?php echo $customer['last_name']; ?></option>
                                                                <?php endforeach; ?>
                                                            </select>
                                                            <button type="button" class="btn btn-primary btn-sm ms-2" data-bs-toggle="modal" data-bs-target="#senderModal">
                                                                +
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-xxl-4 col-md-6">
                                                    <div>
                                                        <label for="senderAddress" class="form-label">Pickup Address</label>
                                                        <select class="js-example-basic-single" name="sender_address_id" id="senderAddress" required>
                                                            <option value="">Select Pickup Address</option>
                                                            <!-- This will be populated via AJAX based on selected sender -->
                                                        </select>
                                                    </div>
                                                </div>
            
                                                <!-- Receiver Information -->
                                                <div class="col-12 mt-4">
                                                    <h5 class="text-muted mb-3">Receiver Information</h5>
                                                </div>

                                                <div class="col-xxl-4 col-md-6">
                                                    <div>
                                                        <label for="receiverCustomer" class="form-label">Select Existing Receiver (Optional)</label>
                                                        <div class="form-icon d-flex align-items-center">
                                                            <select class="js-example-basic-single" name="receiver_customer_id" id="receiverCustomer">
                                                                <option value="">Select Receiver</option>
                                                                <?php foreach ($customers as $customer): ?>
                                                                    <option value="<?php echo $customer['customer_id']; ?>"><?php echo $customer['first_name']; ?> <?php echo $customer['last_name']; ?></option>
                                                                <?php endforeach; ?>
                                                            </select>
                                                            <button type="button" class="btn btn-primary btn-sm ms-2" data-bs-toggle="modal" data-bs-target="#receiverModal">
                                                                +
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <div class="col-xxl-4 col-md-6">
                                                    <div>
                                                        <label for="receiverAddress" class="form-label">Delivery Address</label>
                                                        <select class="js-example-basic-single" name="receiver_address_id" id="receiverAddress" required>
                                                            <option value="">Select Delivery Address</option>
                                                            <!-- This will be populated via AJAX based on selected receiver -->
                                                        </select>
                                                    </div>
                                                </div>
                                                <div class="col-xxl-4 col-md-6">
                                                    <div>
                                                        <label for="receiverName" class="form-label">Receiver Name</label>
                                                        <input type="text" class="form-control" id="receiverName" name="receiver_name" required>
                                                    </div>
                                                </div>
                                                <div class="col-xxl-4 col-md-6">
                                                    <div>
                                                        <label for="receiverPhone" class="form-label">Receiver Phone</label>
                                                        <input type="tel" class="form-control" id="receiverPhone" name="receiver_phone" required>
                                                    </div>
                                                </div>
                                                <div class="col-xxl-4 col-md-6">
                                                    <div>
                                                        <label for="receiverEmail" class="form-label">Receiver Email</label>
                                                        <input type="email" class="form-control" id="receiverEmail" name="receiver_email">
                                                    </div>
                                                </div>
            
                                                <!-- Cargo Details -->
                                                <div class="col-12 mt-4">
                                                    <h5 class="text-muted mb-3">Cargo Details</h5>
                                                </div>
                                                <div class="col-xxl-4 col-md-6">
                                                    <div>
                                                        <label for="cargoType" class="form-label">Cargo Type</label>
                                                        <select class="form-select" id="cargoType" name="cargo_type" required>
                                                            <option value="">Select Cargo Type</option>
                                                            <option value="documents">Documents</option>
                                                            <option value="electronics">Electronics</option>
                                                            <option value="fragile">Fragile Items</option>
                                                            <option value="perishable">Perishable Goods</option>
                                                            <option value="general">General Cargo</option>
                                                        </select>
                                                    </div>
                                                </div>
                                                <div class="col-xxl-2 col-md-6">
                                                    <div>
                                                        <label for="weight" class="form-label">Weight (kg)</label>
                                                        <input type="number" step="0.01" class="form-control" id="weight" name="weight" required>
                                                    </div>
                                                </div>
                                                <div class="col-xxl-2 col-md-6">
                                                    <div>
                                                        <label for="rate" class="form-label">Rate (Cargo fee rate)</label>
                                                        <input type="number" class="form-control" id="rate" name="rate" >
                                                    </div>
                                                </div>
                                                <div class="col-xxl-3 col-md-6">
                                                    <div>
                                                        <label for="dimensions" class="form-label">Dimensions (L x W x H cm)</label>
                                                        <input type="text" class="form-control" id="dimensions" name="dimensions" placeholder="30 x 20 x 15">
                                                    </div>
                                                </div>
                                                <div class="col-12">
                                                    <div>
                                                        <label for="specialInstructions" class="form-label">Special Instructions</label>
                                                        <textarea class="form-control" id="specialInstructions" name="special_instructions" rows="3"></textarea>
                                                    </div>
                                                </div>
            
                                                <!-- Delivery Details -->
                                                <div class="col-12 mt-4">
                                                    <h5 class="text-muted mb-3">Delivery Details</h5>
                                                </div>
                                                <div class="col-xxl-4 col-md-6">
                                                    <div>
                                                        <label for="pickupDate" class="form-label">Pickup Date & Time</label>
                                                        <input type="date" class="form-control" id="pickupDate" name="pickup_date" required>
                                                    </div>
                                                </div>
                                                <div class="col-xxl-4 col-md-6">
                                                    <div>
                                                        <label for="estimatedDeliveryDate" class="form-label">Estimated Delivery Date</label>
                                                        <input type="date" class="form-control" id="estimatedDeliveryDate" name="estimated_delivery_date" required>
                                                    </div>
                                                </div>
                                                
                                                <!-- Payment Details -->
                                                <div class="col-12 mt-4">
                                                    <h5 class="text-muted mb-3">Payment Details</h5>
                                                </div>
                                                <div class="col-xxl-4 col-md-6">
                                                    <div>
                                                        <label for="currency" class="form-label">Currency</label>
                                                        <select class="form-select" id="currency" name="currency" required>
                                                            <option value="KES">Kenyan Shillings (KES)</option>
                                                            <option value="USD">US Dollars (USD)</option>
                                                        </select>
                                                    </div>
                                                </div>
                                                <div class="col-xxl-4 col-md-6">
                                                    <div>
                                                        <label for="totalAmount" class="form-label">Total Amount</label>
                                                        <div class="input-group">
                                                            <span class="input-group-text currency-symbol">KES</span>
                                                            <input type="number" step="0.01" class="form-control" id="totalAmount" name="total_amount" required>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="col-xxl-4 col-md-6">
                                                    <div>
                                                        <label for="payment_status" class="form-label">Payment Status</label>
                                                        <select class="form-select" id="payment_status" name="payment_status" required>
                                                            <option value="Unpaid">Unpaid</option>
                                                            <option value="Partially Paid">Partially Paid</option>
                                                            <option value="Paid">Paid</option>
                                                            <option value="Refunded">Refunded</option>
                                                            <option value="Cancelled">Cancelled</option>
                                                        </select>
                                                    </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> 
                                                        Create Booking
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
<!-- Sender Modal -->
<div class="modal fade" id="senderModal" tabindex="-1" aria-labelledby="senderModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="senderModalLabel">Add New Sender</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="newSenderForm" method="post">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="senderFirstName" class="form-label">First Name</label>
                                <input type="text" class="form-control" id="senderFirstName" name="first_name" required>
                            </div>
                            <div class="mb-3">
                                <label for="senderEmail" class="form-label">Email</label>
                                <input type="email" class="form-control" id="senderEmail" name="email" required>
                            </div>
                            <div class="mb-3">
                                <label for="senderAddress" class="form-label">Address</label>
                                <textarea class="form-control" id="senderAddress" name="address"></textarea>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="senderLastName" class="form-label">Last Name</label>
                                <input type="text" class="form-control" id="senderLastName" name="last_name" required>
                            </div>
                            <div class="mb-3">
                                <label for="senderPhone" class="form-label">Phone Number</label>
                                <input type="text" class="form-control" id="senderPhone" name="phone_number">
                            </div>
                            <div class="mb-3">
                                <label for="senderCity" class="form-label">City</label>
                                <input type="text" class="form-control" id="senderCity" name="city">
                            </div>
                            <!-- New fields for address table -->
                            <div class="mb-3">
                                <label for="senderPostalCode" class="form-label">Postal Code</label>
                                <input type="text" class="form-control" id="senderPostalCode" name="postal_code">
                            </div>
                            <div class="mb-3">
                                <label for="senderState" class="form-label">State/Province</label>
                                <input type="text" class="form-control" id="senderState" name="state">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-12">
                            <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> Save Sender
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Receiver Modal with same structure -->
<div class="modal fade" id="receiverModal" tabindex="-1" aria-labelledby="receiverModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="receiverModalLabel">Add New Receiver</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="newReceiverForm" method="post">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="receiverFirstName" class="form-label">First Name</label>
                                <input type="text" class="form-control" id="receiverFirstName" name="first_name" required>
                            </div>
                            <div class="mb-3">
                                <label for="receiverEmail" class="form-label">Email</label>
                                <input type="email" class="form-control" id="receiverEmail" name="email" required>
                            </div>
                            <div class="mb-3">
                                <label for="receiverAddress" class="form-label">Address</label>
                                <textarea class="form-control" id="receiverAddress" name="address"></textarea>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="receiverLastName" class="form-label">Last Name</label>
                                <input type="text" class="form-control" id="receiverLastName" name="last_name" required>
                            </div>
                            <div class="mb-3">
                                <label for="receiverPhone" class="form-label">Phone Number</label>
                                <input type="text" class="form-control" id="receiverPhone" name="phone_number">
                            </div>
                            <div class="mb-3">
                                <label for="receiverCity" class="form-label">City</label>
                                <input type="text" class="form-control" id="receiverCity" name="city">
                            </div>
                            <!-- New fields for address table -->
                            <div class="mb-3">
                                <label for="receiverPostalCode" class="form-label">Postal Code</label>
                                <input type="text" class="form-control" id="receiverPostalCode" name="postal_code">
                            </div>
                            <div class="mb-3">
                                <label for="receiverState" class="form-label">State/Province</label>
                                <input type="text" class="form-control" id="receiverState" name="state">
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-12">
                            <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> Save Receiver
                            </button>
                        </div>
                    </div>
                </form>
            </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() {
    // Currency and Amount Handling
    const currencySelect = document.getElementById('currency');
    const currencySymbol = document.querySelector('.currency-symbol');
    const weightInput = document.getElementById('weight');
    const rateInput = document.getElementById('rate');
    const totalAmountInput = document.getElementById('totalAmount');

    // Function to calculate total amount
    function calculateTotal() {
        const weight = parseFloat(weightInput.value) || 0;
        const rate = parseFloat(rateInput.value) || 0;
        
        if (weight && rate) {
            const total = weight * rate;
            totalAmountInput.value = total.toFixed(2);
        }
    }

    // Add event listeners for calculation
    weightInput.addEventListener('input', calculateTotal);
    rateInput.addEventListener('input', calculateTotal);

    // Currency handling
    currencySelect.addEventListener('change', function() {
        currencySymbol.textContent = this.value;
    });

    // Total amount formatting and manual override
    totalAmountInput.addEventListener('input', function() {
        if (this.value.includes('.')) {
            const parts = this.value.split('.');
            if (parts[1].length > 2) {
                this.value = parseFloat(this.value).toFixed(2);
            }
        }
    });

    // Customer Management Configuration
    const formConfig = {
        sender: {
            formId: 'newSenderForm',
            modalId: 'senderModal',
            selectId: 'senderCustomer',
            endpoint: 'save_customer_mod.php',
            type: 'sender'
        },
        receiver: {
            formId: 'newReceiverForm',
            modalId: 'receiverModal',
            selectId: 'receiverCustomer',
            endpoint: 'save_customer_mod.php',
            type: 'receiver'
        }
    };

    function updateCustomerSelect(selectId, newCustomer) {
        const select = document.getElementById(selectId);
        if (select) {
            const newOption = new Option(
                `${newCustomer.first_name} ${newCustomer.last_name}`,
                newCustomer.customer_id,
                true,
                true
            );
            $(`#${selectId}`).append(newOption).trigger('change');
        }
    }

    function handleFormSubmission(config) {
        const form = document.getElementById(config.formId);
        if (!form) {
            console.error(`Form with ID ${config.formId} not found`);
            return;
        }

        form.addEventListener('submit', async function(e) {
            e.preventDefault();
            console.log('Form submitted');
            
            const submitBtn = form.querySelector('button[type="submit"]');
            const originalBtnContent = submitBtn.innerHTML;
            const modal = document.getElementById(config.modalId);

            try {
                submitBtn.disabled = true;
                submitBtn.innerHTML = `
                    <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                    Saving...
                `;

                const formData = new FormData(form);
                formData.append('customer_type', config.type);
                formData.append('address_type', 'home');
                formData.append('is_default', '1');

                console.log('Sending data to:', config.endpoint);
                for (let pair of formData.entries()) {
                    console.log(pair[0] + ': ' + pair[1]);
                }

                const response = await fetch(config.endpoint, {
                    method: 'POST',
                    body: formData
                });

                console.log('Response status:', response.status);
                const data = await response.json();
                console.log('Response data:', data);

                if (data.success) {
                    updateCustomerSelect(config.selectId, data);
                    form.reset();
                    
                    const modalInstance = bootstrap.Modal.getInstance(modal);
                    if (modalInstance) {
                        modalInstance.hide();
                    } else {
                        $(modal).modal('hide');
                    }

                    Swal.fire({
                        title: 'Success!',
                        text: `${config.type === 'sender' ? 'Sender' : 'Receiver'} added successfully`,
                        icon: 'success',
                        confirmButtonClass: 'btn btn-primary w-xs mt-2',
                        buttonsStyling: false
                    });
                } else {
                    throw new Error(data.message || 'Failed to save customer');
                }
            } catch (error) {
                console.error('Error details:', error);
                Swal.fire({
                    title: 'Error!',
                    text: error.message || 'An error occurred while saving the customer.',
                    icon: 'error',
                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                    buttonsStyling: false
                });
            } finally {
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalBtnContent;
            }
        });
    }

    // Initialize customer forms
    Object.values(formConfig).forEach(config => {
        handleFormSubmission(config);
    });

    // Reset forms when modals are closed
    document.querySelectorAll('.modal').forEach(modal => {
        modal.addEventListener('hidden.bs.modal', function() {
            const form = this.querySelector('form');
            if (form) {
                form.reset();
                form.querySelectorAll('.is-invalid').forEach(field => {
                    field.classList.remove('is-invalid');
                });
            }
        });
    });

    // Address and Customer Details Handling
    function fetchAddresses(customerId, addressDropdownId) {
        if (customerId) {
            $.ajax({
                url: 'fetch_addresses.php',
                type: 'GET',
                data: { customer_id: customerId },
                dataType: 'json',
                success: function(data) {
                    var addressDropdown = $(addressDropdownId);
                    addressDropdown.empty();
                    addressDropdown.append('<option value="">Select Address</option>');
                    $.each(data, function(index, address) {
                        var addressText = address.street_address + ', ' + address.city + ', ' + address.state + ', ' + address.postal_code + ', ' + address.country;
                        addressDropdown.append('<option value="' + address.address_id + '">' + addressText + '</option>');
                    });
                },
                error: function(xhr, status, error) {
                    console.error('Error fetching addresses:', error);
                }
            });
        } else {
            $(addressDropdownId).empty().append('<option value="">Select Address</option>');
        }
    }

    function fetchCustomerDetails(customerId, nameFieldId, phoneFieldId, emailFieldId) {
        if (customerId) {
            $.ajax({
                url: 'fetch_customer_details.php',
                type: 'GET',
                data: { customer_id: customerId },
                dataType: 'json',
                success: function(data) {
                    $(nameFieldId).val(data.first_name + ' ' + data.last_name);
                    $(phoneFieldId).val(data.phone_number);
                    $(emailFieldId).val(data.email);
                },
                error: function(xhr, status, error) {
                    console.error('Error fetching customer details:', error);
                }
            });
        } else {
            $(nameFieldId).val('');
            $(phoneFieldId).val('');
            $(emailFieldId).val('');
        }
    }

    $('#senderCustomer').on('change', function() {
        var customerId = $(this).val();
        fetchAddresses(customerId, '#senderAddress');
        fetchCustomerDetails(customerId, '#senderName', '#senderPhone', '#senderEmail');
    });

    $('#receiverCustomer').on('change', function() {
        var customerId = $(this).val();
        fetchAddresses(customerId, '#receiverAddress');
        fetchCustomerDetails(customerId, '#receiverName', '#receiverPhone', '#receiverEmail');
        $('#receiverName').prop('required', false);
        $('#receiverPhone').prop('required', false);
    });

    // Initialize Select2
    $('.js-example-basic-single').select2({
        ajax: {
            url: 'fetch_customers.php',
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
                    q: params.term
                };
            },
            processResults: function (data) {
                return {
                    results: data
                };
            },
            cache: true
        },
        minimumInputLength: 1,
        templateResult: formatRepo,
        templateSelection: formatRepoSelection
    });

    function formatRepo (repo) {
        if (repo.loading) {
            return repo.text;
        }

        var markup = "<div class='select2-result-repository clearfix'>" +
            "<div class='select2-result-repository__meta'>" +
            "<div class='select2-result-repository__title'>" + repo.first_name + " " + repo.last_name + "</div>" +
            "<div class='select2-result-repository__description'>" + repo.phone_number + "</div>" +
            "</div></div>";

        return markup;
    }

    function formatRepoSelection (repo) {
        return repo.first_name + " " + repo.last_name;
    }
});
</script>

</body>

</html>