<?php
session_start(); // Start the session
// Include the database connection file
include 'layouts/dbconn.php';

// Check if the user is not logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php'); // Redirect to the login page
    exit();
}

// Query to fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['user_role'];
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
} else {
    // Handle the case if user details are not found
}

// Fetch customers for dropdown
$query_customers = "SELECT customer_id, first_name, last_name FROM customers WHERE status = 1 ORDER BY first_name";
$result_customers = $conn->query($query_customers);
$customers = [];
if ($result_customers->num_rows > 0) {
    while ($row = $result_customers->fetch_assoc()) {
        $customers[] = $row;
    }
}

// Fetch transporters for dropdown
$query_transporters = "SELECT id, name FROM transporter_info WHERE status = 1 ORDER BY name";
$result_transporters = $conn->query($query_transporters);
$transporters = [];
if ($result_transporters->num_rows > 0) {
    while ($row = $result_transporters->fetch_assoc()) {
        $transporters[] = $row;
    }
}

// Set role based permissions
$role_id = $_SESSION['role_id'] ?? null;
if ($role_id && !in_array($role_id, [5, 6, 7])) {
    $showRefund = true;
} else {
    $showRefund = false;
}

// Fetch the system name
$sql = "SELECT setting_value FROM settings WHERE setting_key = 'system_name'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $system_name = $row['setting_value'];
} else {
    $system_name = "Royal Freight"; // Fallback if not found
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Create Transit Shipment')); ?>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <!-- Add these in your HTML head section -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.3.0/dist/sweetalert2.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.3.0/dist/sweetalert2.min.js"></script>
    <?php include 'layouts/head-css.php'; ?>
    <style>
    .table-responsive::-webkit-scrollbar {
        height: 8px;
    }

    .table-responsive::-webkit-scrollbar-track {
        background: #f1f1f1;
    }

    .table-responsive::-webkit-scrollbar-thumb {
        background: #888;
        border-radius: 4px;
    }

    .table-responsive::-webkit-scrollbar-thumb:hover {
        background: #555;
    }
    
    .red-text {
        color: red;
    }
    
    .container-info-card {
        margin-bottom: 20px;
        border-left: 3px solid #3498db;
    }
    
    .bulk-info-card {
        margin-bottom: 20px;
        border-left: 3px solid #f39c12;
    }
    
    .loose-info-card {
        margin-bottom: 20px;
        border-left: 3px solid #27ae60;
    }
    
    .container-details-modal .modal-dialog {
        max-width: 900px;
    }
    
    .container-row-highlight {
        background-color: #f8f9fa;
    }
    
    .container-action-cell {
        white-space: nowrap;
    }
    
    .btn-floating {
        position: fixed;
        bottom: 30px;
        right: 30px;
        z-index: 999;
    }
</style>
</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' => 'Shipment Management', 'title' => 'Create Transit Shipment')); ?>

                    <div class="row">
                        <div class="col-xxl-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Create Transit Shipment</h4>
                                </div><!-- end card header -->

                                <div class="card-body">
                                    <p class="text-muted">Enter the shipment details and container information in the forms provided.</p>
                                    <div class="col text-end">
                                        <span class="red-text">*</span> Required Fields - Must be Filled
                                    </div>
                                    <div class="live-preview">
                                        <form method="POST" action="save_transit_file.php" id="transitShipmentForm">
                                            <!-- Main Shipment Information -->
                                            <div class="row">
                                                <div class="col-md-4 mb-3">
                                                    <label for="fileNumber" class="form-label">Job No:</label>
                                                    <input type="text" class="form-control" id="fileNumberInput" 
                                                           name="file_number" readonly>
                                                    <input type="hidden" name="local_transit" value="2">
                                                </div>
                                                
                                                <div class="col-md-4 mb-3">
                                                    <label for="c_type" class="form-label">Type of Cargo: <span class="red-text">*</span></label>
                                                    <select class="form-select" id="c_type" name="c_type" required onchange="toggleCargoSection()">
                                                        <option value="" selected disabled>Please select type of cargo</option>
                                                        <option value="Container">Container</option>
                                                        <option value="Bulk Cargo">Bulk Cargo</option>
                                                        <option value="Loose Cargo">Loose Cargo</option>
                                                        <option value="Vehicle Cargo">Vehicle Cargo</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-4 mb-3" id="containerNumberDiv" style="display:none;">
                                                    <label for="container_no" class="form-label">Container Count: <span class="red-text">*</span></label>
                                                    <select class="form-select" id="container_no" name="container_no" onchange="generateContainerTable()">
                                                        <option value="" selected disabled>Please select container count</option>
                                                        <?php for ($i=1; $i<=40; $i++): ?>
                                                            <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
                                                        <?php endfor; ?>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="row">
                                                <div class="col-md-4 mb-3">
                                                    <label for="customer" class="form-label">Customer Name: <span class="red-text">*</span></label>
                                                    <select class="js-example-basic-single" name="customer" id="customer-name" required>
                                                        <option value="">Please Select A Customer</option>
                                                        <?php foreach ($customers as $customer): ?>
                                                            <option value="<?php echo $customer['customer_id']; ?>">
                                                                <?php echo htmlspecialchars($customer['first_name'] . ' ' . $customer['last_name']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-4 mb-3">
                                                    <label for="consignee_name" class="form-label">Consignee Name: <span class="red-text">*</span></label>
                                                    <input type="text" class="form-control" placeholder="Enter Consignee Name" 
                                                           name="consignee_name" id="consignee_name" required>
                                                </div>
                                                
                                                <div class="col-md-4 mb-3">
                                                    <label for="destination" class="form-label">Destination: <span class="red-text">*</span></label>
                                                    <select class="form-select" name="destination" id="destination" required onchange="updatePrefix()">
                                                        <option value="" selected disabled>Please select Destination</option>
                                                        <option value="BU-BU">Burundi - Bujumbura</option>
                                                        <option value="DR-LUB">DRC - Lubumbashi</option>
                                                        <option value="DR-GOM">DRC - Goma</option>
                                                        <option value="DR-BUK">DRC - Bukavu</option>
                                                        <option value="DR-KAL">DRC - Kalemie</option>
                                                        <option value="DR-SOL">DRC - Solwezi</option>
                                                        <option value="RW-KI">Rwanda - Kigali</option>
                                                        <option value="ZM-LU">Zambia - Lusaka</option>
                                                        <option value="ZM-ND">Zambia - Ndola</option>
                                                        <option value="ZM-KI">Zambia - Kitwe</option>
                                                    </select>
                                                </div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-3 mb-3">
                                                    <label for="obl_no" class="form-label">OBL No: <span class="red-text">*</span></label>
                                                    <input type="text" class="form-control" placeholder="Enter OBL No" 
                                                           name="obl_no" id="obl_no" required>
                                                </div>
                                                
                                                <div class="col-md-3 mb-3">
                                                    <label for="currency" class="form-label">Currency: <span class="red-text">*</span></label>
                                                    <select class="form-select" id="currency" name="currency">
                                                        <option value="$">USD</option>
                                                        <option value="Tsh.">TSH</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-3 mb-3">
                                                    <label for="free_detention" class="form-label">Free Detention Days: <span class="red-text">*</span></label>
                                                    <select class="form-select" id="free_detention" name="free_detention" required>
                                                        <option value="" selected disabled>Please select Days</option>
                                                        <option value="7">7 Days</option>
                                                        <option value="14">14 Days</option>
                                                        <option value="21">21 Days</option>
                                                        <option value="30">30 Days</option>
                                                        <option value="40">40 Days</option>
                                                        <option value="55">55 Days</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-3 mb-3">
                                                    <label for="way_bill" class="form-label">Way Bill / Telex</label>
                                                    <input type="text" class="form-control" placeholder="Enter way bill" 
                                                           id="way_bill" name="way_bill">
                                                </div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-4 mb-3">
                                                    <label for="initial_eta" class="form-label">Initial ETA Date:</label>
                                                    <input type="date" class="form-control" name="initial_eta" id="initial_eta">
                                                </div>
                                                
                                                <div class="col-md-4 mb-3">
                                                    <label for="eta" class="form-label">ETA Date:</label>
                                                    <input type="date" class="form-control" name="eta" id="eta">
                                                </div>
                                                
                                                <div class="col-md-4 mb-3">
                                                    <label for="vno" class="form-label">Vessel No:</label>
                                                    <input type="text" class="form-control" placeholder="Enter Vessel No" 
                                                           name="vno" id="vno">
                                                </div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-4 mb-3">
                                                    <label for="port" class="form-label">Arrival Port:</label>
                                                    <input type="text" class="form-control" placeholder="Enter Arrival Port Name" 
                                                           id="port" name="port">
                                                </div>
                                                
                                                <div class="col-md-4 mb-3">
                                                    <label for="pre_alert_received_date" class="form-label">Pre-Alert Received Date:</label>
                                                    <input type="date" class="form-control" name="pre_alert_received_date" id="pre_alert_received_date">
                                                </div>
                                                
                                                <div class="col-md-4 mb-3">
                                                    <label for="discharge_date" class="form-label">Discharge Date:</label>
                                                    <input type="date" class="form-control" name="discharge_date" id="discharge_date">
                                                </div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-3 mb-3">
                                                    <label for="port_charges_paid_date" class="form-label">Port Charges Paid Date</label>
                                                    <input type="date" class="form-control" id="port_charges_paid_date" name="port_charges_paid_date">
                                                </div>
                                                
                                                <div class="col-md-3 mb-3">
                                                    <label for="whafage_paid_date" class="form-label">Whafage Paid Date</label>
                                                    <input type="date" class="form-control" id="whafage_paid_date" name="whafage_paid_date">
                                                </div>
                                                
                                                <div class="col-md-3 mb-3">
                                                    <label for="delivery_order_apply_date" class="form-label">Delivery Order Apply Date</label>
                                                    <input type="date" class="form-control" id="delivery_order_apply_date" name="delivery_order_apply_date">
                                                </div>
                                                
                                                <div class="col-md-3 mb-3">
                                                    <label for="delivery_order_received_date" class="form-label">Delivery Order Received Date</label>
                                                    <input type="date" class="form-control" id="delivery_order_received_date" name="delivery_order_received_date">
                                                </div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-md-12 mb-3">
                                                    <label for="remarks" class="form-label">Remarks:</label>
                                                    <textarea class="form-control" rows="3" placeholder="Enter Remarks" 
                                                              name="remarks" id="remarks"></textarea>
                                                </div>
                                            </div>
                                            
                                            <!-- Container Information Section (Table-based) -->
                                            <div id="containerSection" style="display:none;" class="mt-4">
                                                <div class="card container-info-card">
                                                    <div class="card-header align-items-center d-flex">
                                                        <h4 class="card-title mb-0 flex-grow-1">Container Information</h4>
                                                    </div>
                                                    <div class="card-body">
                                                        <div class="table-responsive">
                                                            <table class="table table-bordered" id="containerTable">
                                                                <thead>
                                                                    <tr>
                                                                        <th>#</th>
                                                                        <th>Container Number <span class="red-text">*</span></th>
                                                                        <th>Size <span class="red-text">*</span></th>
                                                                        <th>Transporter <span class="red-text">*</span></th>
                                                                        <th>Driver</th>
                                                                        <th>Actions</th>
                                                                    </tr>
                                                                </thead>
                                                                <tbody id="containerTableBody">
                                                                    <!-- Container rows will be added here dynamically -->
                                                                </tbody>
                                                            </table>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <!-- Bulk Cargo Section -->
                                            <div id="bulkCargoSection" style="display:none;" class="mt-4">
                                                <div class="card bulk-info-card">
                                                    <div class="card-header align-items-center d-flex">
                                                        <h4 class="card-title mb-0 flex-grow-1">Bulk Cargo Information</h4>
                                                    </div>
                                                    <div class="card-body">
                                                        <div class="row">
                                                            <div class="col-md-4 mb-3">
                                                                <label for="bulk_item_count" class="form-label">Number of Items <span class="red-text">*</span></label>
                                                                <input type="number" class="form-control" id="bulk_item_count" name="bulk_item_count" min="1">
                                                            </div>
                                                            
                                                            <div class="col-md-4 mb-3">
                                                                <label for="bulk_tonnage" class="form-label">Total Tonnage <span class="red-text">*</span></label>
                                                                <input type="number" step="0.01" class="form-control" id="bulk_tonnage" name="bulk_tonnage" placeholder="0.00">
                                                            </div>
                                                            
                                                            <div class="col-md-4 mb-3">
                                                                <label for="bulk_truck_count" class="form-label">Number of Trucks <span class="red-text">*</span></label>
                                                                <select class="form-select" id="bulk_truck_count" name="bulk_truck_count" onchange="generateBulkTruckTable()">
                                                                    <option value="" selected disabled>Please select truck count</option>
                                                                    <?php for ($i=1; $i<=40; $i++): ?>
                                                                        <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
                                                                    <?php endfor; ?>
                                                                </select>
                                                            </div>
                                                        </div>
                                                        
                                                        <div class="row">
                                                            <div class="col-md-12 mb-3">
                                                                <label for="bulk_description" class="form-label">Cargo Description <span class="red-text">*</span></label>
                                                                <textarea class="form-control" id="bulk_description" name="bulk_description" rows="3" 
                                                                          placeholder="Enter description of bulk cargo"></textarea>
                                                            </div>
                                                        </div>
                                                        
                                                        <div id="bulkTruckTableSection" style="display:none;">
                                                            <h5 class="mt-4 mb-3">Truck Information</h5>
                                                            <div class="table-responsive">
                                                                <table class="table table-bordered" id="bulkTruckTable">
                                                                    <thead>
                                                                        <tr>
                                                                            <th>#</th>
                                                                            <th>Truck Reg Number <span class="red-text">*</span></th>
                                                                            <th>Transporter <span class="red-text">*</span></th>
                                                                            <th>Driver</th>
                                                                            <th>Tonnage</th>
                                                                            <th>Actions</th>
                                                                        </tr>
                                                                    </thead>
                                                                    <tbody id="bulkTruckTableBody">
                                                                        <!-- Truck rows will be added here dynamically -->
                                                                    </tbody>
                                                                </table>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <!-- Loose Cargo Section -->
                                            <div id="looseCargoSection" style="display:none;" class="mt-4">
                                                <div class="card loose-info-card">
                                                    <div class="card-header align-items-center d-flex">
                                                        <h4 class="card-title mb-0 flex-grow-1">Loose Cargo Information</h4>
                                                    </div>
                                                    <div class="card-body">
                                                        <div class="row">
                                                            <div class="col-md-4 mb-3">
                                                                <label for="loose_item_count" class="form-label">Number of Items <span class="red-text">*</span></label>
                                                                <input type="number" class="form-control" id="loose_item_count" name="loose_item_count" min="1">
                                                            </div>
                                                            
                                                            <div class="col-md-4 mb-3">
                                                                <label for="loose_tonnage" class="form-label">Total Tonnage <span class="red-text">*</span></label>
                                                                <input type="number" step="0.01" class="form-control" id="loose_tonnage" name="loose_tonnage" placeholder="0.00">
                                                            </div>
                                                            
                                                            <div class="col-md-4 mb-3">
                                                                <label for="loose_truck_count" class="form-label">Number of Trucks <span class="red-text">*</span></label>
                                                                <select class="form-select" id="loose_truck_count" name="loose_truck_count" onchange="generateLooseTruckTable()">
                                                                    <option value="" selected disabled>Please select truck count</option>
                                                                    <?php for ($i=1; $i<=40; $i++): ?>
                                                                        <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
                                                                    <?php endfor; ?>
                                                                </select>
                                                            </div>
                                                        </div>
                                                        
                                                        <div class="row">
                                                            <div class="col-md-12 mb-3">
                                                                <label for="loose_description" class="form-label">Cargo Description <span class="red-text">*</span></label>
                                                                <textarea class="form-control" id="loose_description" name="loose_description" rows="3" 
                                                                          placeholder="Enter description of loose cargo"></textarea>
                                                            </div>
                                                        </div>
                                                        
                                                        <div id="looseTruckTableSection" style="display:none;">
                                                            <h5 class="mt-4 mb-3">Truck Information</h5>
                                                            <div class="table-responsive">
                                                                <table class="table table-bordered" id="looseTruckTable">
                                                                    <thead>
                                                                        <tr>
                                                                            <th>#</th>
                                                                            <th>Truck Reg Number <span class="red-text">*</span></th>
                                                                            <th>Transporter <span class="red-text">*</span></th>
                                                                            <th>Driver</th>
                                                                            <th>Tonnage</th>
                                                                            <th>Actions</th>
                                                                        </tr>
                                                                    </thead>
                                                                    <tbody id="looseTruckTableBody">
                                                                        <!-- Truck rows will be added here dynamically -->
                                                                    </tbody>
                                                                </table>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div id="vehicleCargoSection" style="display:none;" class="mt-4">
                                                <div class="card container-info-card">
                                                    <div class="card-header align-items-center d-flex">
                                                        <h4 class="card-title mb-0 flex-grow-1">Vehicle Cargo Information</h4>
                                                        <button type="button" class="btn btn-sm btn-primary" id="addVehicleItemBtn">
                                                            <i class="ri-add-line"></i> Add Vehicle
                                                        </button>
                                                    </div>
                                                    <div class="card-body">
                                                        <div class="row mb-3">
                                                            <div class="col-md-6">
                                                                <label for="vehicle_item_count" class="form-label">Number of Vehicles <span class="red-text">*</span></label>
                                                                <input type="number" class="form-control" id="vehicle_item_count" name="vehicle_item_count" min="1" value="1">
                                                            </div>
                                                        </div>
                                                        
                                                        <div class="table-responsive">
                                                            <table class="table table-bordered" id="vehicleItemsTable">
                                                                <thead>
                                                                    <tr>
                                                                        <th>#</th>
                                                                        <th>Chassis Number <span class="red-text">*</span></th>
                                                                        <th>Car Model</th>
                                                                        <th>Make</th>
                                                                        <th>Year</th>
                                                                        <th>Actions</th>
                                                                    </tr>
                                                                </thead>
                                                                <tbody id="vehicleItemsTableBody">
                                                                    <tr class="vehicle-item-row" id="vehicle-item-row-1">
                                                                        <td>1</td>
                                                                        <td>
                                                                            <input type="text" class="form-control" name="vehicle_chassis_number[]" 
                                                                                   placeholder="Enter chassis number">
                                                                        </td>
                                                                        <td>
                                                                            <input type="text" class="form-control" name="vehicle_car_model[]" 
                                                                                   placeholder="Enter car model">
                                                                        </td>
                                                                        <td>
                                                                            <input type="text" class="form-control" name="vehicle_make[]" 
                                                                                   placeholder="Enter make">
                                                                        </td>
                                                                        <td>
                                                                            <input type="number" class="form-control" name="vehicle_year[]" 
                                                                                   placeholder="Enter year">
                                                                        </td>
                                                                        <td>
                                                                            <button type="button" class="btn btn-sm btn-primary" onclick="editVehicleItem(1)">
                                                                                <i class="ri-edit-2-line"></i>
                                                                            </button>
                                                                            <!-- Hidden fields for vehicle item details -->
                                                                            <input type="hidden" name="vehicle_color[]">
                                                                            <input type="hidden" name="vehicle_engine_number[]">
                                                                            <input type="hidden" name="vehicle_mileage[]">
                                                                            <input type="hidden" name="vehicle_condition[]">
                                                                            <input type="hidden" name="vehicle_remarks[]">
                                                                        </td>
                                                                    </tr>
                                                                </tbody>
                                                            </table>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <!-- Add after the cargo type selection -->
                                            <div class="row" id="truckAssignmentSection">
                                                <div class="col-md-4 mb-3">
                                                    <label for="total_trucks_required" class="form-label">Total Trucks Required <span class="red-text">*</span></label>
                                                    <input type="number" class="form-control" id="total_trucks_required" name="total_trucks_required" min="1">
                                                </div>
                                                
                                                <div class="col-md-4 mb-3">
                                                    <label for="trucks_to_assign" class="form-label">Trucks to Assign Now <span class="red-text">*</span></label>
                                                    <input type="number" class="form-control" id="trucks_to_assign" name="trucks_to_assign" min="1">
                                                </div>

                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Remaining Trucks</label>
                                                    <input type="text" class="form-control" id="remaining_trucks" readonly>
                                                </div>
                                            </div>
                                            
                                            <div class="col-xxl-6 col-md-6 mt-4">
                                                <div>
                                                    <a href="index.php" class="btn btn-danger btn-label waves-effect waves-light rounded-pill">
                                                        <i class="ri-close-circle-line label-icon align-middle rounded-pill fs-16 me-2"></i> Cancel
                                                    </a>
                                                    <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 Shipment
                                                    </button>
                                                </div>
                                            </div>
                                            <!--end col-->
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div> <!-- end col -->
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

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

    <!-- Container Details Modal -->
    <div class="modal fade container-details-modal" id="containerDetailsModal" tabindex="-1" aria-labelledby="containerDetailsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="containerDetailsModalLabel">Container Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="containerDetailsForm">
                        <input type="hidden" id="modalContainerIndex" value="">
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Driver License</label>
                                <input type="text" class="form-control" id="modalDriverLicense">
                            </div>
                        </div>
                        
                        <!-- Dates section -->
                        <h6 class="mt-3 mb-3 border-bottom pb-2">Important Dates</h6>
                        
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">OBR/SCT Received Date</label>
                                <input type="date" class="form-control" id="modalObrSctReceivedDate">
                            </div>
                            
                            <div class="col-md-4 mb-3">
                                <label class="form-label">OBR/TI Validation Date</label>
                                <input type="date" class="form-control" id="modalObrTiValidationDate">
                            </div>
                            
                            <div class="col-md-4 mb-3">
                                <label class="form-label">T1/C2 Approval Date</label>
                                <input type="date" class="form-control" id="modalT1C2ApprovalDate">
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Loading Permit Apply Date</label>
                                <input type="date" class="form-control" id="modalLoadingPermitApplyDate">
                            </div>
                            
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Truck Exit Date</label>
                                <input type="date" class="form-control" id="modalTruckExitDate">
                            </div>
                            
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Truck At Border Date</label>
                                <input type="date" class="form-control" id="modalTruckAtBorderDate">
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Border Crossing Date</label>
                                <input type="date" class="form-control" id="modalBorderCrossingDate">
                            </div>
                            
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Delivery Date</label>
                                <input type="date" class="form-control" id="modalDeliveryDate">
                            </div>
                            
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Empty Return Date</label>
                                <input type="date" class="form-control" id="modalEmptyReturnDate">
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Remarks</label>
                                <textarea class="form-control" id="modalRemarks" rows="2"></textarea>
                            </div>
                        </div>
                    </form>
                </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="saveContainerDetails">Save changes</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bulk Truck Details Modal -->
    <div class="modal fade" id="bulkTruckDetailsModal" tabindex="-1" aria-labelledby="bulkTruckDetailsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="bulkTruckDetailsModalLabel">Bulk Cargo Truck Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="bulkTruckDetailsForm">
                        <input type="hidden" id="modalBulkTruckIndex" value="">
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Truck Registration Number <span class="red-text">*</span></label>
                                <input type="text" class="form-control" id="modalBulkTruckReg" required>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Transporter <span class="red-text">*</span></label>
                                <select class="form-select" id="modalBulkTransporter" required>
                                    <option value="">Please Select A Transporter</option>
                                    <?php 
                                    $result_transporters->data_seek(0);
                                    while($transporter = $result_transporters->fetch_assoc()): 
                                    ?>
                                        <option value="<?php echo $transporter['id']; ?>">
                                            <?php echo htmlspecialchars($transporter['name']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Driver Name</label>
                                <input type="text" class="form-control" id="modalBulkDriverName">
                            </div>
                            
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Driver Phone</label>
                                <input type="text" class="form-control" id="modalBulkDriverPhone">
                            </div>
                            
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Driver License</label>
                                <input type="text" class="form-control" id="modalBulkDriverLicense">
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Tonnage</label>
                                <input type="number" step="0.01" class="form-control" id="modalBulkTonnage" placeholder="0.00">
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label class="form-label">CBM</label>
                                <input type="number" step="0.01" class="form-control" id="modalBulkCBM" placeholder="0.00">
                            </div>
                        </div>
                        
                        <!-- Dates section -->
                        <h6 class="mt-3 mb-3 border-bottom pb-2">Important Dates</h6>
                        
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Loading Date</label>
                                <input type="date" class="form-control" id="modalBulkLoadingDate">
                            </div>
                            
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Truck Exit Date</label>
                                <input type="date" class="form-control" id="modalBulkTruckExitDate">
                            </div>
                            
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Truck At Border Date</label>
                                <input type="date" class="form-control" id="modalBulkTruckAtBorderDate">
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Border Crossing Date</label>
                                <input type="date" class="form-control" id="modalBulkBorderCrossingDate">
                            </div>
                            
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Delivery Date</label>
                                <input type="date" class="form-control" id="modalBulkDeliveryDate">
                            </div>
                            
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Return Date</label>
                                <input type="date" class="form-control" id="modalBulkReturnDate">
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Remarks</label>
                                <textarea class="form-control" id="modalBulkRemarks" rows="2"></textarea>
                            </div>
                        </div>
                    </form>
                </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="saveBulkTruckDetails">Save changes</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Loose Cargo Truck Details Modal -->
    <div class="modal fade" id="looseTruckDetailsModal" tabindex="-1" aria-labelledby="looseTruckDetailsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="looseTruckDetailsModalLabel">Loose Cargo Truck Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="looseTruckDetailsForm">
                        <input type="hidden" id="modalLooseTruckIndex" value="">
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Truck Registration Number <span class="red-text">*</span></label>
                                <input type="text" class="form-control" id="modalLooseTruckReg" required>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Transporter <span class="red-text">*</span></label>
                                <select class="form-select" id="modalLooseTransporter" required>
                                    <option value="">Please Select A Transporter</option>
                                    <?php 
                                    $result_transporters->data_seek(0);
                                    while($transporter = $result_transporters->fetch_assoc()): 
                                    ?>
                                        <option value="<?php echo $transporter['id']; ?>">
                                            <?php echo htmlspecialchars($transporter['name']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Driver Name</label>
                                <input type="text" class="form-control" id="modalLooseDriverName">
                            </div>
                            
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Driver Phone</label>
                                <input type="text" class="form-control" id="modalLooseDriverPhone">
                            </div>
                            
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Driver License</label>
                                <input type="text" class="form-control" id="modalLooseDriverLicense">
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Tonnage</label>
                                <input type="number" step="0.01" class="form-control" id="modalLooseTonnage" placeholder="0.00">
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Number of Items</label>
                                <input type="number" class="form-control" id="modalLooseItemCount" min="1">
                            </div>
                        </div>
                        
                        <!-- Dates section -->
                        <h6 class="mt-3 mb-3 border-bottom pb-2">Important Dates</h6>
                        
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Loading Date</label>
                                <input type="date" class="form-control" id="modalLooseLoadingDate">
                            </div>
                            
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Truck Exit Date</label>
                                <input type="date" class="form-control" id="modalLooseTruckExitDate">
                            </div>
                            
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Truck At Border Date</label>
                                <input type="date" class="form-control" id="modalLooseTruckAtBorderDate">
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Border Crossing Date</label>
                                <input type="date" class="form-control" id="modalLooseBorderCrossingDate">
                            </div>
                            
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Delivery Date</label>
                                <input type="date" class="form-control" id="modalLooseDeliveryDate">
                            </div>
                            
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Return Date</label>
                                <input type="date" class="form-control" id="modalLooseReturnDate">
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Remarks</label>
                                <textarea class="form-control" id="modalLooseRemarks" rows="2"></textarea>
                            </div>
                        </div>
                    </form>
                </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="saveLooseTruckDetails">Save changes</button>
                </div>
            </div>
        </div>
    </div>

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

    <!-- App js -->
    <script src="assets/js/app.js"></script>
    <!--jquery cdn-->
    <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>
// Function to update file number prefix based on destination
function updatePrefix() {
    const destination = document.getElementById('destination').value;
    const fileNumberInput = document.getElementById('fileNumberInput');
    
    if (destination) {
        // Call AJAX to get the next file number for this destination
        $.ajax({
            url: 'generate_transit_code.php',
            type: 'POST',
            data: {
                countryPrefix: destination.split('-')[0],
                cityPrefix: destination.split('-')[1]
            },
            success: function(response) {
                fileNumberInput.value = response;
            },
            error: function() {
                Swal.fire('Error', 'Failed to generate file number', 'error');
            }
        });
    }
}

function toggleCargoSection() {
    const cargoType = document.getElementById('c_type').value;
    const containerNumberDiv = document.getElementById('containerNumberDiv');
    const containerSection = document.getElementById('containerSection');
    const bulkCargoSection = document.getElementById('bulkCargoSection');
    const looseCargoSection = document.getElementById('looseCargoSection');
    const vehicleCargoSection = document.getElementById('vehicleCargoSection');
    
    // Hide all sections first
    containerNumberDiv.style.display = 'none';
    containerSection.style.display = 'none';
    
    if (bulkCargoSection) bulkCargoSection.style.display = 'none';
    if (looseCargoSection) looseCargoSection.style.display = 'none';
    if (vehicleCargoSection) vehicleCargoSection.style.display = 'none';
    
    // Show appropriate section based on cargo type
    if (cargoType === 'Container') {
        containerNumberDiv.style.display = 'block';
    } else if (cargoType === 'Bulk Cargo' && bulkCargoSection) {
        bulkCargoSection.style.display = 'block';
    } else if (cargoType === 'Loose Cargo' && looseCargoSection) {
        looseCargoSection.style.display = 'block';
    } else if (cargoType === 'Vehicle Cargo' && vehicleCargoSection) {
        vehicleCargoSection.style.display = 'block';
    }
    
    // Handle required attributes after toggling visibility
    handleRequiredAttributesOnToggle(cargoType);
}

function addVehicleItem() {
    const tableBody = document.getElementById('vehicleItemsTableBody');
    if (!tableBody) return;
    
    // Get current number of items
    const currentRows = tableBody.querySelectorAll('tr.vehicle-item-row');
    const newIndex = currentRows.length + 1;
    
    // Create new row
    const newRow = document.createElement('tr');
    newRow.className = 'vehicle-item-row';
    newRow.id = `vehicle-item-row-${newIndex}`;
    
    newRow.innerHTML = `
        <td>${newIndex}</td>
        <td>
            <input type="text" class="form-control" name="vehicle_chassis_number[]" id="vehicle_chassis_number_${newIndex}"
                   placeholder="Enter chassis number" tabindex="${newIndex * 10}">
        </td>
        <td>
            <input type="text" class="form-control" name="vehicle_car_model[]" id="vehicle_car_model_${newIndex}" 
                   placeholder="Enter car model" tabindex="${newIndex * 10 + 1}">
        </td>
        <td>
            <input type="text" class="form-control" name="vehicle_make[]" id="vehicle_make_${newIndex}" 
                   placeholder="Enter make" tabindex="${newIndex * 10 + 2}">
        </td>
        <td>
            <input type="number" class="form-control" name="vehicle_year[]" id="vehicle_year_${newIndex}" 
                   placeholder="Enter year" tabindex="${newIndex * 10 + 3}">
        </td>
        <td>
            <button type="button" class="btn btn-sm btn-primary" onclick="editVehicleItem(${newIndex})" tabindex="${newIndex * 10 + 4}">
                <i class="ri-edit-2-line"></i>
            </button>
            <button type="button" class="btn btn-sm btn-danger" onclick="removeVehicleItem(${newIndex})" tabindex="${newIndex * 10 + 5}">
                <i class="ri-delete-bin-line"></i>
            </button>
            <!-- Hidden fields for vehicle item details -->
            <input type="hidden" name="vehicle_color[]" id="vehicle_color_${newIndex}">
            <input type="hidden" name="vehicle_engine_number[]" id="vehicle_engine_number_${newIndex}">
            <input type="hidden" name="vehicle_mileage[]" id="vehicle_mileage_${newIndex}">
            <input type="hidden" name="vehicle_condition[]" id="vehicle_condition_${newIndex}">
            <input type="hidden" name="vehicle_remarks[]" id="vehicle_remarks_${newIndex}">
        </td>
    `;
    
    tableBody.appendChild(newRow);
    
    // Update the vehicle item count
    updateVehicleItemCount();
}

// 3. Add function to remove vehicle items
function removeVehicleItem(index) {
    const row = document.getElementById(`vehicle-item-row-${index}`);
    if (!row) return;
    
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: 'Are you sure?',
            text: `Remove vehicle #${index}?`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, remove it!',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                row.remove();
                // Renumber the remaining rows
                renumberVehicleItems();
                // Update the vehicle item count
                updateVehicleItemCount();
            }
        });
    } else {
        // Fallback if SweetAlert is not available
        if (confirm(`Are you sure you want to remove vehicle #${index}?`)) {
            row.remove();
            renumberVehicleItems();
            updateVehicleItemCount();
        }
    }
}

// 4. Add function to renumber vehicle items
function renumberVehicleItems() {
    const tableBody = document.getElementById('vehicleItemsTableBody');
    if (!tableBody) return;
    
    const rows = tableBody.querySelectorAll('tr.vehicle-item-row');
    rows.forEach((row, index) => {
        // Update row ID
        const newIndex = index + 1;
        row.id = `vehicle-item-row-${newIndex}`;
        
        // Update index number in first cell
        const indexCell = row.querySelector('td:first-child');
        if (indexCell) {
            indexCell.textContent = newIndex;
        }
        
        // Update input IDs and tabindexes
        const inputs = row.querySelectorAll('input');
        inputs.forEach(input => {
            if (input.id) {
                // Update ID with new index
                const baseName = input.id.replace(/\d+$/, '');
                input.id = baseName + newIndex;
            }
            
            // Update tabindex
            if (input.hasAttribute('tabindex')) {
                const baseTabIndex = parseInt(input.getAttribute('tabindex')) % 10;
                input.setAttribute('tabindex', (newIndex * 10) + baseTabIndex);
            }
        });
        
        // Update edit button onclick attribute
        const editButton = row.querySelector('button[onclick^="editVehicleItem"]');
        if (editButton) {
            editButton.setAttribute('onclick', `editVehicleItem(${newIndex})`);
            editButton.setAttribute('tabindex', (newIndex * 10) + 4);
        }
        
        // Update remove button onclick attribute
        const removeButton = row.querySelector('button[onclick^="removeVehicleItem"]');
        if (removeButton) {
            removeButton.setAttribute('onclick', `removeVehicleItem(${newIndex})`);
            removeButton.setAttribute('tabindex', (newIndex * 10) + 5);
        }
    });
}

// 5. Add function to update vehicle item count
function updateVehicleItemCount() {
    const tableBody = document.getElementById('vehicleItemsTableBody');
    const vehicleItemCountInput = document.getElementById('vehicle_item_count');
    
    if (tableBody && vehicleItemCountInput) {
        const itemCount = tableBody.querySelectorAll('tr.vehicle-item-row').length;
        vehicleItemCountInput.value = itemCount;
    }
}

// 6. Add function to edit vehicle item via modal
function editVehicleItem(index) {
    const row = document.getElementById(`vehicle-item-row-${index}`);
    if (!row) return;
    
    // Get current values
    const chassisInput = row.querySelector('input[name="vehicle_chassis_number[]"]');
    const modelInput = row.querySelector('input[name="vehicle_car_model[]"]');
    const makeInput = row.querySelector('input[name="vehicle_make[]"]');
    const yearInput = row.querySelector('input[name="vehicle_year[]"]');
    const colorInput = row.querySelector('input[name="vehicle_color[]"]');
    const engineNumberInput = row.querySelector('input[name="vehicle_engine_number[]"]');
    const mileageInput = row.querySelector('input[name="vehicle_mileage[]"]');
    const conditionInput = row.querySelector('input[name="vehicle_condition[]"]');
    const remarksInput = row.querySelector('input[name="vehicle_remarks[]"]');
    
    if (!chassisInput) return;
    
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: `Vehicle #${index} Details`,
            html: `
                <form id="vehicleItemEditForm" class="text-start">
                    <div class="mb-3">
                        <label class="form-label">Chassis Number <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="modal_vehicle_chassis_number" 
                               value="${chassisInput.value || ''}">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Car Model</label>
                        <input type="text" class="form-control" id="modal_vehicle_car_model" 
                               value="${modelInput ? modelInput.value || '' : ''}">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Make</label>
                        <input type="text" class="form-control" id="modal_vehicle_make" 
                               value="${makeInput ? makeInput.value || '' : ''}">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Year</label>
                        <input type="number" class="form-control" id="modal_vehicle_year" 
                               value="${yearInput ? yearInput.value || '' : ''}">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Color</label>
                        <input type="text" class="form-control" id="modal_vehicle_color" 
                               value="${colorInput ? colorInput.value || '' : ''}">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Engine Number</label>
                        <input type="text" class="form-control" id="modal_vehicle_engine_number" 
                               value="${engineNumberInput ? engineNumberInput.value || '' : ''}">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Mileage</label>
                        <input type="number" class="form-control" id="modal_vehicle_mileage" 
                               value="${mileageInput ? mileageInput.value || '' : ''}">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Condition</label>
                        <select class="form-select" id="modal_vehicle_condition">
                            <option value="">Select Condition</option>
                            <option value="Excellent" ${conditionInput && conditionInput.value === 'Excellent' ? 'selected' : ''}>Excellent</option>
                            <option value="Good" ${conditionInput && conditionInput.value === 'Good' ? 'selected' : ''}>Good</option>
                            <option value="Fair" ${conditionInput && conditionInput.value === 'Fair' ? 'selected' : ''}>Fair</option>
                            <option value="Poor" ${conditionInput && conditionInput.value === 'Poor' ? 'selected' : ''}>Poor</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Remarks</label>
                        <textarea class="form-control" id="modal_vehicle_remarks" rows="2">${remarksInput ? remarksInput.value || '' : ''}</textarea>
                    </div>
                </form>
            `,
            showCancelButton: true,
            confirmButtonText: 'Save',
            cancelButtonText: 'Cancel',
            customClass: {
                confirmButton: 'btn btn-primary',
                cancelButton: 'btn btn-secondary'
            },
            preConfirm: () => {
                // Validate required fields
                const chassisNumber = document.getElementById('modal_vehicle_chassis_number').value;
                
                if (!chassisNumber) {
                    Swal.showValidationMessage('Chassis Number is required');
                    return false;
                }
                
                return {
                    chassisNumber: chassisNumber,
                    carModel: document.getElementById('modal_vehicle_car_model').value,
                    make: document.getElementById('modal_vehicle_make').value,
                    year: document.getElementById('modal_vehicle_year').value,
                    color: document.getElementById('modal_vehicle_color').value,
                    engineNumber: document.getElementById('modal_vehicle_engine_number').value,
                    mileage: document.getElementById('modal_vehicle_mileage').value,
                    condition: document.getElementById('modal_vehicle_condition').value,
                    remarks: document.getElementById('modal_vehicle_remarks').value
                };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                // Update the form fields with modal values
                chassisInput.value = result.value.chassisNumber;
                if (modelInput) modelInput.value = result.value.carModel;
                if (makeInput) makeInput.value = result.value.make;
                if (yearInput) yearInput.value = result.value.year;
                if (colorInput) colorInput.value = result.value.color;
                if (engineNumberInput) engineNumberInput.value = result.value.engineNumber;
                if (mileageInput) mileageInput.value = result.value.mileage;
                if (conditionInput) conditionInput.value = result.value.condition;
                if (remarksInput) remarksInput.value = result.value.remarks;
                
                Swal.fire({
                    title: 'Success!',
                    text: `Vehicle #${index} details have been updated.`,
                    icon: 'success',
                    timer: 2000,
                    showConfirmButton: false
                });
            }
        });
    } else {
        // Fallback if SweetAlert is not available
        alert('Vehicle edit functionality requires SweetAlert library.');
    }
}

// Function to generate container table rows
function generateContainerTable() {
    const containerCount = parseInt(document.getElementById('container_no').value);
    const containerTableBody = document.getElementById('containerTableBody');
    const containerSection = document.getElementById('containerSection');
    
    // Show container section
    containerSection.style.display = 'block';
    
    // Clear existing container rows
    containerTableBody.innerHTML = '';
    
    // Generate rows for each container
    for (let i = 1; i <= containerCount; i++) {
        const row = document.createElement('tr');
        row.id = `container-row-${i}`;
        row.innerHTML = `
            <td>${i}</td>
            <td>
                <input type="text" class="form-control" name="container_code[]" id="container_code_${i}" 
                       placeholder="Enter container number" required>
            </td>
            <td>
                <select class="form-select" name="container_size[]" id="container_size_${i}" required>
                    <option value="">Select Size</option>
                    <option value="20">20ft</option>
                    <option value="40">40ft</option>
                    <option value="40HC">40ft HC</option>
                </select>
            </td>
            <td>
                <select class="form-select" name="transporter[]" id="transporter_${i}" required>
                    <option value="">Select Transporter</option>
                    <?php foreach ($transporters as $transporter): ?>
                        <option value="<?php echo $transporter['id']; ?>">
                            <?php echo htmlspecialchars($transporter['name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </td>
            <td>
                <input type="text" class="form-control" name="driver_name[]" id="driver_name_${i}" 
                       placeholder="Driver name">
            </td>
            <td class="container-action-cell">
                <button type="button" class="btn btn-sm btn-primary" onclick="editContainer(${i})">
                    <i class="ri-edit-2-line"></i> More Details
                </button>
                
                <!-- Hidden fields for container details -->
                <input type="hidden" name="driver_phone_number[]" id="driver_phone_${i}">
                <input type="hidden" name="driver_license[]" id="driver_license_${i}">
                <input type="hidden" name="obr_sct_received_date[]" id="obr_sct_received_date_${i}">
                <input type="hidden" name="obr_ti_validation_date[]" id="obr_ti_validation_date_${i}">
                <input type="hidden" name="t1_c2_approval_date[]" id="t1_c2_approval_date_${i}">
                <input type="hidden" name="loading_permit_apply_date[]" id="loading_permit_apply_date_${i}">
                <input type="hidden" name="truck_exit_date[]" id="truck_exit_date_${i}">
                <input type="hidden" name="truck_at_border_date[]" id="truck_at_border_date_${i}">
                <input type="hidden" name="border_crossing_date[]" id="border_crossing_date_${i}">
                <input type="hidden" name="delivery_date[]" id="delivery_date_${i}">
                <input type="hidden" name="empty_return_date[]" id="empty_return_date_${i}">
                <input type="hidden" name="remarks[]" id="remarks_${i}">
            </td>
        `;
        containerTableBody.appendChild(row);
    }
}

// Function to generate bulk cargo truck table
function generateBulkTruckTable() {
    const truckCount = parseInt(document.getElementById('trucks_to_assign').value);
    if (!truckCount) {
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Please specify number of trucks to assign first'
        });
        return;
    }
    
    const totalRequired = parseInt(document.getElementById('total_trucks_required').value);
    if (truckCount > totalRequired) {
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Trucks to assign cannot exceed total trucks required'
        });
        return;
    }

    const bulkTruckTableBody = document.getElementById('bulkTruckTableBody');
    const bulkTruckTableSection = document.getElementById('bulkTruckTableSection');
    
    // Show truck table section
    bulkTruckTableSection.style.display = 'block';
    
    // Clear existing truck rows
    bulkTruckTableBody.innerHTML = '';
    
    // Generate rows for each truck
    for (let i = 1; i <= truckCount; i++) {
        const row = document.createElement('tr');
        row.id = `bulk-truck-row-${i}`;
        row.innerHTML = `
            <td>${i}</td>
            <td>
                <input type="text" class="form-control" name="bulk_truck_reg[]" id="bulk_truck_reg_${i}" 
                       placeholder="Enter truck reg number" required>
            </td>
            <td>
                <select class="form-select" name="bulk_truck_transporter[]" id="bulk_truck_transporter_${i}" required>
                    <option value="">Select Transporter</option>
                    <?php foreach ($transporters as $transporter): ?>
                        <option value="<?php echo $transporter['id']; ?>">
                            <?php echo htmlspecialchars($transporter['name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </td>
            <td>
                <input type="text" class="form-control" name="bulk_truck_driver[]" id="bulk_truck_driver_${i}" 
                       placeholder="Driver name">
            </td>
            <td>
                <input type="number" step="0.01" class="form-control" name="bulk_truck_tonnage[]" id="bulk_truck_tonnage_${i}" 
                       placeholder="0.00">
            </td>
            <td class="container-action-cell">
                <button type="button" class="btn btn-sm btn-primary" onclick="editBulkTruck(${i})">
                    <i class="ri-edit-2-line"></i> More Details
                </button>
                
                <!-- Hidden fields for truck details -->
                <input type="hidden" name="bulk_truck_driver_phone[]" id="bulk_truck_driver_phone_${i}">
                <input type="hidden" name="bulk_truck_driver_license[]" id="bulk_truck_driver_license_${i}">
                <input type="hidden" name="bulk_truck_cbm[]" id="bulk_truck_cbm_${i}">
                <input type="hidden" name="bulk_truck_loading_date[]" id="bulk_truck_loading_date_${i}">
                <input type="hidden" name="bulk_truck_exit_date[]" id="bulk_truck_exit_date_${i}">
                <input type="hidden" name="bulk_truck_at_border_date[]" id="bulk_truck_at_border_date_${i}">
                <input type="hidden" name="bulk_truck_border_crossing_date[]" id="bulk_truck_border_crossing_date_${i}">
                <input type="hidden" name="bulk_truck_delivery_date[]" id="bulk_truck_delivery_date_${i}">
                <input type="hidden" name="bulk_truck_return_date[]" id="bulk_truck_return_date_${i}">
                <input type="hidden" name="bulk_truck_remarks[]" id="bulk_truck_remarks_${i}">
            </td>
        `;
        bulkTruckTableBody.appendChild(row);
    }
}

// Function to generate loose cargo truck table
function generateLooseTruckTable() {
    const truckCount = parseInt(document.getElementById('trucks_to_assign').value);
    if (!truckCount) {
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Please specify number of trucks to assign first'
        });
        return;
    }
    
    const totalRequired = parseInt(document.getElementById('total_trucks_required').value);
    if (truckCount > totalRequired) {
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Trucks to assign cannot exceed total trucks required'
        });
        return;
    }

    const looseTruckTableBody = document.getElementById('looseTruckTableBody');
    const looseTruckTableSection = document.getElementById('looseTruckTableSection');
    
    // Show truck table section
    looseTruckTableSection.style.display = 'block';
    
    // Clear existing truck rows
    looseTruckTableBody.innerHTML = '';
    
    // Generate rows for each truck
    for (let i = 1; i <= truckCount; i++) {
        const row = document.createElement('tr');
        row.id = `loose-truck-row-${i}`;
        row.innerHTML = `
            <td>${i}</td>
            <td>
                <input type="text" class="form-control" name="loose_truck_reg[]" id="loose_truck_reg_${i}" 
                       placeholder="Enter truck reg number" required>
            </td>
            <td>
                <select class="form-select" name="loose_truck_transporter[]" id="loose_truck_transporter_${i}" required>
                    <option value="">Select Transporter</option>
                    <?php foreach ($transporters as $transporter): ?>
                        <option value="<?php echo $transporter['id']; ?>">
                            <?php echo htmlspecialchars($transporter['name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </td>
            <td>
                <input type="text" class="form-control" name="loose_truck_driver[]" id="loose_truck_driver_${i}" 
                       placeholder="Driver name">
            </td>
            <td>
                <input type="number" step="0.01" class="form-control" name="loose_truck_tonnage[]" id="loose_truck_tonnage_${i}" 
                       placeholder="0.00">
            </td>
            <td class="container-action-cell">
                <button type="button" class="btn btn-sm btn-primary" onclick="editLooseTruck(${i})">
                    <i class="ri-edit-2-line"></i> More Details
                </button>
                
                <!-- Hidden fields for truck details -->
                <input type="hidden" name="loose_truck_driver_phone[]" id="loose_truck_driver_phone_${i}">
                <input type="hidden" name="loose_truck_driver_license[]" id="loose_truck_driver_license_${i}">
                <input type="hidden" name="loose_truck_item_count[]" id="loose_truck_item_count_${i}">
                <input type="hidden" name="loose_truck_loading_date[]" id="loose_truck_loading_date_${i}">
                <input type="hidden" name="loose_truck_exit_date[]" id="loose_truck_exit_date_${i}">
                <input type="hidden" name="loose_truck_at_border_date[]" id="loose_truck_at_border_date_${i}">
                <input type="hidden" name="loose_truck_border_crossing_date[]" id="loose_truck_border_crossing_date_${i}">
                <input type="hidden" name="loose_truck_delivery_date[]" id="loose_truck_delivery_date_${i}">
                <input type="hidden" name="loose_truck_return_date[]" id="loose_truck_return_date_${i}">
                <input type="hidden" name="loose_truck_remarks[]" id="loose_truck_remarks_${i}">
            </td>
        `;
        looseTruckTableBody.appendChild(row);
    }
}

// Function to open container details modal for editing
function editContainer(index) {
    // Set current index in modal
    document.getElementById('modalContainerIndex').value = index;
    
    // Fill modal with current container data
    document.getElementById('modalContainerCode').value = document.getElementById(`container_code_${index}`).value;
    document.getElementById('modalContainerSize').value = document.getElementById(`container_size_${index}`).value;
    document.getElementById('modalTransporter').value = document.getElementById(`transporter_${index}`).value;
    document.getElementById('modalDriverName').value = document.getElementById(`driver_name_${index}`).value;
    document.getElementById('modalDriverPhone').value = document.getElementById(`driver_phone_${index}`).value;
    document.getElementById('modalDriverLicense').value = document.getElementById(`driver_license_${index}`).value;
    document.getElementById('modalObrSctReceivedDate').value = document.getElementById(`obr_sct_received_date_${index}`).value;
    document.getElementById('modalObrTiValidationDate').value = document.getElementById(`obr_ti_validation_date_${index}`).value;
    document.getElementById('modalT1C2ApprovalDate').value = document.getElementById(`t1_c2_approval_date_${index}`).value;
    document.getElementById('modalLoadingPermitApplyDate').value = document.getElementById(`loading_permit_apply_date_${index}`).value;
    document.getElementById('modalTruckExitDate').value = document.getElementById(`truck_exit_date_${index}`).value;
    document.getElementById('modalTruckAtBorderDate').value = document.getElementById(`truck_at_border_date_${index}`).value;
    document.getElementById('modalBorderCrossingDate').value = document.getElementById(`border_crossing_date_${index}`).value;
    document.getElementById('modalDeliveryDate').value = document.getElementById(`delivery_date_${index}`).value;
    document.getElementById('modalEmptyReturnDate').value = document.getElementById(`empty_return_date_${index}`).value;
    document.getElementById('modalRemarks').value = document.getElementById(`remarks_${index}`).value;
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('containerDetailsModal'));
    modal.show();
}

// Function to open bulk truck details modal for editing
function editBulkTruck(index) {
    // Set current index in modal
    document.getElementById('modalBulkTruckIndex').value = index;
    
    // Fill modal with current truck data
    document.getElementById('modalBulkTruckReg').value = document.getElementById(`bulk_truck_reg_${index}`).value;
    document.getElementById('modalBulkTransporter').value = document.getElementById(`bulk_truck_transporter_${index}`).value;
    document.getElementById('modalBulkDriverName').value = document.getElementById(`bulk_truck_driver_${index}`).value;
    document.getElementById('modalBulkDriverPhone').value = document.getElementById(`bulk_truck_driver_phone_${index}`).value;
    document.getElementById('modalBulkDriverLicense').value = document.getElementById(`bulk_truck_driver_license_${index}`).value;
    document.getElementById('modalBulkTonnage').value = document.getElementById(`bulk_truck_tonnage_${index}`).value;
    document.getElementById('modalBulkCBM').value = document.getElementById(`bulk_truck_cbm_${index}`).value;
    document.getElementById('modalBulkLoadingDate').value = document.getElementById(`bulk_truck_loading_date_${index}`).value;
    document.getElementById('modalBulkTruckExitDate').value = document.getElementById(`bulk_truck_exit_date_${index}`).value;
    document.getElementById('modalBulkTruckAtBorderDate').value = document.getElementById(`bulk_truck_at_border_date_${index}`).value;
    document.getElementById('modalBulkBorderCrossingDate').value = document.getElementById(`bulk_truck_border_crossing_date_${index}`).value;
    document.getElementById('modalBulkDeliveryDate').value = document.getElementById(`bulk_truck_delivery_date_${index}`).value;
    document.getElementById('modalBulkReturnDate').value = document.getElementById(`bulk_truck_return_date_${index}`).value;
    document.getElementById('modalBulkRemarks').value = document.getElementById(`bulk_truck_remarks_${index}`).value;
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('bulkTruckDetailsModal'));
    modal.show();
}

// Function to open loose cargo truck details modal for editing
function editLooseTruck(index) {
    // Set current index in modal
    document.getElementById('modalLooseTruckIndex').value = index;
    
    // Fill modal with current truck data
    document.getElementById('modalLooseTruckReg').value = document.getElementById(`loose_truck_reg_${index}`).value;
    document.getElementById('modalLooseTransporter').value = document.getElementById(`loose_truck_transporter_${index}`).value;
    document.getElementById('modalLooseDriverName').value = document.getElementById(`loose_truck_driver_${index}`).value;
    document.getElementById('modalLooseDriverPhone').value = document.getElementById(`loose_truck_driver_phone_${index}`).value;
    document.getElementById('modalLooseDriverLicense').value = document.getElementById(`loose_truck_driver_license_${index}`).value;
    document.getElementById('modalLooseTonnage').value = document.getElementById(`loose_truck_tonnage_${index}`).value;
    document.getElementById('modalLooseItemCount').value = document.getElementById(`loose_truck_item_count_${index}`).value;
    document.getElementById('modalLooseLoadingDate').value = document.getElementById(`loose_truck_loading_date_${index}`).value;
    document.getElementById('modalLooseTruckExitDate').value = document.getElementById(`loose_truck_exit_date_${index}`).value;
    document.getElementById('modalLooseTruckAtBorderDate').value = document.getElementById(`loose_truck_at_border_date_${index}`).value;
    document.getElementById('modalLooseBorderCrossingDate').value = document.getElementById(`loose_truck_border_crossing_date_${index}`).value;
    document.getElementById('modalLooseDeliveryDate').value = document.getElementById(`loose_truck_delivery_date_${index}`).value;
    document.getElementById('modalLooseReturnDate').value = document.getElementById(`loose_truck_return_date_${index}`).value;
    document.getElementById('modalLooseRemarks').value = document.getElementById(`loose_truck_remarks_${index}`).value;
    
    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('looseTruckDetailsModal'));
    modal.show();
}

// Function to save container modal data back to form
function saveContainerModalData() {
    // Get current index from modal
    const index = document.getElementById('modalContainerIndex').value;
    
    // Validate required fields
    const containerCode = document.getElementById('modalContainerCode').value;
    const containerSize = document.getElementById('modalContainerSize').value;
    const transporter = document.getElementById('modalTransporter').value;
    
    if (!containerCode || !containerSize || !transporter) {
        Swal.fire({
            icon: 'error',
            title: 'Required Fields Missing',
            text: 'Please fill in all required fields (Container Number, Size, and Transporter)',
            confirmButtonText: 'OK'
        });
        return false;
    }
    
    // Update form fields with modal values
    document.getElementById(`container_code_${index}`).value = containerCode;
    document.getElementById(`container_size_${index}`).value = containerSize;
    document.getElementById(`transporter_${index}`).value = transporter;
    document.getElementById(`driver_name_${index}`).value = document.getElementById('modalDriverName').value;
    document.getElementById(`driver_phone_${index}`).value = document.getElementById('modalDriverPhone').value;
    document.getElementById(`driver_license_${index}`).value = document.getElementById('modalDriverLicense').value;
    document.getElementById(`obr_sct_received_date_${index}`).value = document.getElementById('modalObrSctReceivedDate').value;
    document.getElementById(`obr_ti_validation_date_${index}`).value = document.getElementById('modalObrTiValidationDate').value;
    document.getElementById(`t1_c2_approval_date_${index}`).value = document.getElementById('modalT1C2ApprovalDate').value;
    document.getElementById(`loading_permit_apply_date_${index}`).value = document.getElementById('modalLoadingPermitApplyDate').value;
    document.getElementById(`truck_exit_date_${index}`).value = document.getElementById('modalTruckExitDate').value;
    document.getElementById(`truck_at_border_date_${index}`).value = document.getElementById('modalTruckAtBorderDate').value;
    document.getElementById(`border_crossing_date_${index}`).value = document.getElementById('modalBorderCrossingDate').value;
    document.getElementById(`delivery_date_${index}`).value = document.getElementById('modalDeliveryDate').value;
    document.getElementById(`empty_return_date_${index}`).value = document.getElementById('modalEmptyReturnDate').value;
    document.getElementById(`remarks_${index}`).value = document.getElementById('modalRemarks').value;
    
    return true;
}

// Function to save bulk truck modal data back to form
function saveBulkTruckModalData() {
    // Get current index from modal
    const index = document.getElementById('modalBulkTruckIndex').value;
    
    // Validate required fields
    const truckReg = document.getElementById('modalBulkTruckReg').value;
    const transporter = document.getElementById('modalBulkTransporter').value;
    
    if (!truckReg || !transporter) {
        Swal.fire({
            icon: 'error',
            title: 'Required Fields Missing',
            text: 'Please fill in all required fields (Truck Reg Number and Transporter)',
            confirmButtonText: 'OK'
        });
        return false;
    }
    
    // Update form fields with modal values
    document.getElementById(`bulk_truck_reg_${index}`).value = truckReg;
    document.getElementById(`bulk_truck_transporter_${index}`).value = transporter;
    document.getElementById(`bulk_truck_driver_${index}`).value = document.getElementById('modalBulkDriverName').value;
    document.getElementById(`bulk_truck_driver_phone_${index}`).value = document.getElementById('modalBulkDriverPhone').value;
    document.getElementById(`bulk_truck_driver_license_${index}`).value = document.getElementById('modalBulkDriverLicense').value;
    document.getElementById(`bulk_truck_tonnage_${index}`).value = document.getElementById('modalBulkTonnage').value;
    document.getElementById(`bulk_truck_cbm_${index}`).value = document.getElementById('modalBulkCBM').value;
    document.getElementById(`bulk_truck_loading_date_${index}`).value = document.getElementById('modalBulkLoadingDate').value;
    document.getElementById(`bulk_truck_exit_date_${index}`).value = document.getElementById('modalBulkTruckExitDate').value;
    document.getElementById(`bulk_truck_at_border_date_${index}`).value = document.getElementById('modalBulkTruckAtBorderDate').value;
    document.getElementById(`bulk_truck_border_crossing_date_${index}`).value = document.getElementById('modalBulkBorderCrossingDate').value;
    document.getElementById(`bulk_truck_delivery_date_${index}`).value = document.getElementById('modalBulkDeliveryDate').value;
    document.getElementById(`bulk_truck_return_date_${index}`).value = document.getElementById('modalBulkReturnDate').value;
    document.getElementById(`bulk_truck_remarks_${index}`).value = document.getElementById('modalBulkRemarks').value;
    
    return true;
}

// Function to save loose truck modal data back to form
function saveLooseTruckModalData() {
    // Get current index from modal
    const index = document.getElementById('modalLooseTruckIndex').value;
    
    // Validate required fields
    const truckReg = document.getElementById('modalLooseTruckReg').value;
    const transporter = document.getElementById('modalLooseTransporter').value;
    
    if (!truckReg || !transporter) {
        Swal.fire({
            icon: 'error',
            title: 'Required Fields Missing',
            text: 'Please fill in all required fields (Truck Reg Number and Transporter)',
            confirmButtonText: 'OK'
        });
        return false;
    }
    
    // Update form fields with modal values
    document.getElementById(`loose_truck_reg_${index}`).value = truckReg;
    document.getElementById(`loose_truck_transporter_${index}`).value = transporter;
    document.getElementById(`loose_truck_driver_${index}`).value = document.getElementById('modalLooseDriverName').value;
    document.getElementById(`loose_truck_driver_phone_${index}`).value = document.getElementById('modalLooseDriverPhone').value;
    document.getElementById(`loose_truck_driver_license_${index}`).value = document.getElementById('modalLooseDriverLicense').value;
    document.getElementById(`loose_truck_tonnage_${index}`).value = document.getElementById('modalLooseTonnage').value;
    document.getElementById(`loose_truck_item_count_${index}`).value = document.getElementById('modalLooseItemCount').value;
    document.getElementById(`loose_truck_loading_date_${index}`).value = document.getElementById('modalLooseLoadingDate').value;
    document.getElementById(`loose_truck_exit_date_${index}`).value = document.getElementById('modalLooseTruckExitDate').value;
    document.getElementById(`loose_truck_at_border_date_${index}`).value = document.getElementById('modalLooseTruckAtBorderDate').value;
    document.getElementById(`loose_truck_border_crossing_date_${index}`).value = document.getElementById('modalLooseBorderCrossingDate').value;
    document.getElementById(`loose_truck_delivery_date_${index}`).value = document.getElementById('modalLooseDeliveryDate').value;
    document.getElementById(`loose_truck_return_date_${index}`).value = document.getElementById('modalLooseReturnDate').value;
    document.getElementById(`loose_truck_remarks_${index}`).value = document.getElementById('modalLooseRemarks').value;
    
    return true;
}

// Function to validate form before submission
function validateForm() {
    const cargoType = document.getElementById('c_type').value;
    const customer = document.getElementById('customer-name').value;
    const consignee = document.getElementById('consignee_name').value;
    const destination = document.getElementById('destination').value;
    const oblNo = document.getElementById('obl_no').value;
    const freeDetention = document.getElementById('free_detention').value;
    
    // Validate basic required fields
    if (!cargoType || !customer || !consignee || !destination || !oblNo || !freeDetention) {
        Swal.fire({
            icon: 'error',
            title: 'Required Fields Missing',
            text: 'Please fill in all required fields (marked with *)',
            confirmButtonText: 'OK'
        });
        return false;
    }
    
    // Validate cargo type specific fields
    if (cargoType === 'Container') {
        const containerCount = parseInt(document.getElementById('container_no').value);
        
        if (!containerCount) {
            Swal.fire({
                icon: 'error',
                title: 'Container Count Required',
                text: 'Please select the number of containers',
                confirmButtonText: 'OK'
            });
            return false;
        }
        
        // Check each container's required fields
        for (let i = 1; i <= containerCount; i++) {
            const containerCode = document.getElementById(`container_code_${i}`).value;
            const containerSize = document.getElementById(`container_size_${i}`).value;
            const transporter = document.getElementById(`transporter_${i}`).value;
            
            if (!containerCode || !containerSize || !transporter) {
                Swal.fire({
                    icon: 'error',
                    title: 'Container Details Missing',
                    text: `Please fill in all required fields for Container #${i}`,
                    confirmButtonText: 'OK'
                });
                return false;
            }
        }
    } else if (cargoType === 'Bulk Cargo') {
        // Validate bulk cargo specific fields
        const bulkItemCount = document.getElementById('bulk_item_count').value;
        const bulkTonnage = document.getElementById('bulk_tonnage').value;
        const bulkTruckCount = document.getElementById('bulk_truck_count').value;
        const bulkDescription = document.getElementById('bulk_description').value;
        
        if (!bulkItemCount || !bulkTonnage || !bulkTruckCount || !bulkDescription) {
            Swal.fire({
                icon: 'error',
                title: 'Bulk Cargo Details Missing',
                text: 'Please fill in all required fields for Bulk Cargo',
                confirmButtonText: 'OK'
            });
            return false;
        }
        
        // Validate truck details
        const truckCount = parseInt(bulkTruckCount);
        for (let i = 1; i <= truckCount; i++) {
            const truckReg = document.getElementById(`bulk_truck_reg_${i}`).value;
            const transporter = document.getElementById(`bulk_truck_transporter_${i}`).value;
            
            if (!truckReg || !transporter) {
                Swal.fire({
                    icon: 'error',
                    title: 'Truck Details Missing',
                    text: `Please fill in all required fields for Truck #${i}`,
                    confirmButtonText: 'OK'
                });
                return false;
            }
        }
    } else if (cargoType === 'Loose Cargo') {
        // Validate loose cargo specific fields
        const looseItemCount = document.getElementById('loose_item_count').value;
        const looseTonnage = document.getElementById('loose_tonnage').value;
        const looseTruckCount = document.getElementById('loose_truck_count').value;
        const looseDescription = document.getElementById('loose_description').value;
        
        if (!looseItemCount || !looseTonnage || !looseTruckCount || !looseDescription) {
            Swal.fire({
                icon: 'error',
                title: 'Loose Cargo Details Missing',
                text: 'Please fill in all required fields for Loose Cargo',
                confirmButtonText: 'OK'
            });
            return false;
        }
        
        // Validate truck details
        const truckCount = parseInt(looseTruckCount);
        for (let i = 1; i <= truckCount; i++) {
            const truckReg = document.getElementById(`loose_truck_reg_${i}`).value;
            const transporter = document.getElementById(`loose_truck_transporter_${i}`).value;
            
            if (!truckReg || !transporter) {
                Swal.fire({
                    icon: 'error',
                    title: 'Truck Details Missing',
                    text: `Please fill in all required fields for Truck #${i}`,
                    confirmButtonText: 'OK'
                });
                return false;
            }
        }
    } else if (cargoType === 'Vehicle Cargo') {
        // Validate vehicle cargo specific fields
        const vehicleItemCount = document.getElementById('vehicle_item_count').value;
        
        if (!vehicleItemCount || vehicleItemCount < 1) {
            Swal.fire({
                icon: 'error',
                title: 'Vehicle Details Missing',
                text: 'Please enter at least one vehicle',
                confirmButtonText: 'OK'
            });
            return false;
        }
        
        // Check if chassis numbers are provided for each vehicle
        const chassisInputs = document.querySelectorAll('input[name="vehicle_chassis_number[]"]');
        let missingChassis = false;
        
        chassisInputs.forEach((input, index) => {
            if (!input.value.trim()) {
                missingChassis = true;
                Swal.fire({
                    icon: 'error',
                    title: 'Vehicle Details Missing',
                    text: `Please enter chassis number for Vehicle #${index + 1}`,
                    confirmButtonText: 'OK'
                });
                return false;
            }
        });
        
        if (missingChassis) {
            return false;
        }
    }    
    
    // Add truck assignment validation
    if (cargoType === 'Bulk Cargo' || cargoType === 'Loose Cargo') {
        const totalRequired = parseInt(document.getElementById('total_trucks_required').value);
        const toAssign = parseInt(document.getElementById('trucks_to_assign').value);
        
        if (!totalRequired) {
            Swal.fire({
                icon: 'error',
                title: 'Validation Error',
                text: 'Please specify total trucks required'
            });
            return false;
        }
        
        if (!toAssign) {
            Swal.fire({
                icon: 'error',
                title: 'Validation Error',
                text: 'Please specify number of trucks to assign'
            });
            return false;
        }
        
        if (toAssign > totalRequired) {
            Swal.fire({
                icon: 'error',
                title: 'Validation Error',
                text: 'Trucks to assign cannot exceed total trucks required'
            });
            return false;
        }
    }
    
    return true;
}

// Initialize form when document is ready
document.addEventListener('DOMContentLoaded', function() {
    // Initialize Select2
    $('.js-example-basic-single').select2();
    
     // Add event listener for Add Vehicle Button
    const addVehicleItemBtn = document.getElementById('addVehicleItemBtn');
    if (addVehicleItemBtn) {
        addVehicleItemBtn.addEventListener('click', function() {
            addVehicleItem();
        });
    }
    
    // Set up modal save buttons
    document.getElementById('saveContainerDetails').addEventListener('click', function() {
        if (saveContainerModalData()) {
            // Close modal
            const modal = bootstrap.Modal.getInstance(document.getElementById('containerDetailsModal'));
            modal.hide();
            
            // Show success toast
            Swal.fire({
                icon: 'success',
                title: 'Container Details Updated',
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000
            });
        }
    });
    
    document.getElementById('saveBulkTruckDetails').addEventListener('click', function() {
        if (saveBulkTruckModalData()) {
            // Close modal
            const modal = bootstrap.Modal.getInstance(document.getElementById('bulkTruckDetailsModal'));
            modal.hide();
            
            // Show success toast
            Swal.fire({
                icon: 'success',
                title: 'Bulk Truck Details Updated',
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000
            });
        }
    });
    
    document.getElementById('saveLooseTruckDetails').addEventListener('click', function() {
        if (saveLooseTruckModalData()) {
            // Close modal
            const modal = bootstrap.Modal.getInstance(document.getElementById('looseTruckDetailsModal'));
            modal.hide();
            
            // Show success toast
            Swal.fire({
                icon: 'success',
                title: 'Loose Cargo Truck Details Updated',
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000
            });
        }
    });
    
    // Add form validation before submission
    document.getElementById('transitShipmentForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        if (validateForm()) {
            // Show loading spinner
            Swal.fire({
                title: 'Saving...',
                text: 'Please wait while we save your shipment',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            // Submit form
            this.submit();
        }
    });
    
    // Update currency display
    document.getElementById('currency').addEventListener('change', function() {
        const currencySymbol = this.value;
        document.querySelectorAll('.currency-symbol').forEach(span => {
            span.textContent = currencySymbol;
        });
    });
    
    // Trigger destination change to get initial file number
    if (document.getElementById('destination').value) {
        updatePrefix();
    }
    
    // Initialize truck assignment tracking
    function initTruckAssignment() {
        const truckSection = document.getElementById('truckAssignmentSection');
        const totalInput = document.getElementById('total_trucks_required');
        const assignInput = document.getElementById('trucks_to_assign');
        const remainingInput = document.getElementById('remaining_trucks');
        
        // Hide truck assignment section initially
        truckSection.style.display = 'none';
        
        function updateRemainingTrucks() {
            const total = parseInt(totalInput.value) || 0;
            const assigned = parseInt(assignInput.value) || 0;
            const remaining = total - assigned;
            
            remainingInput.value = remaining;
            
            // Validate assignment
            if (assigned > total) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Warning',
                    text: 'Trucks to assign cannot exceed total trucks required'
                });
                assignInput.value = total;
                updateRemainingTrucks();
            }
        }
        
        // Add event listeners
        totalInput.addEventListener('change', updateRemainingTrucks);
        assignInput.addEventListener('change', updateRemainingTrucks);
        
        // Update toggleCargoSection to handle truck section visibility
        const originalToggle = window.toggleCargoSection;
        window.toggleCargoSection = function() {
            originalToggle();
            const cargoType = document.getElementById('c_type').value;
            
            if (cargoType === 'Bulk Cargo' || cargoType === 'Loose Cargo') {
                truckSection.style.display = 'flex';
            } else {
                truckSection.style.display = 'none';
                // Reset values when switching cargo types
                totalInput.value = '';
                assignInput.value = '';
                remainingInput.value = '';
            }
        };
    }
    
    initTruckAssignment();
    
    // Update form submission handler
    document.getElementById('transitShipmentForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        if (validateForm()) {
            // Show loading spinner
            Swal.fire({
                title: 'Saving...',
                text: 'Please wait while we save your shipment',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            // Submit form
            this.submit();
        }
    });
});
</script>
</body>
</html>