<?php
session_start();
include 'layouts/dbconn.php';

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

// Check if file ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    $_SESSION['error_message'] = "No file ID provided";
    header('Location: file_list.php');
    exit();
}

$file_id = intval($_GET['id']);

// Get user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email, role_id 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'];
    $role_id = $row_user_details['role_id'];
}

// Check user permissions
function hasPermission($role_id, $permission) {
    // Define permissions for different roles
    $permissions = [
        '1' => ['view', 'edit', 'delete', 'approve', 'invoice'], // Admin has all permissions
        '2' => ['view', 'edit', 'approve', 'invoice'], // General Manager
        '3' => ['view', 'edit', 'invoice'], // Operations
        '4' => ['view', 'edit', 'invoice'], // Finance
        '5' => ['view', 'edit', 'invoice'], // Declaration Officer
        '6' => ['view', 'edit', 'invoice'], // Shipping Line Clerk
        '7' => ['view', 'edit', 'invoice'], // Transport Supervisor
    ];
    
    if (isset($permissions[$role_id]) && in_array($permission, $permissions[$role_id])) {
        return true;
    }
    
    return false;
}

// Verify user has edit permissions
if (!hasPermission($role_id, 'edit')) {
    $_SESSION['error_message'] = "You don't have permission to edit files";
    header('Location: file_list.php');
    exit();
}

// Get file details
$query = "SELECT f.*, c.first_name as customer_name 
          FROM files f 
          LEFT JOIN customers c ON f.customer = c.customer_id 
          WHERE f.id = ?";

$stmt = $conn->prepare($query);
$stmt->bind_param('i', $file_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "File not found";
    header('Location: file_list.php');
    exit();
}

$file = $result->fetch_assoc();
$file_number = $file['file_number'];
$file_type = $file['local/transit']; // 1 = Local, 2 = Transit
$cargo_type = $file['c_type'] ?? 'Container'; // Get cargo type, default to Container

// Get container details if cargo type is Container
$containers = [];
if ($cargo_type === 'Container') {
    $container_query = "SELECT * FROM container_details WHERE file_number = ? ORDER BY id ASC";
    $container_stmt = $conn->prepare($container_query);
    $container_stmt->bind_param('s', $file_number);
    $container_stmt->execute();
    $container_result = $container_stmt->get_result();

    if ($container_result->num_rows > 0) {
        while ($row = $container_result->fetch_assoc()) {
            $containers[] = $row;
        }
    }
}

// Get loose cargo items if cargo type is not Container
$loose_cargo_items = [];
if ($cargo_type !== 'Container') {
    $loose_cargo_query = "SELECT * FROM loose_cargo_items WHERE file_number = ? ORDER BY id ASC";
    $loose_cargo_stmt = $conn->prepare($loose_cargo_query);
    $loose_cargo_stmt->bind_param('s', $file_number);
    $loose_cargo_stmt->execute();
    $loose_cargo_result = $loose_cargo_stmt->get_result();

    if ($loose_cargo_result->num_rows > 0) {
        while ($row = $loose_cargo_result->fetch_assoc()) {
            $loose_cargo_items[] = $row;
        }
    }
}

// Get charges details
$charges_query = "SELECT * FROM charges WHERE file_number = ?";
$charges_stmt = $conn->prepare($charges_query);
$charges_stmt->bind_param('s', $file_number);
$charges_stmt->execute();
$charges_result = $charges_stmt->get_result();
$charges = $charges_result->fetch_assoc();

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

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

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Start transaction
    $conn->begin_transaction();
    
    try {
        // Update main file information
        $updateFields = [
            'customer' => $_POST['customer'] ?? $file['customer'],
            'consignee_name' => $_POST['consignee_name'] ?? $file['consignee_name'],
            'trans_type' => $_POST['trans_type'] ?? $file['trans_type'],
            'transporter' => $_POST['transporter'] ?? $file['transporter'],
            'destination' => $_POST['destination'] ?? $file['destination'],
            'currency' => $_POST['currency'] ?? $file['currency'],
            'obl_no' => $_POST['obl_no'] ?? $file['obl_no'],
            'vno' => $_POST['vno'] ?? $file['vno'],
            'port' => $_POST['port'] ?? $file['port'],
            'remarks' => $_POST['remarks'] ?? $file['remarks'],
            'free_detention' => $_POST['free_detention'] ?? $file['free_detention']
        ];
        
        if (!empty($_POST['eta'])) {
            $updateFields['eta'] = date('Y-m-d', strtotime($_POST['eta']));
        }
        
        if ($file_type == 2) { // Transit specific fields
            if (!empty($_POST['initial_eta'])) {
                $updateFields['initial_eta'] = date('Y-m-d', strtotime($_POST['initial_eta']));
            }
            
            if (!empty($_POST['pre_alert_received_date'])) {
                $updateFields['pre_alert_received_date'] = date('Y-m-d', strtotime($_POST['pre_alert_received_date']));
            }
            
            if (!empty($_POST['discharge_date'])) {
                $updateFields['discharge_date'] = date('Y-m-d', strtotime($_POST['discharge_date']));
            }
            
            // Moved from container to file level
            if (!empty($_POST['delivery_order_apply_date'])) {
                $updateFields['delivery_order_apply_date'] = date('Y-m-d', strtotime($_POST['delivery_order_apply_date']));
            }
            
            if (!empty($_POST['delivery_order_received_date'])) {
                $updateFields['delivery_order_received_date'] = date('Y-m-d', strtotime($_POST['delivery_order_received_date']));
            }
        }
        
        // Build update query
        $updateQuery = "UPDATE files SET ";
        $updateParams = [];
        $updateTypes = "";
        
        foreach ($updateFields as $field => $value) {
            $updateQuery .= "$field = ?, ";
            $updateParams[] = $value;
            
            if (is_int($value)) {
                $updateTypes .= "i";
            } else {
                $updateTypes .= "s";
            }
        }
        
        // Remove trailing comma from the last field
        $updateQuery = rtrim($updateQuery, ', ');
        $updateQuery .= " WHERE id = ?";
        $updateParams[] = $file_id;
        $updateTypes .= "i";
        
        $updateStmt = $conn->prepare($updateQuery);
        if (!$updateStmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        
        // Bind parameters dynamically
        $bindParams = [$updateTypes];
        foreach ($updateParams as $key => $value) {
            $bindParams[] = &$updateParams[$key];
        }
        
        call_user_func_array([$updateStmt, 'bind_param'], $bindParams);
        
        if (!$updateStmt->execute()) {
            throw new Exception("Execute failed: " . $updateStmt->error);
        }
        
        // Update cargo-specific data
        if ($cargo_type === 'Container') {
            // Update container details if provided
            if (isset($_POST['container_id']) && is_array($_POST['container_id'])) {
                foreach ($_POST['container_id'] as $index => $container_id) {
                    if (empty($container_id)) continue;
                    
                    $containerFields = [
                        'container_code' => $_POST['container_code'][$index] ?? '',
                        'container_size' => $_POST['container_size'][$index] ?? '',
                        'transporter_name' => $_POST['transporter_name'][$index] ?? '',
                        'driver_name' => $_POST['driver_name'][$index] ?? '',
                        'driver_phone_number' => $_POST['driver_phone_number'][$index] ?? '',
                        'driver_license' => $_POST['driver_license'][$index] ?? '',
                        'way_bill' => $_POST['way_bill'][$index] ?? '',
                        'remarks' => $_POST['container_remarks'][$index] ?? ''
                    ];
                    
                    // Handle dates based on shipment type
                    if ($file_type == 2) { // Transit
                        $dateFields = [
                            'obr_sct_received_date', 'obr_ti_validation_date',
                            't1_c2_approval_date', 'loading_permit_apply_date',
                            'truck_exit_date', 'truck_at_border_date',
                            'border_crossing_date', 'delivery_date',
                            'empty_return_date'
                        ];
                        
                        foreach ($dateFields as $dateField) {
                            if (isset($_POST[$dateField][$index]) && !empty($_POST[$dateField][$index])) {
                                $containerFields[$dateField] = date('Y-m-d', strtotime($_POST[$dateField][$index]));
                            }
                        }
                    } else { // Local
                        if (isset($_POST['load_date'][$index]) && !empty($_POST['load_date'][$index])) {
                            $containerFields['load_date'] = date('Y-m-d', strtotime($_POST['load_date'][$index]));
                        }
                        
                        if (isset($_POST['offload_date'][$index]) && !empty($_POST['offload_date'][$index])) {
                            $containerFields['offload_date'] = date('Y-m-d', strtotime($_POST['offload_date'][$index]));
                        }
                    }
                    
                    // Build container update query
                    $containerUpdateQuery = "UPDATE container_details SET ";
                    $containerParams = [];
                    $containerTypes = "";
                    
                    foreach ($containerFields as $field => $value) {
                        if ($value !== null) {
                            $containerUpdateQuery .= "$field = ?, ";
                            $containerParams[] = $value;
                            $containerTypes .= "s";
                        }
                    }
                    
                    // Remove trailing comma from the last field
                    $containerUpdateQuery = rtrim($containerUpdateQuery, ', ');
                    $containerUpdateQuery .= " WHERE id = ?";
                    $containerParams[] = $container_id;
                    $containerTypes .= "i";
                    
                    $containerUpdateStmt = $conn->prepare($containerUpdateQuery);
                    if (!$containerUpdateStmt) {
                        throw new Exception("Container prepare failed: " . $conn->error);
                    }
                    
                    // Bind parameters dynamically
                    $containerBindParams = [$containerTypes];
                    foreach ($containerParams as $key => $value) {
                        $containerBindParams[] = &$containerParams[$key];
                    }
                    
                    call_user_func_array([$containerUpdateStmt, 'bind_param'], $containerBindParams);
                    
                    if (!$containerUpdateStmt->execute()) {
                        throw new Exception("Container execute failed: " . $containerUpdateStmt->error);
                    }
                }
            }
        } else {
            // Update loose cargo items if provided
            if (isset($_POST['loose_cargo_id']) && is_array($_POST['loose_cargo_id'])) {
                foreach ($_POST['loose_cargo_id'] as $index => $item_id) {
                    // Skip if no ID is provided (for new items)
                    if (empty($item_id) && intval($item_id) === 0) {
                        // Insert new loose cargo item
                        $insertQuery = "INSERT INTO loose_cargo_items (
                            file_number, chassis_number, car_model, cbm, 
                            transporter, driver_name, driver_phone, driver_license, remarks
                        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
                        
                        $insertParams = [
                            $file_number,
                            $_POST['chassis_number'][$index] ?? '',
                            $_POST['car_model'][$index] ?? '',
                            isset($_POST['cbm'][$index]) ? floatval($_POST['cbm'][$index]) : null,
                            $_POST['loose_transporter'][$index] ?? '',
                            $_POST['loose_driver_name'][$index] ?? '',
                            $_POST['loose_driver_phone'][$index] ?? '',
                            $_POST['loose_driver_license'][$index] ?? '',
                            $_POST['loose_remarks'][$index] ?? ''
                        ];
                        
                        $insertStmt = $conn->prepare($insertQuery);
                        $insertStmt->bind_param('sssdsssss', ...$insertParams);
                        
                        if (!$insertStmt->execute()) {
                            throw new Exception("Failed to insert loose cargo item: " . $insertStmt->error);
                        }
                    } else {
                        // Update existing loose cargo item
                        $looseCargoFields = [
                            'chassis_number' => $_POST['chassis_number'][$index] ?? '',
                            'car_model' => $_POST['car_model'][$index] ?? '',
                            'transporter' => $_POST['loose_transporter'][$index] ?? '',
                            'driver_name' => $_POST['loose_driver_name'][$index] ?? '',
                            'driver_phone' => $_POST['loose_driver_phone'][$index] ?? '',
                            'driver_license' => $_POST['loose_driver_license'][$index] ?? '',
                            'remarks' => $_POST['loose_remarks'][$index] ?? ''
                        ];
                        
                        // Handle numeric values
                        if (isset($_POST['cbm'][$index]) && is_numeric($_POST['cbm'][$index])) {
                            $looseCargoFields['cbm'] = floatval($_POST['cbm'][$index]);
                        }
                        
                        // Build update query
                        $looseCargoUpdateQuery = "UPDATE loose_cargo_items SET ";
                        $looseCargoParams = [];
                        $looseCargoTypes = "";
                        
                        foreach ($looseCargoFields as $field => $value) {
                            $looseCargoUpdateQuery .= "$field = ?, ";
                            $looseCargoParams[] = $value;
                            
                            if (is_float($value)) {
                                $looseCargoTypes .= "d"; // Decimal/Double
                            } else {
                                $looseCargoTypes .= "s"; // String
                            }
                        }
                        
                        // Remove trailing comma
                        $looseCargoUpdateQuery = rtrim($looseCargoUpdateQuery, ', ');
                        $looseCargoUpdateQuery .= " WHERE id = ?";
                        $looseCargoParams[] = $item_id;
                        $looseCargoTypes .= "i";
                        
                        $looseCargoUpdateStmt = $conn->prepare($looseCargoUpdateQuery);
                        
                        if (!$looseCargoUpdateStmt) {
                            throw new Exception("Loose cargo prepare failed: " . $conn->error);
                        }
                        
                        // Bind parameters dynamically
                        $looseCargoBindParams = [$looseCargoTypes];
                        foreach ($looseCargoParams as $key => $value) {
                            $looseCargoBindParams[] = &$looseCargoParams[$key];
                        }
                        
                        call_user_func_array([$looseCargoUpdateStmt, 'bind_param'], $looseCargoBindParams);
                        
                        if (!$looseCargoUpdateStmt->execute()) {
                            throw new Exception("Loose cargo execute failed: " . $looseCargoUpdateStmt->error);
                        }
                    }
                }
            }
            
            // Update bulk cargo info if needed
            if (isset($_POST['bulk_item_count'])) {
                $bulkUpdateQuery = "UPDATE files SET bulk_item_count = ?, bulk_cbm = ? WHERE id = ?";
                $bulkUpdateParams = [
                    intval($_POST['bulk_item_count']),
                    floatval($_POST['bulk_cbm']),
                    $file_id
                ];
                
                $bulkUpdateStmt = $conn->prepare($bulkUpdateQuery);
                $bulkUpdateStmt->bind_param('idi', ...$bulkUpdateParams);
                
                if (!$bulkUpdateStmt->execute()) {
                    throw new Exception("Bulk cargo update failed: " . $bulkUpdateStmt->error);
                }
            }
        }
        
        // Update charges if provided
        if (isset($_POST['port_charge']) || isset($_POST['wharfage_charge'])) {
            $chargeFields = [];
            
            if (isset($_POST['port_charge']) && is_numeric($_POST['port_charge'])) {
                $chargeFields['port_charge'] = floatval($_POST['port_charge']);
            }
            
            if (isset($_POST['wharfage_charge']) && is_numeric($_POST['wharfage_charge'])) {
                $chargeFields['wharfage_charge'] = floatval($_POST['wharfage_charge']);
            }
            
            if (isset($_POST['port_charges_paid_date']) && !empty($_POST['port_charges_paid_date'])) {
                $chargeFields['port_charges_paid_date'] = date('Y-m-d', strtotime($_POST['port_charges_paid_date']));
            }
            
            if (isset($_POST['whafage_paid_date']) && !empty($_POST['whafage_paid_date'])) {
                $chargeFields['whafage_paid_date'] = date('Y-m-d', strtotime($_POST['whafage_paid_date']));
            }
            
            if (!empty($chargeFields)) {
                // Build charge update query
                $chargeUpdateQuery = "UPDATE charges SET ";
                $chargeParams = [];
                $chargeTypes = "";
                
                foreach ($chargeFields as $field => $value) {
                    $chargeUpdateQuery .= "$field = ?, ";
                    $chargeParams[] = $value;
                    
                    if (is_float($value)) {
                        $chargeTypes .= "d"; // Decimal/Double
                    } else {
                        $chargeTypes .= "s"; // String (including dates)
                    }
                }
                
                $chargeUpdateQuery .= "user_id = ? WHERE file_number = ?";
                $chargeParams[] = $user_id;
                $chargeParams[] = $file_number;
                $chargeTypes .= "is";
                
                $chargeUpdateStmt = $conn->prepare($chargeUpdateQuery);
                if (!$chargeUpdateStmt) {
                    throw new Exception("Charge prepare failed: " . $conn->error);
                }
                
                // Bind parameters dynamically
                $chargeBindParams = [$chargeTypes];
                foreach ($chargeParams as $key => $value) {
                    $chargeBindParams[] = &$chargeParams[$key];
                }
                
                call_user_func_array([$chargeUpdateStmt, 'bind_param'], $chargeBindParams);
                
                if (!$chargeUpdateStmt->execute()) {
                    throw new Exception("Charge execute failed: " . $chargeUpdateStmt->error);
                }
            }
        }
        
        // Create notification
        $notif_message = "File {$file_number} has been updated by {$username}.";
        $notif_query = "INSERT INTO notifications (file_id, file_number, notif_message, notif_message_id, created_at) 
                        VALUES (?, ?, ?, 2, NOW())";
        
        $notif_stmt = $conn->prepare($notif_query);
        $notif_stmt->bind_param('iss', $file_id, $file_number, $notif_message);
        $notif_stmt->execute();
        
        // Commit the transaction
        $conn->commit();
        
        $_SESSION['success_message'] = "File updated successfully";
        header("Location: view_file.php?id=$file_id");
        exit();
        
    } catch (Exception $e) {
        // Rollback the transaction
        $conn->rollback();
        $_SESSION['error_message'] = "Error updating file: " . $e->getMessage();
    }
}

// Format date helper function
function formatDate($date) {
    if (empty($date) || $date == '0000-00-00' || $date == '0000-00-00 00:00:00') {
        return '';
    }
    return date('Y-m-d', strtotime($date));
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Edit Shipment File')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    
    <!-- Modal positioning fixes -->
    <style>
    /* Container Management Table Styling */
    #containerTable, #looseCargoTable {
        border-collapse: collapse;
        width: 100%;
    }

    #containerTable th, #looseCargoTable th {
        background-color: #f8f9fa;
        font-weight: 600;
        padding: 12px 8px;
        vertical-align: middle;
    }

    #containerTable td, #looseCargoTable td {
        padding: 10px 8px;
        vertical-align: middle;
    }

    #containerTable tr:nth-child(even), #looseCargoTable tr:nth-child(even) {
        background-color: rgba(0, 0, 0, 0.02);
    }

    .text-danger {
        color: #dc3545;
    }

    /* Card header with add button */
    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    /* Button styling */
    .btn-sm {
        padding: 0.25rem 0.5rem;
        font-size: 0.75rem;
    }

    .gap-2 {
        gap: 0.5rem;
    }

    /* Modal styling */
    .modal-lg {
        max-width: 800px;
    }

    .modal-header {
        background-color: #f8f9fa;
        border-bottom: 1px solid #dee2e6;
    }

    .modal-footer {
        background-color: #f8f9fa;
        border-top: 1px solid #dee2e6;
    }

    /* Form control focus styling */
    .form-control:focus, 
    .form-select:focus {
        border-color: #86b7fe;
        box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
    }

    /* Section headers in modal */
    .modal-body h6 {
        color: #6c757d;
        font-weight: 600;
        border-bottom: 1px solid #dee2e6;
        padding-bottom: 0.5rem;
        margin-top: 1rem;
        margin-bottom: 1rem;
    }

    /* Toast container */
    #toastContainer {
        z-index: 1060;
    }

    /* Responsive adjustments */
    @media (max-width: 992px) {
        .table-responsive {
            overflow-x: auto;
        }
        
        #containerTable th, 
        #containerTable td,
        #looseCargoTable th,
        #looseCargoTable td {
            white-space: nowrap;
        }
    }
    
    /* Modal positioning fixes */
    .modal-dialog {
        margin: 1.75rem auto;
    }
    
    .modal {
        position: fixed;
        top: 0;
        left: 0;
        z-index: 1055;
        width: 100%;
        height: 100%;
        overflow-x: hidden;
        overflow-y: auto;
        outline: 0;
    }
    
    /* Ensure modal appears in center of screen */
    .modal-dialog-centered {
        display: flex;
        align-items: center;
        min-height: calc(100% - 3.5rem);
    }
    
    /* Tabs styling */
    .nav-tabs .nav-link {
        color: #495057;
        background-color: #f8f9fa;
        border: 1px solid #dee2e6;
        border-bottom: none;
        margin-right: 2px;
    }
    
    .nav-tabs .nav-link.active {
        color: #495057;
        background-color: #fff;
        border-color: #dee2e6 #dee2e6 #fff;
    }
    
    .tab-content {
        border: 1px solid #dee2e6;
        border-top: none;
        padding: 20px;
    }
    </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' => 'Edit Shipment File')); ?>

                    <?php if (isset($_SESSION['error_message'])): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?php echo $_SESSION['error_message']; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php unset($_SESSION['error_message']); ?>
                    <?php endif; ?>

                    <form method="POST" action="">
                        <div class="row">
                            <!-- Main File Information Card -->
                            <div class="col-xl-12">
                                <div class="card">
                                    <div class="card-header">
                                        <h4 class="card-title mb-0">
                                            Edit Shipment #<?php echo htmlspecialchars($file['file_number']); ?>
                                            <?php if ($file_type == 1): ?>
                                                <span class="badge bg-success">Local Shipment</span>
                                            <?php else: ?>
                                                <span class="badge bg-info">Transit Shipment</span>
                                            <?php endif; ?>
                                            
                                            <span class="badge bg-primary"><?php echo htmlspecialchars($cargo_type); ?></span>
                                        </h4>
                                    </div>
                                    <div class="card-body">
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label for="file_number" class="form-label">File Number</label>
                                                <input type="text" class="form-control" id="file_number" value="<?php echo htmlspecialchars($file['file_number']); ?>" readonly>
                                            </div>
                                            <div class="col-md-6">
                                                <label for="customer" class="form-label">Customer</label>
                                                <select class="form-select select2" id="customer" name="customer">
                                                    <option value="">Select Customer</option>
                                                    <?php foreach ($customers as $customer): ?>
                                                    <option value="<?php echo $customer['customer_id']; ?>" <?php echo ($customer['customer_id'] == $file['customer']) ? 'selected' : ''; ?> readonly>
                                                        <?php echo htmlspecialchars($customer['first_name']); ?>
                                                    </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="row mb-3">
                                            <div class="col-md-6">
											<div class="row mb-3">
                                            <div class="col-md-6">
                                                <label for="consignee_name" class="form-label">Consignee Name</label>
                                                <input type="text" class="form-control" id="consignee_name" name="consignee_name" 
                                                    value="<?php echo htmlspecialchars($file['consignee_name']); ?>">
                                            </div>
                                            <div class="col-md-3">
                                                <label for="destination" class="form-label">Destination</label>
                                                <input type="text" class="form-control" id="destination" name="destination" 
                                                    value="<?php echo htmlspecialchars($file['destination']); ?>">
                                            </div>
                                            <div class="col-md-3">
                                                <label for="port" class="form-label">Port</label>
                                                <input type="text" class="form-control" id="port" name="port" 
                                                    value="<?php echo htmlspecialchars($file['port']); ?>">
                                            </div>
                                        </div>

                                        <div class="row mb-3">
                                            <div class="col-md-4">
                                                <label for="trans_type" class="form-label">Transportation Type</label>
                                                <input type="text" class="form-control" id="trans_type" name="trans_type" 
                                                    value="<?php echo htmlspecialchars($file['trans_type']); ?>">
                                            </div>
                                            <div class="col-md-4">
                                                <label for="transporter" class="form-label">Transporter</label>
                                                <select class="form-select select2" id="transporter" name="transporter">
                                                    <option value="">Select Transporter</option>
                                                    <?php foreach ($transporters as $transporter): ?>
                                                    <option value="<?php echo $transporter['id']; ?>" <?php echo ($transporter['id'] == $file['transporter']) ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($transporter['name']); ?>
                                                    </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-4">
                                                <label for="obl_no" class="form-label">BL Number</label>
                                                <input type="text" class="form-control" id="obl_no" name="obl_no" 
                                                    value="<?php echo htmlspecialchars($file['obl_no']); ?>">
                                            </div>
                                        </div>

                                        <div class="row mb-3">
                                            <div class="col-md-3">
                                                <label for="way_bill" class="form-label">Way Bill / Telex</label>
                                                <input type="text" class="form-control" id="way_bill" name="way_bill" 
                                                    value="<?php echo htmlspecialchars($file['way_bill']); ?>">
                                            </div>
                                            <div class="col-md-3">
                                                <label for="currency" class="form-label">Currency</label>
                                                <select class="form-select" id="currency" name="currency">
                                                    <option value="$" <?php echo ($file['currency'] == '$') ? 'selected' : ''; ?>>USD ($)</option>
                                                    <option value="€" <?php echo ($file['currency'] == '€') ? 'selected' : ''; ?>>EUR (€)</option>
                                                    <option value="TZS" <?php echo ($file['currency'] == 'TZS') ? 'selected' : ''; ?>>TZS</option>
                                                    <option value="KES" <?php echo ($file['currency'] == 'KES') ? 'selected' : ''; ?>>KES</option>
                                                </select>
                                            </div>
                                            <div class="col-md-3">
                                                <label for="eta" class="form-label">ETA</label>
                                                <input type="date" class="form-control" id="eta" name="eta" 
                                                    value="<?php echo formatDate($file['eta']); ?>">
                                            </div>
                                            <div class="col-md-3">
                                                <label for="vno" class="form-label">Vessel Number</label>
                                                <input type="text" class="form-control" id="vno" name="vno" 
                                                    value="<?php echo htmlspecialchars($file['vno']); ?>">
                                            </div>
                                        </div>

                                        <?php if ($file_type == 2): // Transit Specific Fields ?>
                                        <div class="row mb-3">
                                            <div class="col-md-3">
                                                <label for="initial_eta" class="form-label">Initial ETA</label>
                                                <input type="date" class="form-control" id="initial_eta" name="initial_eta" 
                                                    value="<?php echo formatDate($file['initial_eta']); ?>">
                                            </div>
                                            <div class="col-md-3">
                                                <label for="pre_alert_received_date" class="form-label">Pre-Alert Received Date</label>
                                                <input type="date" class="form-control" id="pre_alert_received_date" name="pre_alert_received_date" 
                                                    value="<?php echo formatDate($file['pre_alert_received_date']); ?>">
                                            </div>
                                            <div class="col-md-3">
                                                <label for="discharge_date" class="form-label">Discharge Date</label>
                                                <input type="date" class="form-control" id="discharge_date" name="discharge_date" 
                                                    value="<?php echo formatDate($file['discharge_date']); ?>">
                                            </div>
                                            <div class="col-md-3">
                                                <label for="free_detention" class="form-label">Free Detention Days</label>
                                                <input type="number" class="form-control" id="free_detention" name="free_detention" 
                                                    value="<?php echo htmlspecialchars($file['free_detention']); ?>">
                                            </div>
                                        </div>
                                        
                                        <!-- Documentation Dates -->
                                        <div class="row mb-3">
                                            <div class="col-md-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" 
                                                    value="<?php echo formatDate($file['delivery_order_apply_date']); ?>">
                                            </div>
                                            <div class="col-md-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" 
                                                    value="<?php echo formatDate($file['delivery_order_received_date']); ?>">
                                            </div>
                                            <div class="col-md-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" 
                                                    value="<?php echo formatDate($charges['port_charges_paid_date'] ?? null); ?>">
                                            </div>
                                            <div class="col-md-3">
                                                <label for="whafage_paid_date" class="form-label">Wharfage Paid Date</label>
                                                <input type="date" class="form-control" id="whafage_paid_date" name="whafage_paid_date" 
                                                    value="<?php echo formatDate($charges['whafage_paid_date'] ?? null); ?>">
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <!-- Port & Wharfage Charges -->
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label for="port_charge" class="form-label">Port Charges</label>
                                                <div class="input-group">
                                                    <span class="input-group-text"><?php echo htmlspecialchars($file['currency']); ?></span>
                                                    <input type="number" step="0.01" class="form-control" id="port_charge" name="port_charge" 
                                                        value="<?php echo htmlspecialchars($charges['port_charge'] ?? ''); ?>">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <label for="wharfage_charge" class="form-label">Wharfage Charges</label>
                                                <div class="input-group">
                                                    <span class="input-group-text"><?php echo htmlspecialchars($file['currency']); ?></span>
                                                    <input type="number" step="0.01" class="form-control" id="wharfage_charge" name="wharfage_charge" 
                                                        value="<?php echo htmlspecialchars($charges['wharfage_charge'] ?? ''); ?>">
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row mb-3">
                                            <div class="col-md-12">
                                                <label for="remarks" class="form-label">Remarks</label>
                                                <textarea class="form-control" id="remarks" name="remarks" rows="3"><?php echo htmlspecialchars($file['remarks']); ?></textarea>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Container/Cargo Details Section -->
                            <div class="col-xl-12">
                                <div class="card">
                                    <div class="card-header">
                                        <h4 class="card-title mb-0">Cargo Information</h4>
                                    </div>
                                    
                                    <div class="card-body">
                                        <?php if ($cargo_type === 'Container'): ?>
                                        <!-- Container Cargo Section -->
                                        <div class="container-cargo-section">
                                            <div class="d-flex justify-content-end mb-3">
                                                <button type="button" class="btn btn-sm btn-primary" id="addContainerBtn">
                                                    <i class="ri-add-line"></i> Add Container
                                                </button>
                                            </div>
                                            
                                            <div class="table-responsive">
                                                <table class="table table-bordered" id="containerTable">
                                                    <thead>
                                                        <tr>
                                                            <th width="5%">#</th>
                                                            <th width="20%">Container Number <span class="text-danger">*</span></th>
                                                            <th width="15%">Size <span class="text-danger">*</span></th>
                                                            <th width="20%">Transporter <span class="text-danger">*</span></th>
                                                            <th width="20%">Driver</th>
                                                            <th width="20%">Actions</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody id="containerTableBody">
                                                        <?php if (!empty($containers)): ?>
                                                            <?php foreach ($containers as $index => $container): ?>
                                                            <tr id="container-row-<?php echo $index; ?>">
                                                                <td><?php echo ($index + 1); ?></td>
                                                                <td>
                                                                    <input type="hidden" name="container_id[<?php echo $index; ?>]" value="<?php echo $container['id']; ?>">
                                                                    <input type="text" class="form-control" name="container_code[<?php echo $index; ?>]" 
                                                                        id="container_code_<?php echo $index; ?>" 
                                                                        value="<?php echo htmlspecialchars($container['container_code']); ?>" required>
                                                                </td>
                                                                <td>
                                                                    <select class="form-select" name="container_size[<?php echo $index; ?>]" id="container_size_<?php echo $index; ?>" required>
                                                                        <option value="">Select Size</option>
                                                                        <option value="20" <?php echo ($container['container_size'] == '20') ? 'selected' : ''; ?>>20ft</option>
                                                                        <option value="40" <?php echo ($container['container_size'] == '40') ? 'selected' : ''; ?>>40ft</option>
                                                                        <option value="40HC" <?php echo ($container['container_size'] == '40HC') ? 'selected' : ''; ?>>40ft HC</option>
                                                                    </select>
                                                                </td>
                                                                <td>
                                                                    <select class="form-select" name="transporter_name[<?php echo $index; ?>]" id="transporter_<?php echo $index; ?>">
                                                                        <option value="">Select Transporter</option>
                                                                        <?php foreach ($transporters as $transporter): ?>
                                                                        <option value="<?php echo htmlspecialchars($transporter['name']); ?>" 
                                                                                <?php echo ($transporter['name'] == $container['transporter_name']) ? 'selected' : ''; ?>>
                                                                            <?php echo htmlspecialchars($transporter['name']); ?>
                                                                        </option>
                                                                        <?php endforeach; ?>
                                                                    </select>
                                                                </td>
                                                                <td>
                                                                    <input type="text" class="form-control" name="driver_name[<?php echo $index; ?>]" 
                                                                        id="driver_name_<?php echo $index; ?>" 
                                                                        value="<?php echo htmlspecialchars($container['driver_name']); ?>" 
                                                                        placeholder="Driver Name">
                                                                </td>
                                                                <td>
                                                                    <div class="d-flex gap-2">
                                                                        <button type="button" class="btn btn-sm btn-info" onclick="openContainerDetails(<?php echo $index; ?>)">
                                                                            <i class="ri-edit-box-line"></i> More Details
                                                                        </button>
                                                                        <?php if (count($containers) > 1): ?>
                                                                        <button type="button" class="btn btn-sm btn-danger" onclick="removeContainer(<?php echo $index; ?>)">
                                                                            <i class="ri-delete-bin-line"></i>
                                                                        </button>
                                                                        <?php endif; ?>
                                                                    </div>
                                                                </td>
                                                            </tr>
                                                            <?php endforeach; ?>
                                                        <?php else: ?>
                                                            <tr id="container-row-0">
                                                                <td>1</td>
                                                                <td>
                                                                    <input type="hidden" name="container_id[0]" value="">
                                                                    <input type="text" class="form-control" name="container_code[0]" id="container_code_0" required>
                                                                </td>
                                                                <td>
                                                                    <select class="form-select" name="container_size[0]" id="container_size_0" 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_name[0]" id="transporter_0" required>
                                                                        <option value="">Select Transporter</option>
                                                                        <?php foreach ($transporters as $transporter): ?>
                                                                        <option value="<?php echo htmlspecialchars($transporter['name']); ?>">
                                                                            <?php echo htmlspecialchars($transporter['name']); ?>
                                                                        </option>
                                                                        <?php endforeach; ?>
                                                                    </select>
                                                                </td>
                                                                <td>
                                                                    <input type="text" class="form-control" name="driver_name[0]" id="driver_name_0" placeholder="Driver Name">
                                                                </td>
                                                                <td>
                                                                    <button type="button" class="btn btn-sm btn-info" onclick="openContainerDetails(0)">
                                                                        <i class="ri-edit-box-line"></i> More Details
                                                                    </button>
                                                                </td>
                                                            </tr>
                                                        <?php endif; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                        <?php else: ?>
                                        <!-- Non-Container Cargo Section -->
                                        <ul class="nav nav-tabs" id="cargoTabs" role="tablist">
                                            <!-- Loose Cargo Tab -->
                                            <li class="nav-item" role="presentation">
                                                <button class="nav-link active" id="loose-cargo-tab" data-bs-toggle="tab" 
                                                    data-bs-target="#loose-cargo" type="button" role="tab" 
                                                    aria-controls="loose-cargo" aria-selected="true">
                                                    Loose Cargo Items
                                                </button>
                                            </li>
                                            <!-- Bulk Cargo Tab -->
                                            <li class="nav-item" role="presentation">
                                                <button class="nav-link" id="bulk-cargo-tab" data-bs-toggle="tab" 
                                                    data-bs-target="#bulk-cargo" type="button" role="tab" 
                                                    aria-controls="bulk-cargo" aria-selected="false">
                                                    Bulk Cargo Details
                                                </button>
                                            </li>
                                        </ul>
                                        
                                        <div class="tab-content" id="cargoTabsContent">
                                            <!-- Loose Cargo Tab Content -->
                                            <div class="tab-pane fade show active" id="loose-cargo" role="tabpanel" aria-labelledby="loose-cargo-tab">
                                                <div class="d-flex justify-content-end mb-3">
                                                    <button type="button" class="btn btn-sm btn-primary" id="addLooseCargoBtn">
                                                        <i class="ri-add-line"></i> Add Loose Cargo Item
                                                    </button>
                                                </div>
                                                
                                                <div class="table-responsive">
                                                    <table class="table table-bordered" id="looseCargoTable">
                                                        <thead>
                                                            <tr>
                                                                <th width="5%">#</th>
                                                                <th width="25%">Chassis/Item Number <span class="text-danger">*</span></th>
                                                                <th width="20%">Car Model/Item Description</th>
                                                                <th width="10%">CBM</th>
                                                                <th width="20%">Transporter</th>
                                                                <th width="20%">Actions</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody id="looseCargoTableBody">
                                                            <?php if (!empty($loose_cargo_items)): ?>
                                                                <?php foreach ($loose_cargo_items as $index => $item): ?>
                                                                <tr id="loose-cargo-row-<?php echo $index; ?>">
                                                                    <td><?php echo ($index + 1); ?></td>
                                                                    <td>
                                                                        <input type="hidden" name="loose_cargo_id[<?php echo $index; ?>]" value="<?php echo $item['id']; ?>">
                                                                        <input type="text" class="form-control" name="chassis_number[<?php echo $index; ?>]" 
                                                                            id="chassis_number_<?php echo $index; ?>" 
                                                                            value="<?php echo htmlspecialchars($item['chassis_number']); ?>" required>
                                                                    </td>
                                                                    <td>
                                                                        <input type="text" class="form-control" name="car_model[<?php echo $index; ?>]" 
                                                                            id="car_model_<?php echo $index; ?>" 
                                                                            value="<?php echo htmlspecialchars($item['car_model']); ?>">
                                                                    </td>
                                                                    <td>
                                                                        <input type="number" step="0.01" class="form-control" name="cbm[<?php echo $index; ?>]" 
                                                                            id="cbm_<?php echo $index; ?>" 
                                                                            value="<?php echo htmlspecialchars($item['cbm']); ?>">
                                                                    </td>
                                                                    <td>
                                                                        <select class="form-select" name="loose_transporter[<?php echo $index; ?>]" id="loose_transporter_<?php echo $index; ?>">
                                                                            <option value="">Select Transporter</option>
                                                                            <?php foreach ($transporters as $transporter): ?>
                                                                            <option value="<?php echo htmlspecialchars($transporter['name']); ?>" 
                                                                                    <?php echo ($transporter['name'] == $item['transporter']) ? 'selected' : ''; ?>>
                                                                                <?php echo htmlspecialchars($transporter['name']); ?>
                                                                            </option>
                                                                            <?php endforeach; ?>
                                                                        </select>
                                                                    </td>
                                                                    <td>
                                                                        <div class="d-flex gap-2">
                                                                            <button type="button" class="btn btn-sm btn-info" onclick="openLooseCargoDetails(<?php echo $index; ?>)">
                                                                                <i class="ri-edit-box-line"></i> More Details
                                                                            </button>
                                                                            <?php if (count($loose_cargo_items) > 1): ?>
                                                                            <button type="button" class="btn btn-sm btn-danger" onclick="removeLooseCargo(<?php echo $index; ?>)">
                                                                                <i class="ri-delete-bin-line"></i>
                                                                            </button>
                                                                            <?php endif; ?>
                                                                        </div>
                                                                    </td>
                                                                </tr>
                                                                <?php endforeach; ?>
                                                            <?php else: ?>
                                                                <tr id="loose-cargo-row-0">
                                                                    <td>1</td>
                                                                    <td>
                                                                        <input type="hidden" name="loose_cargo_id[0]" value="">
                                                                        <input type="text" class="form-control" name="chassis_number[0]" id="chassis_number_0" required>
                                                                    </td>
                                                                    <td>
                                                                        <input type="text" class="form-control" name="car_model[0]" id="car_model_0">
                                                                    </td>
                                                                    <td>
                                                                        <input type="number" step="0.01" class="form-control" name="cbm[0]" id="cbm_0">
                                                                    </td>
                                                                    <td>
                                                                        <select class="form-select" name="loose_transporter[0]" id="loose_transporter_0">
                                                                            <option value="">Select Transporter</option>
                                                                            <?php foreach ($transporters as $transporter): ?>
                                                                            <option value="<?php echo htmlspecialchars($transporter['name']); ?>">
                                                                                <?php echo htmlspecialchars($transporter['name']); ?>
                                                                            </option>
                                                                            <?php endforeach; ?>
                                                                        </select>
                                                                    </td>
                                                                    <td>
                                                                        <button type="button" class="btn btn-sm btn-info" onclick="openLooseCargoDetails(0)">
                                                                            <i class="ri-edit-box-line"></i> More Details
                                                                        </button>
                                                                    </td>
                                                                </tr>
                                                            <?php endif; ?>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                            
                                            <!-- Bulk Cargo Tab Content -->
                                            <div class="tab-pane fade" id="bulk-cargo" role="tabpanel" aria-labelledby="bulk-cargo-tab">
                                                <div class="row mb-3">
                                                    <div class="col-md-6">
                                                        <label for="bulk_item_count" class="form-label">Number of Items</label>
                                                        <input type="number" class="form-control" id="bulk_item_count" name="bulk_item_count" 
                                                            value="<?php echo htmlspecialchars($file['bulk_item_count'] ?? '0'); ?>">
                                                    </div>
                                                    <div class="col-md-6">
                                                        <label for="bulk_cbm" class="form-label">Total CBM</label>
                                                        <input type="number" step="0.01" class="form-control" id="bulk_cbm" name="bulk_cbm" 
                                                            value="<?php echo htmlspecialchars($file['bulk_cbm'] ?? '0.00'); ?>">
                                                    </div>
                                                </div>
                                                <div class="alert alert-info">
                                                    <i class="ri-information-line me-2"></i>
                                                    Use this section to record summary information for bulk cargo shipments with multiple items.
                                                </div>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Form Buttons -->
                            <div class="col-12 mb-4">
                                <div class="d-flex justify-content-between">
                                    <a href="view_file.php?id=<?php echo $file_id; ?>" class="btn btn-secondary">
                                        <i class="ri-arrow-left-line align-bottom me-1"></i> Cancel
                                    </a>
                                    <button type="submit" class="btn btn-primary">
                                        <i class="ri-save-line align-bottom me-1"></i> Update File
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

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

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <!-- Container Details Modal -->
    <div class="modal fade" id="containerDetailsModal" tabindex="-1" aria-labelledby="containerDetailsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <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 mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Container Number <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="modalContainerCode" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Container Size <span class="text-danger">*</span></label>
                                <select class="form-select" id="modalContainerSize" required>
                                    <option value="">Select Size</option>
                                    <option value="20">20ft</option>
                                    <option value="40">40ft</option>
                                    <option value="40HC">40ft HC</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Transporter <span class="text-danger">*</span></label>
                                <select class="form-select" id="modalTransporter" required>
                                    <option value="">Select Transporter</option>
                                    <?php foreach ($transporters as $transporter): ?>
                                    <option value="<?php echo htmlspecialchars($transporter['name']); ?>">
                                        <?php echo htmlspecialchars($transporter['name']); ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Way Bill</label>
                                <input type="text" class="form-control" id="modalWayBill">
                            </div>
                        </div>
                        
                        <h6 class="mt-4 mb-3">Driver Information</h6>
                        <div class="row mb-3">
                            <div class="col-md-4">
                                <label class="form-label">Driver Name</label>
                                <input type="text" class="form-control" id="modalDriverName">
                            <div class="col-md-4">
                                <label class="form-label">Driver Phone</label>
                                <input type="text" class="form-control" id="modalDriverPhone">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Driver License</label>
                                <input type="text" class="form-control" id="modalDriverLicense">
                            </div>
                        </div>
                        
                        <?php if ($file_type == 2): // Transit specific fields ?>
                        <!-- Transit Shipment Fields -->
                        <h6 class="mt-4 mb-3">Documentation Timeline</h6>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">OBR/SCT Received Date</label>
                                <input type="date" class="form-control" id="modalObrSctReceivedDate">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">OBR/TI Validation Date</label>
                                <input type="date" class="form-control" id="modalObrTiValidationDate">
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">T1/C2 Approval Date</label>
                                <input type="date" class="form-control" id="modalT1C2ApprovalDate">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Loading Permit Apply Date</label>
                                <input type="date" class="form-control" id="modalLoadingPermitApplyDate">
                            </div>
                        </div>
                        
                        <h6 class="mt-4 mb-3">Transit Timeline</h6>
                        <div class="row mb-3">
                            <div class="col-md-4">
                                <label class="form-label">Truck Exit Date</label>
                                <input type="date" class="form-control" id="modalTruckExitDate">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Truck at Border Date</label>
                                <input type="date" class="form-control" id="modalTruckAtBorderDate">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Border Crossing Date</label>
                                <input type="date" class="form-control" id="modalBorderCrossingDate">
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Delivery Date</label>
                                <input type="date" class="form-control" id="modalDeliveryDate">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Empty Return Date</label>
                                <input type="date" class="form-control" id="modalEmptyReturnDate">
                            </div>
                        </div>
                        <?php else: // Local shipment fields ?>
                        <!-- Local Shipment Fields -->
                        <h6 class="mt-4 mb-3">Local Timeline</h6>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Load Date</label>
                                <input type="date" class="form-control" id="modalLoadDate">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Offload Date</label>
                                <input type="date" class="form-control" id="modalOffloadDate">
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <div class="row mb-3">
                            <div class="col-md-12">
                                <label class="form-label">Container Remarks</label>
                                <textarea class="form-control" id="modalContainerRemarks" rows="3"></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>
    
    <!-- Loose Cargo Details Modal -->
    <div class="modal fade" id="looseCargoDetailsModal" tabindex="-1" aria-labelledby="looseCargoDetailsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="looseCargoDetailsModalLabel">Loose Cargo Item Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="looseCargoDetailsForm">
                        <input type="hidden" id="modalLooseCargoIndex" value="">
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Chassis/Item Number <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="modalChassisNumber" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Car Model/Item Description</label>
                                <input type="text" class="form-control" id="modalCarModel">
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">CBM</label>
                                <input type="number" step="0.01" class="form-control" id="modalCbm">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Transporter</label>
                                <select class="form-select" id="modalLooseTransporter">
                                    <option value="">Select Transporter</option>
                                    <?php foreach ($transporters as $transporter): ?>
                                    <option value="<?php echo htmlspecialchars($transporter['name']); ?>">
                                        <?php echo htmlspecialchars($transporter['name']); ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                        
                        <h6 class="mt-4 mb-3">Driver Information</h6>
                        <div class="row mb-3">
                            <div class="col-md-4">
                                <label class="form-label">Driver Name</label>
                                <input type="text" class="form-control" id="modalLooseDriverName">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Driver Phone</label>
                                <input type="text" class="form-control" id="modalLooseDriverPhone">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Driver License</label>
                                <input type="text" class="form-control" id="modalLooseDriverLicense">
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-12">
                                <label class="form-label">Remarks</label>
                                <textarea class="form-control" id="modalLooseRemarks" rows="3"></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="saveLooseCargoDetails">Save changes</button>
                </div>
            </div>
        </div>
    </div>
    <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
// Global variables for cargo management
let containerCount = <?php echo !empty($containers) ? count($containers) : 1; ?>;
let looseCargoCount = <?php echo isset($loose_cargo_items) && !empty($loose_cargo_items) ? count($loose_cargo_items) : 0; ?>;
let bulkCargoCount = <?php echo isset($bulk_cargo_items) && !empty($bulk_cargo_items) ? count($bulk_cargo_items) : 0; ?>;
const fileType = <?php echo $file_type; ?>; // 1 = Local, 2 = Transit
const cargoType = '<?php echo isset($file["c_type"]) ? $file["c_type"] : "Container"; ?>';
const containerDetailsModal = new bootstrap.Modal(document.getElementById('containerDetailsModal'));
const looseCargoDetailsModal = new bootstrap.Modal(document.getElementById('looseCargoDetailsModal'));
const hiddenContainerFields = [];
const hiddenLooseCargoFields = [];

// Initialize cargo management
document.addEventListener('DOMContentLoaded', function() {
    // Setup UI based on cargo type
    setupCargoTypeUI();
    
    // Setup add container/cargo button
    document.getElementById('addContainerBtn').addEventListener('click', addCargoRow);
    
    // Setup save container details button
    document.getElementById('saveContainerDetails').addEventListener('click', saveContainerDetails);
    
    // Setup save loose cargo details button if available
    const saveLooseCargoBtn = document.getElementById('saveLooseCargoDetails');
    if (saveLooseCargoBtn) {
        saveLooseCargoBtn.addEventListener('click', saveLooseCargoDetails);
    }
    
    // Initialize Select2 on transporters if available
    /*if (typeof $.fn.select2 !== 'undefined') {
        $('.select2').select2({
            width: '100%'
        });
        
        $('#cargoTable select').select2({
            width: '100%',
            dropdownParent: $('#cargoTable')
        });
    }*/
    
    // Generate hidden fields for all cargo items
    initializeCargoHiddenFields();
});

// Setup UI based on cargo type
function setupCargoTypeUI() {
    const cargoSectionTitle = document.querySelector('.card-title');
    const addButtonText = document.querySelector('#addContainerBtn');
    const tableHeaderRow = document.querySelector('#containerTable thead tr');
    
    if (cargoSectionTitle && addButtonText && tableHeaderRow) {
        // Update table ID to be more generic
        const containerTable = document.getElementById('containerTable');
        if (containerTable) {
            containerTable.id = 'cargoTable';
        }
        
        const containerTableBody = document.getElementById('containerTableBody');
        if (containerTableBody) {
            containerTableBody.id = 'cargoTableBody';
        }
        
        // Update UI elements based on cargo type
        switch (cargoType) {
            case 'Container':
                cargoSectionTitle.textContent = 'Container Information';
                addButtonText.innerHTML = '<i class="ri-add-line"></i> Add Container';
                break;
                
            case 'Loose Cargo':
                cargoSectionTitle.textContent = 'Loose Cargo Items';
                addButtonText.innerHTML = '<i class="ri-add-line"></i> Add Loose Cargo Item';
                
                // Update table headers for loose cargo
                tableHeaderRow.innerHTML = `
                    <th width="5%">#</th>
                    <th width="20%">Item/Chassis Number <span class="text-danger">*</span></th>
                    <th width="15%">Model/Description <span class="text-danger">*</span></th>
                    <th width="15%">CBM</th>
                    <th width="20%">Transporter</th>
                    <th width="25%">Actions</th>
                `;
                break;
                
            case 'Bulk':
                cargoSectionTitle.textContent = 'Bulk Cargo Items';
                addButtonText.innerHTML = '<i class="ri-add-line"></i> Add Bulk Item';
                
                // Update table headers for bulk cargo
                tableHeaderRow.innerHTML = `
                    <th width="5%">#</th>
                    <th width="25%">Description <span class="text-danger">*</span></th>
                    <th width="15%">Weight (MT)</th>
                    <th width="15%">CBM</th>
                    <th width="15%">Quantity</th>
                    <th width="25%">Actions</th>
                `;
                break;
                
            case 'Vehicle':
                cargoSectionTitle.textContent = 'Vehicle Information';
                addButtonText.innerHTML = '<i class="ri-add-line"></i> Add Vehicle';
                
                // Update table headers for vehicles
                tableHeaderRow.innerHTML = `
                    <th width="5%">#</th>
                    <th width="20%">Chassis Number <span class="text-danger">*</span></th>
                    <th width="15%">Make & Model <span class="text-danger">*</span></th>
                    <th width="15%">Year</th>
                    <th width="20%">Transporter</th>
                    <th width="25%">Actions</th>
                `;
                break;
        }
    }
}

// Initialize hidden fields for all cargo items
function initializeCargoHiddenFields() {
    const hiddenFieldsContainer = document.getElementById('cargoHiddenFields') || document.createElement('div');
    hiddenFieldsContainer.id = 'cargoHiddenFields';
    hiddenFieldsContainer.style.display = 'none';
    
    // Add to form if not exists
    if (!document.getElementById('cargoHiddenFields')) {
        document.querySelector('form').appendChild(hiddenFieldsContainer);
    }
    
    if (cargoType === 'Container') {
        // Define fields based on shipment type
        let fields = ['driver_phone_number', 'driver_license', 'way_bill', 'remarks'];
        
        if (fileType === 2) { // Transit
            fields = fields.concat([
                'obr_sct_received_date', 'obr_ti_validation_date',
                't1_c2_approval_date', 'loading_permit_apply_date',
                'truck_exit_date', 'truck_at_border_date',
                'border_crossing_date', 'delivery_date',
                'empty_return_date'
            ]);
        } else { // Local
            fields = fields.concat(['load_date', 'offload_date']);
        }
        
        // Store field names for later use
        hiddenContainerFields.push(...fields);
        
        // Create hidden fields for each container
        for (let i = 0; i < containerCount; i++) {
            createHiddenFieldsForContainer(i, hiddenFieldsContainer);
        }
    } else if (cargoType === 'Loose Cargo') {
        // Define fields for loose cargo
        let fields = ['driver_phone', 'driver_license', 'remarks'];
        
        // Store field names for later use
        hiddenLooseCargoFields.push(...fields);
        
        // Create hidden fields for each loose cargo item
        for (let i = 0; i < looseCargoCount; i++) {
            createHiddenFieldsForLooseCargo(i, hiddenFieldsContainer);
        }
    }
    // Add other cargo types as needed
}

// Create hidden fields for a specific container
function createHiddenFieldsForContainer(index, container) {
    hiddenContainerFields.forEach(field => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = `${field}[${index}]`;
        input.id = `${field}_${index}`;
        
        // Set initial value if it exists in container data
        const existingValue = getExistingContainerValue(index, field);
        if (existingValue) {
            input.value = existingValue;
        }
        
        container.appendChild(input);
    });
}

// Create hidden fields for a specific loose cargo item
function createHiddenFieldsForLooseCargo(index, container) {
    hiddenLooseCargoFields.forEach(field => {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = `${field}[${index}]`;
        input.id = `loose_${field}_${index}`;
        
        // Set initial value if it exists
        const existingValue = getExistingLooseCargoValue(index, field);
        if (existingValue) {
            input.value = existingValue;
        }
        
        container.appendChild(input);
    });
}

// Get existing value for a container field from PHP data
function getExistingContainerValue(index, field) {
    const existingField = document.getElementById(`${field}_${index}`);
    return existingField ? existingField.value : '';
}

// Get existing value for a loose cargo field from PHP data
function getExistingLooseCargoValue(index, field) {
    const existingField = document.getElementById(`loose_${field}_${index}`);
    return existingField ? existingField.value : '';
}

// Add a new cargo row based on cargo type
function addCargoRow() {
    switch (cargoType) {
        case 'Container':
            addContainerRow();
            break;
        case 'Loose Cargo':
            addLooseCargoRow();
            break;
        case 'Bulk':
            addBulkCargoRow();
            break;
        case 'Vehicle':
            addVehicleRow();
            break;
    }
}

// Add a new container row
function addContainerRow() {
    const newIndex = containerCount;
    const tableBody = document.getElementById('cargoTableBody');
    
    // Create new row
    const newRow = document.createElement('tr');
    newRow.id = `container-row-${newIndex}`;
    
    newRow.innerHTML = `
        <td>${newIndex + 1}</td>
        <td>
            <input type="hidden" name="container_id[${newIndex}]" value="">
            <input type="text" class="form-control" name="container_code[${newIndex}]" 
                id="container_code_${newIndex}" required>
        </td>
        <td>
            <select class="form-select" name="container_size[${newIndex}]" id="container_size_${newIndex}" 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_name[${newIndex}]" id="transporter_${newIndex}" required>
                <option value="">Select Transporter</option>
                ${generateTransporterOptions()}
            </select>
        </td>
        <td>
            <input type="text" class="form-control" name="driver_name[${newIndex}]" 
                id="driver_name_${newIndex}" placeholder="Driver Name">
        </td>
        <td>
            <div class="d-flex gap-2">
                <button type="button" class="btn btn-sm btn-info" onclick="openContainerDetails(${newIndex})">
                    <i class="ri-edit-box-line"></i> More Details
                </button>
                <button type="button" class="btn btn-sm btn-danger" onclick="removeContainer(${newIndex})">
                    <i class="ri-delete-bin-line"></i>
                </button>
            </div>
        </td>
    `;
    
    tableBody.appendChild(newRow);
    
    // Initialize Select2 for the new row if available
    if (typeof $.fn.select2 !== 'undefined') {
        $(`#transporter_${newIndex}`).select2({
            width: '100%',
            dropdownParent: $('#cargoTable')
        });
    }
    
    // Create hidden fields for the new container
    const hiddenFieldsContainer = document.getElementById('cargoHiddenFields');
    if (hiddenFieldsContainer) {
        createHiddenFieldsForContainer(newIndex, hiddenFieldsContainer);
    }
    
    // Increment counter
    containerCount++;
    
    // Update row numbers
    updateRowNumbers();
}

// Add a new loose cargo row
function addLooseCargoRow() {
    const newIndex = looseCargoCount;
    const tableBody = document.getElementById('cargoTableBody');
    
    // Create new row
    const newRow = document.createElement('tr');
    newRow.id = `loose-cargo-row-${newIndex}`;
    
    newRow.innerHTML = `
        <td>${newIndex + 1}</td>
        <td>
            <input type="hidden" name="loose_cargo_id[${newIndex}]" value="">
            <input type="text" class="form-control" name="chassis_number[${newIndex}]" 
                id="chassis_number_${newIndex}" required>
        </td>
        <td>
            <input type="text" class="form-control" name="car_model[${newIndex}]" 
                id="car_model_${newIndex}" required>
        </td>
        <td>
            <input type="number" step="0.01" class="form-control" name="cbm[${newIndex}]" 
                id="cbm_${newIndex}">
        </td>
        <td>
            <select class="form-select" name="loose_transporter[${newIndex}]" id="loose_transporter_${newIndex}">
                <option value="">Select Transporter</option>
                ${generateTransporterOptions()}
            </select>
        </td>
        <td>
            <div class="d-flex gap-2">
                <button type="button" class="btn btn-sm btn-info" onclick="openLooseCargoDetails(${newIndex})">
                    <i class="ri-edit-box-line"></i> More Details
                </button>
                <button type="button" class="btn btn-sm btn-danger" onclick="removeLooseCargo(${newIndex})">
                    <i class="ri-delete-bin-line"></i>
                </button>
            </div>
        </td>
    `;
    
    tableBody.appendChild(newRow);
    
    // Initialize Select2 for the new row if available
    if (typeof $.fn.select2 !== 'undefined') {
        $(`#loose_transporter_${newIndex}`).select2({
            width: '100%',
            dropdownParent: $('#cargoTable')
        });
    }
    
    // Create hidden fields for the new loose cargo
    const hiddenFieldsContainer = document.getElementById('cargoHiddenFields');
    if (hiddenFieldsContainer) {
        createHiddenFieldsForLooseCargo(newIndex, hiddenFieldsContainer);
    }
    
    // Increment counter
    looseCargoCount++;
    
    // Update row numbers
    updateRowNumbers();
}

// Add a new bulk cargo row
function addBulkCargoRow() {
    const newIndex = bulkCargoCount;
    const tableBody = document.getElementById('cargoTableBody');
    
    // Create new row
    const newRow = document.createElement('tr');
    newRow.id = `bulk-cargo-row-${newIndex}`;
    
    newRow.innerHTML = `
        <td>${newIndex + 1}</td>
        <td>
            <input type="hidden" name="bulk_cargo_id[${newIndex}]" value="">
            <input type="text" class="form-control" name="bulk_description[${newIndex}]" 
                id="bulk_description_${newIndex}" required>
        </td>
        <td>
            <input type="number" step="0.01" class="form-control" name="bulk_weight[${newIndex}]" 
                id="bulk_weight_${newIndex}">
        </td>
        <td>
            <input type="number" step="0.01" class="form-control" name="bulk_cbm[${newIndex}]" 
                id="bulk_cbm_${newIndex}">
        </td>
        <td>
            <input type="number" class="form-control" name="bulk_quantity[${newIndex}]" 
                id="bulk_quantity_${newIndex}">
        </td>
        <td>
            <div class="d-flex gap-2">
                <button type="button" class="btn btn-sm btn-info" onclick="openBulkCargoDetails(${newIndex})">
                    <i class="ri-edit-box-line"></i> More Details
                </button>
                <button type="button" class="btn btn-sm btn-danger" onclick="removeBulkCargo(${newIndex})">
                    <i class="ri-delete-bin-line"></i>
                </button>
            </div>
        </td>
    `;
    
    tableBody.appendChild(newRow);
    
    // Increment counter
    bulkCargoCount++;
    
    // Update row numbers
    updateRowNumbers();
}

// Add a new vehicle row
function addVehicleRow() {
    const newIndex = looseCargoCount; // Vehicles are stored as loose cargo items
    const tableBody = document.getElementById('cargoTableBody');
    
    // Create new row
    const newRow = document.createElement('tr');
    newRow.id = `vehicle-row-${newIndex}`;
    
    newRow.innerHTML = `
        <td>${newIndex + 1}</td>
        <td>
            <input type="hidden" name="loose_cargo_id[${newIndex}]" value="">
            <input type="text" class="form-control" name="chassis_number[${newIndex}]" 
                id="chassis_number_${newIndex}" required>
        </td>
        <td>
            <input type="text" class="form-control" name="car_model[${newIndex}]" 
                id="car_model_${newIndex}" required>
        </td>
        <td>
            <input type="text" class="form-control" name="vehicle_year[${newIndex}]" 
                id="vehicle_year_${newIndex}">
        </td>
        <td>
            <select class="form-select" name="loose_transporter[${newIndex}]" id="loose_transporter_${newIndex}">
                <option value="">Select Transporter</option>
                ${generateTransporterOptions()}
            </select>
        </td>
        <td>
            <div class="d-flex gap-2">
                <button type="button" class="btn btn-sm btn-info" onclick="openLooseCargoDetails(${newIndex})">
                    <i class="ri-edit-box-line"></i> More Details
                </button>
                <button type="button" class="btn btn-sm btn-danger" onclick="removeLooseCargo(${newIndex})">
                    <i class="ri-delete-bin-line"></i>
                </button>
            </div>
        </td>
    `;
    
    tableBody.appendChild(newRow);
    
    // Initialize Select2 for the new row if available
    if (typeof $.fn.select2 !== 'undefined') {
        $(`#loose_transporter_${newIndex}`).select2({
            width: '100%',
            dropdownParent: $('#cargoTable')
        });
    }
    
    // Create hidden fields for the new vehicle (as loose cargo)
    const hiddenFieldsContainer = document.getElementById('cargoHiddenFields');
    if (hiddenFieldsContainer) {
        createHiddenFieldsForLooseCargo(newIndex, hiddenFieldsContainer);
    }
    
    // Increment counter
    looseCargoCount++;
    
    // Update row numbers
    updateRowNumbers();
}

// Generate options for transporter select
function generateTransporterOptions() {
    let options = '';
    
    // Find a transporter select to copy options from
    let transporterSelect = null;
    
    // Try to find a select with transporter options
    if (cargoType === 'Container') {
        transporterSelect = document.querySelector('select[name^="transporter_name"]');
    } else if (cargoType === 'Loose Cargo' || cargoType === 'Vehicle') {
        transporterSelect = document.querySelector('select[name^="loose_transporter"]');
    }
    
    // If no transporter select is found, try to get transporter data from PHP variable
    if (!transporterSelect || transporterSelect.options.length <= 1) {
        // This assumes you have a PHP variable with transporter data available in the JavaScript context
        // You'll need to adapt this based on your actual data structure
        if (typeof transporters !== 'undefined') {
            transporters.forEach(transporter => {
                options += `<option value="${transporter.id}">${transporter.name}</option>`;
            });
        }
    } else {
        // Copy options from existing select
        Array.from(transporterSelect.options)
            .filter(option => option.value)
            .forEach(option => {
                options += `<option value="${option.value}">${option.textContent}</option>`;
            });
    }
    
    return options;
}

// Remove a container row
function removeContainer(index) {
    if (containerCount <= 1) {
        alert('At least one container is required.');
        return;
    }
    
    // Confirm deletion
    if (!confirm('Are you sure you want to remove this container?')) {
        return;
    }
    
    // Remove the row
    const row = document.getElementById(`container-row-${index}`);
    if (row) {
        row.remove();
        
        // Decrease counter
        containerCount--;
        
        // Update row numbers
        updateRowNumbers();
        
        // Remove hidden fields
        removeContainerHiddenFields(index);
    }
}

// Remove a loose cargo row
function removeLooseCargo(index) {
    if (looseCargoCount <= 1) {
        alert('At least one item is required.');
        return;
    }
    
    // Confirm deletion
    if (!confirm('Are you sure you want to remove this item?')) {
        return;
    }
    
    // Remove the row
    const row = document.getElementById(`loose-cargo-row-${index}`);
    if (row) {
        row.remove();
        
        // Decrease counter
        looseCargoCount--;
        
        // Update row numbers
        updateRowNumbers();
        
        // Remove hidden fields
        removeLooseCargoHiddenFields(index);
    }
}

// Remove a bulk cargo row
function removeBulkCargo(index) {
    if (bulkCargoCount <= 1) {
        alert('At least one bulk item is required.');
        return;
    }
    
    // Confirm deletion
    if (!confirm('Are you sure you want to remove this bulk item?')) {
        return;
    }
    
    // Remove the row
    const row = document.getElementById(`bulk-cargo-row-${index}`);
    if (row) {
        row.remove();
        
        // Decrease counter
        bulkCargoCount--;
        
        // Update row numbers
        updateRowNumbers();
    }
}

// Update row numbers after deletion
function updateRowNumbers() {
    const rows = document.querySelectorAll('#cargoTableBody tr');
    rows.forEach((row, i) => {
        row.cells[0].textContent = i + 1;
    });
}

// Remove hidden fields for a deleted container
function removeContainerHiddenFields(index) {
    hiddenContainerFields.forEach(field => {
        const input = document.getElementById(`${field}_${index}`);
        if (input) {
            input.remove();
        }
    });
}

// Remove hidden fields for a deleted loose cargo item
function removeLooseCargoHiddenFields(index) {
    hiddenLooseCargoFields.forEach(field => {
        const input = document.getElementById(`loose_${field}_${index}`);
        if (input) {
            input.remove();
        }
    });
}

// Open container details modal
function openContainerDetails(index) {
    // Store current container index in modal
    document.getElementById('modalContainerIndex').value = index;
    
    // Populate modal with container data
    populateContainerModal(index);
    
    // Ensure the modal is visible on the screen by scrolling to top first
    window.scrollTo(0, 0);
    
    // Show modal
    containerDetailsModal.show();
}

// Open loose cargo details modal
function openLooseCargoDetails(index) {
    // Store current loose cargo index in modal
    document.getElementById('modalLooseCargoIndex').value = index;
    
    // Populate modal with loose cargo data
    populateLooseCargoModal(index);
    
    // Ensure the modal is visible on the screen by scrolling to top first
    window.scrollTo(0, 0);
    
    // Show modal
    looseCargoDetailsModal.show();
}

// Open bulk cargo details modal
function openBulkCargoDetails(index) {
    // Implement if needed for bulk cargo
    alert('Bulk cargo details functionality not implemented yet.');
}

// Populate modal with container data
function populateContainerModal(index) {
    // Set basic fields
    document.getElementById('modalContainerCode').value = document.getElementById(`container_code_${index}`).value;
    
    const sizeSelect = document.getElementById(`container_size_${index}`);
    if (sizeSelect) {
        document.getElementById('modalContainerSize').value = sizeSelect.value;
    }
    
    const transporterSelect = document.getElementById(`transporter_${index}`);
    if (transporterSelect) {
        document.getElementById('modalTransporter').value = transporterSelect.value;
    }
    
    document.getElementById('modalDriverName').value = document.getElementById(`driver_name_${index}`).value;
    
    // Set fields from hidden inputs
    hiddenContainerFields.forEach(field => {
        const hiddenInput = document.getElementById(`${field}_${index}`);
        if (hiddenInput) {
            const modalField = field.charAt(0).toUpperCase() + field.slice(1);
            // Handle special field naming
            let modalFieldName = modalField;
            if (field === 'way_bill') modalFieldName = 'WayBill';
            
            const modalInput = document.getElementById(`modal${modalFieldName}`);
            if (modalInput) {
                modalInput.value = hiddenInput.value;
            }
        }
    });
}

// Populate modal with loose cargo data
function populateLooseCargoModal(index) {
    // Set basic fields
    document.getElementById('modalChassisNumber').value = document.getElementById(`chassis_number_${index}`).value;
    document.getElementById('modalCarModel').value = document.getElementById(`car_model_${index}`).value;
    
    const cbmInput = document.getElementById(`cbm_${index}`);
    if (cbmInput) {
        document.getElementById('modalCbm').value = cbmInput.value;
    }
    
    const transporterSelect = document.getElementById(`loose_transporter_${index}`);
    if (transporterSelect) {
        document.getElementById('modalLooseTransporter').value = transporterSelect.value;
    }
    
    // Set fields from hidden inputs
    hiddenLooseCargoFields.forEach(field => {
        const hiddenInput = document.getElementById(`loose_${field}_${index}`);
        if (hiddenInput) {
            const modalField = field.charAt(0).toUpperCase() + field.slice(1);
            // Handle special field naming
            let modalFieldName = modalField;
            
            const modalInput = document.getElementById(`modalLoose${modalFieldName}`);
            if (modalInput) {
                modalInput.value = hiddenInput.value;
            }
        }
    });
    
    // Handle vehicle year if available (for vehicle cargo type)
    const vehicleYearInput = document.getElementById(`vehicle_year_${index}`);
    if (vehicleYearInput && document.getElementById('modalVehicleYear')) {
        document.getElementById('modalVehicleYear').value = vehicleYearInput.value;
    }
}

// Save container details from modal
function saveContainerDetails() {
    const index = document.getElementById('modalContainerIndex').value;
    
    // Update visible fields
    document.getElementById(`container_code_${index}`).value = document.getElementById('modalContainerCode').value;
    
    const sizeSelect = document.getElementById(`container_size_${index}`);
    if (sizeSelect) {
        sizeSelect.value = document.getElementById('modalContainerSize').value;
    }
    
    const transporterSelect = document.getElementById(`transporter_${index}`);
    if (transporterSelect) {
        transporterSelect.value = document.getElementById('modalTransporter').value;
        
        // Update Select2 if available
        if (typeof $.fn.select2 !== 'undefined') {
            $(transporterSelect).trigger('change');
        }
    }
    
    document.getElementById(`driver_name_${index}`).value = document.getElementById('modalDriverName').value;
    
    // Update hidden fields
    hiddenContainerFields.forEach(field => {
        const hiddenInput = document.getElementById(`${field}_${index}`);
        if (hiddenInput) {
            const modalField = field.charAt(0).toUpperCase() + field.slice(1);
            // Handle special field naming
            let modalFieldName = modalField;
            if (field === 'way_bill') modalFieldName = 'WayBill';
            
            const modalInput = document.getElementById(`modal${modalFieldName}`);
            if (modalInput) {
                hiddenInput.value = modalInput.value;
            }
        }
    });
    
    // Close modal
    containerDetailsModal.hide();
    
    // Show success notification
    showToast('Container details updated successfully', 'success');
}

// Save loose cargo details from modal
function saveLooseCargoDetails() {
    const index = document.getElementById('modalLooseCargoIndex').value;
    
    // Update visible fields
    document.getElementById(`chassis_number_${index}`).value = document.getElementById('modalChassisNumber').value;
    document.getElementById(`car_model_${index}`).value = document.getElementById('modalCarModel').value;
    
    const cbmInput = document.getElementById(`cbm_${index}`);
    if (cbmInput) {
        cbmInput.value = document.getElementById('modalCbm').value;
    }
    
    const transporterSelect = document.getElementById(`loose_transporter_${index}`);
    if (transporterSelect) {
        transporterSelect.value = document.getElementById('modalLooseTransporter').value;
        
        // Update Select2 if available
        if (typeof $.fn.select2 !== 'undefined') {
            $(transporterSelect).trigger('change');
        }
    }
    
    // Update hidden fields
    hiddenLooseCargoFields.forEach(field => {
        const hiddenInput = document.getElementById(`loose_${field}_${index}`);
        if (hiddenInput) {
            const modalField = field.charAt(0).toUpperCase() + field.slice(1);
            
            const modalInput = document.getElementById(`modalLoose${modalFieldName}`);
            if (modalInput) {
                hiddenInput.value = modalInput.value;
            }
        }
    });
    
    // Handle vehicle year if available (for vehicle cargo type)
    const vehicleYearInput = document.getElementById(`vehicle_year_${index}`);
    if (vehicleYearInput && document.getElementById('modalVehicleYear')) {
        vehicleYearInput.value = document.getElementById('modalVehicleYear').value;
    }
    
    // Close modal
    looseCargoDetailsModal.hide();
    
    // Show success notification
    showToast('Item details updated successfully', 'success');
}

// Show toast notification
function showToast(message, type = 'info') {
    // Check if Bootstrap toasts are available
    if (typeof bootstrap !== 'undefined' && typeof bootstrap.Toast !== 'undefined') {
        // Create toast element
        const toastContainer = document.getElementById('toastContainer') || createToastContainer();
        
        const toastEl = document.createElement('div');
        toastEl.className = `toast align-items-center text-white bg-${type} border-0`;
        toastEl.setAttribute('role', 'alert');
        toastEl.setAttribute('aria-live', 'assertive');
        toastEl.setAttribute('aria-atomic', 'true');
        
        toastEl.innerHTML = `
            <div class="d-flex">
                <div class="toast-body">${message}</div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
        `;
        
        toastContainer.appendChild(toastEl);
        
        const toast = new bootstrap.Toast(toastEl, { delay: 3000 });
        toast.show();
        
        // Remove toast after it's hidden
        toastEl.addEventListener('hidden.bs.toast', function() {
            toastEl.remove();
        });
    } else {
        // Fallback to alert
        alert(message);
    }
}

// Create toast container if it doesn't exist
function createToastContainer() {
    const container = document.createElement('div');
    container.id = 'toastContainer';
    container.className = 'toast-container position-fixed top-0 end-0 p-3';
    container.style.zIndex = '1060';
    
    document.body.appendChild(container);
    return container;
}

// Handle form submission
document.addEventListener('DOMContentLoaded', function() {
    const form = document.querySelector('form');
    
    if (form) {
        form.addEventListener('submit', function(e) {
            // Validate form based on cargo type
            if (cargoType === 'Container') {
                // Validate all containers have required fields
                const containerRows = document.querySelectorAll('#cargoTableBody tr');
                let valid = true;
                
                containerRows.forEach((row, index) => {
                    const containerCode = document.getElementById(`container_code_${index}`);
                    const containerSize = document.getElementById(`container_size_${index}`);
                    
                    if (!containerCode || containerCode.value.trim() === '') {
                        valid = false;
                        containerCode.classList.add('is-invalid');
                    } else {
                        containerCode.classList.remove('is-invalid');
                    }
                    
                    if (!containerSize || containerSize.value === '') {
                        valid = false;
                        containerSize.classList.add('is-invalid');
                    } else {
                        containerSize.classList.remove('is-invalid');
                    }
                });
                
                if (!valid) {
                    e.preventDefault();
                    alert('Please fill all required container fields');
                    return false;
                }
            } else if (cargoType === 'Loose Cargo' || cargoType === 'Vehicle') {
                // Validate all loose cargo items have required fields
                const cargoRows = document.querySelectorAll('#cargoTableBody tr');
                let valid = true;
                
                cargoRows.forEach((row, index) => {
                    const chassisNumber = document.getElementById(`chassis_number_${index}`);
                    const carModel = document.getElementById(`car_model_${index}`);
                    
                    if (!chassisNumber || chassisNumber.value.trim() === '') {
                        valid = false;
                        chassisNumber.classList.add('is-invalid');
                    } else {
                        chassisNumber.classList.remove('is-invalid');
                    }
                    
                    if (!carModel || carModel.value.trim() === '') {
                        valid = false;
                        carModel.classList.add('is-invalid');
                    } else {
                        carModel.classList.remove('is-invalid');
                    }
                });
                
                if (!valid) {
                    e.preventDefault();
                    alert('Please fill all required item fields');
                    return false;
                }
            } else if (cargoType === 'Bulk') {
                // Validate all bulk cargo items have required fields
                const bulkRows = document.querySelectorAll('#cargoTableBody tr');
                let valid = true;
                
                bulkRows.forEach((row, index) => {
                    const description = document.getElementById(`bulk_description_${index}`);
                    
                    if (!description || description.value.trim() === '') {
                        valid = false;
                        description.classList.add('is-invalid');
                    } else {
                        description.classList.remove('is-invalid');
                    }
                });
                
                if (!valid) {
                    e.preventDefault();
                    alert('Please fill all required bulk item fields');
                    return false;
                }
            }
        });
    }
});

// Initialize any potential modals needed for different cargo types
document.addEventListener('DOMContentLoaded', function() {
    // Only create modals if they don't exist yet
    if (cargoType === 'Loose Cargo' || cargoType === 'Vehicle') {
        if (!document.getElementById('looseCargoDetailsModal')) {
            createLooseCargoModal();
        }
    }
    
    if (cargoType === 'Bulk') {
        if (!document.getElementById('bulkCargoDetailsModal')) {
            createBulkCargoModal();
        }
    }
});

// Create loose cargo modal dynamically if needed
function createLooseCargoModal() {
    const modalHtml = `
    <div class="modal fade" id="looseCargoDetailsModal" tabindex="-1" aria-labelledby="looseCargoDetailsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="looseCargoDetailsModalLabel">${cargoType === 'Vehicle' ? 'Vehicle Details' : 'Loose Cargo Details'}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="looseCargoDetailsForm">
                        <input type="hidden" id="modalLooseCargoIndex" value="">
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Chassis Number <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="modalChassisNumber" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">${cargoType === 'Vehicle' ? 'Make & Model' : 'Car Model'} <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="modalCarModel" required>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            ${cargoType === 'Vehicle' ? 
                            `<div class="col-md-4">
                                <label class="form-label">Year</label>
                                <input type="text" class="form-control" id="modalVehicleYear">
                            </div>` : ''}
                            <div class="col-md-${cargoType === 'Vehicle' ? '4' : '6'}">
                                <label class="form-label">CBM</label>
                                <input type="number" step="0.01" class="form-control" id="modalCbm">
                            </div>
                            <div class="col-md-${cargoType === 'Vehicle' ? '4' : '6'}">
                                <label class="form-label">Transporter</label>
                                <select class="form-select" id="modalLooseTransporter">
                                    <option value="">Select Transporter</option>
                                    ${generateTransporterOptions()}
                                </select>
                            </div>
                        </div>
                        
                        <h6 class="mt-4 mb-3">Driver Information</h6>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Driver Name</label>
                                <input type="text" class="form-control" id="modalLooseDriverName">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Driver Phone</label>
                                <input type="text" class="form-control" id="modalLooseDriverPhone">
                            </div>
                        </div>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Driver License</label>
                                <input type="text" class="form-control" id="modalLooseDriverLicense">
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-12">
                                <label class="form-label">Item Remarks</label>
                                <textarea class="form-control" id="modalLooseRemarks" rows="3"></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="saveLooseCargoDetails">Save changes</button>
                </div>
            </div>
        </div>
    </div>`;
    
    // Append modal HTML to document body
    const modalContainer = document.createElement('div');
    modalContainer.innerHTML = modalHtml;
    document.body.appendChild(modalContainer.firstChild);
    
    // Initialize the modal instance
    const looseCargoDetailsModal = new bootstrap.Modal(document.getElementById('looseCargoDetailsModal'));
    
    // Setup save button event
    document.getElementById('saveLooseCargoDetails').addEventListener('click', saveLooseCargoDetails);
}

// Create bulk cargo modal dynamically if needed
function createBulkCargoModal() {
    const modalHtml = `
    <div class="modal fade" id="bulkCargoDetailsModal" tabindex="-1" aria-labelledby="bulkCargoDetailsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="bulkCargoDetailsModalLabel">Bulk Item Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="bulkCargoDetailsForm">
                        <input type="hidden" id="modalBulkCargoIndex" value="">
                        
                        <div class="row mb-3">
                            <div class="col-md-12">
                                <label class="form-label">Description <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="modalBulkDescription" required>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-4">
                                <label class="form-label">Weight (MT)</label>
                                <input type="number" step="0.01" class="form-control" id="modalBulkWeight">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">CBM</label>
                                <input type="number" step="0.01" class="form-control" id="modalBulkCbm">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Quantity</label>
                                <input type="number" class="form-control" id="modalBulkQuantity">
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-12">
                                <label class="form-label">Additional Information</label>
                                <textarea class="form-control" id="modalBulkRemarks" rows="3"></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="saveBulkCargoDetails">Save changes</button>
                </div>
            </div>
        </div>
    </div>`;
    
    // Append modal HTML to document body
    const modalContainer = document.createElement('div');
    modalContainer.innerHTML = modalHtml;
    document.body.appendChild(modalContainer.firstChild);
    
    // Initialize the modal instance
    const bulkCargoDetailsModal = new bootstrap.Modal(document.getElementById('bulkCargoDetailsModal'));
    
    // Setup save button event
    document.getElementById('saveBulkCargoDetails').addEventListener('click', function() {
        const index = document.getElementById('modalBulkCargoIndex').value;
        
        // Update visible fields
        document.getElementById(`bulk_description_${index}`).value = document.getElementById('modalBulkDescription').value;
        document.getElementById(`bulk_weight_${index}`).value = document.getElementById('modalBulkWeight').value;
        document.getElementById(`bulk_cbm_${index}`).value = document.getElementById('modalBulkCbm').value;
        document.getElementById(`bulk_quantity_${index}`).value = document.getElementById('modalBulkQuantity').value;
        
        // Close modal
        bulkCargoDetailsModal.hide();
        
        // Show success notification
        showToast('Bulk item details updated successfully', 'success');
    });
}

// Handle file type change if the page has a file type selector
document.addEventListener('DOMContentLoaded', function() {
    const fileTypeSelect = document.getElementById('c_type');
    if (fileTypeSelect) {
        fileTypeSelect.addEventListener('change', function() {
            // Store the current selection
            const newCargoType = this.value;
            
            // Ask for confirmation if changing from one type to another with existing data
            if (cargoType !== newCargoType) {
                if ((cargoType === 'Container' && containerCount > 0) || 
                    (cargoType === 'Loose Cargo' && looseCargoCount > 0) ||
                    (cargoType === 'Bulk' && bulkCargoCount > 0)) {
                    
                    if (!confirm('Changing the cargo type will clear all current cargo items. Are you sure you want to continue?')) {
                        // Revert selection if user cancels
                        this.value = cargoType;
                        return;
                    }
                    
                    // Clear existing cargo items
                    clearCargoTable();
                }
                
                // Update cargoType variable
                cargoType = newCargoType;
                
                // Update UI for the new cargo type
                setupCargoTypeUI();
                
                // Reset counters
                if (cargoType === 'Container') {
                    containerCount = 0;
                    addContainerRow(); // Add one empty row
                } else if (cargoType === 'Loose Cargo' || cargoType === 'Vehicle') {
                    looseCargoCount = 0;
                    if (cargoType === 'Loose Cargo') {
                        addLooseCargoRow(); // Add one empty row
                    } else {
                        addVehicleRow(); // Add one empty row
                    }
                } else if (cargoType === 'Bulk') {
                    bulkCargoCount = 0;
                    addBulkCargoRow(); // Add one empty row
                }
            }
        });
    }
});

// Clear cargo table for cargo type change
function clearCargoTable() {
    const tableBody = document.getElementById('cargoTableBody');
    if (tableBody) {
        tableBody.innerHTML = '';
    }
    
    // Clear hidden fields
    const hiddenFieldsContainer = document.getElementById('cargoHiddenFields');
    if (hiddenFieldsContainer) {
        hiddenFieldsContainer.innerHTML = '';
    }
}
</script>
</body>
</html>