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

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

// 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'];
} else {
    // Handle the case if user details are not found
    header('Location: login.php');
    exit();
}

// Check if file number is provided
$file_number = isset($_GET['file_number']) ? $_GET['file_number'] : '';
$action = isset($_GET['action']) ? $_GET['action'] : 'view';
$truck_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Get file details if file number is provided
$file_details = null;
if (!empty($file_number)) {
    $file_query = "SELECT * FROM files WHERE file_number = ?";
    $file_stmt = $conn->prepare($file_query);
    $file_stmt->bind_param('s', $file_number);
    $file_stmt->execute();
    $file_result = $file_stmt->get_result();
    
    if ($file_result->num_rows > 0) {
        $file_details = $file_result->fetch_assoc();
    } else {
        $_SESSION['error_message'] = "File not found with number: $file_number";
        header('Location: truck_list.php');
        exit();
    }
}

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

// Handle truck detail form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_truck_details'])) {
    $file_no = $_POST['file_no'];
    $container_code = $_POST['container_code'];
    $transporter_name = $_POST['transporter_name'];
    $load_date = !empty($_POST['load_date']) ? $_POST['load_date'] : null;
    $truck_trailer_no = $_POST['truck_trailer_no'];
    $driver_name = $_POST['driver_name'];
    $driver_phone_number = $_POST['driver_phone_number'];
    $driver_license = $_POST['driver_license'];
    $port_date = !empty($_POST['port_date']) ? $_POST['port_date'] : null;
    $border_date = !empty($_POST['border_date']) ? $_POST['border_date'] : null;
    $border_crossing_date = !empty($_POST['border_crossing_date']) ? $_POST['border_crossing_date'] : null;
    $dest_date = !empty($_POST['dest_date']) ? $_POST['dest_date'] : null;
    $offload_date = !empty($_POST['offload_date']) ? $_POST['offload_date'] : null;
    $empty_return_date = !empty($_POST['empty_return_date']) ? $_POST['empty_return_date'] : null;
    
    try {
        $conn->begin_transaction();
        
        if ($action === 'edit' && $truck_id > 0) {
            // Update existing truck details
            $update_sql = "UPDATE truck_details SET 
                transporter_name = ?, load_date = ?, truck_trailer_no = ?, 
                driver_name = ?, driver_phone_number = ?, driver_license = ?,
                port_date = ?, border_date = ?, border_crossing_date = ?,
                dest_date = ?, offload_date = ?, empty_return_date = ?,
                user_id = ?, updated_at = NOW()
                WHERE id = ?";
                
            $update_stmt = $conn->prepare($update_sql);
            $update_stmt->bind_param('sssssssssssiii', 
                $transporter_name, $load_date, $truck_trailer_no, 
                $driver_name, $driver_phone_number, $driver_license,
                $port_date, $border_date, $border_crossing_date,
                $dest_date, $offload_date, $empty_return_date,
                $user_id, $truck_id
            );
            
            if ($update_stmt->execute()) {
                $conn->commit();
                $_SESSION['success_message'] = "Truck details updated successfully";
                header("Location: truck_details.php?file_number=$file_no&id=$truck_id");
                exit();
            } else {
                throw new Exception("Error updating truck details: " . $conn->error);
            }
        } else {
            // Insert new truck details
            $insert_sql = "INSERT INTO truck_details (
                file_no, container_code, transporter_name, load_date,
                truck_trailer_no, driver_name, driver_phone_number, driver_license,
                port_date, border_date, border_crossing_date, dest_date, offload_date, 
                empty_return_date, user_id, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
            
            $insert_stmt = $conn->prepare($insert_sql);
            $insert_stmt->bind_param('ssssssssssssssi', 
                $file_no, $container_code, $transporter_name, $load_date,
                $truck_trailer_no, $driver_name, $driver_phone_number, $driver_license,
                $port_date, $border_date, $border_crossing_date, $dest_date, $offload_date,
                $empty_return_date, $user_id
            );
            
            if ($insert_stmt->execute()) {
                $new_truck_id = $conn->insert_id;
                $conn->commit();
                $_SESSION['success_message'] = "Truck details added successfully";
                header("Location: truck_details.php?file_number=$file_no&id=$new_truck_id");
                exit();
            } else {
                throw new Exception("Error adding truck details: " . $conn->error);
            }
        }
    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['error_message'] = $e->getMessage();
        header("Location: truck_details.php?file_number=$file_number&action=$action" . ($truck_id > 0 ? "&id=$truck_id" : ""));
        exit();
    }
}

// Fetch truck details if editing
$truck_details = null;
if ($action === 'edit' && $truck_id > 0) {
    $truck_query = "SELECT * FROM truck_details WHERE id = ?";
    $truck_stmt = $conn->prepare($truck_query);
    $truck_stmt->bind_param('i', $truck_id);
    $truck_stmt->execute();
    $truck_result = $truck_stmt->get_result();
    
    if ($truck_result->num_rows > 0) {
        $truck_details = $truck_result->fetch_assoc();
        $file_number = $truck_details['file_no']; // Override file number with the one from truck details
    } else {
        $_SESSION['error_message'] = "Truck details not found";
        header('Location: truck_list.php');
        exit();
    }
}

// Fetch containers for the file
$containers = [];
if (!empty($file_number)) {
    $containers_query = "SELECT container_code, container_size FROM container_details WHERE file_number = ?";
    $containers_stmt = $conn->prepare($containers_query);
    $containers_stmt->bind_param('s', $file_number);
    $containers_stmt->execute();
    $containers_result = $containers_stmt->get_result();
    
    while ($row = $containers_result->fetch_assoc()) {
        $containers[] = $row;
    }
}

include 'layouts/main.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => ($action === 'edit' ? 'Edit Truck Details' : 'Add Truck Details'))); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="assets/libs/sweetalert2/sweetalert2.min.css">
    <style>
        .form-label .required {
            color: red;
        }
        .card-header-info {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 20px;
        }
        .card-header-info .info-item {
            display: flex;
            margin-bottom: 10px;
        }
        .card-header-info .info-label {
            font-weight: 600;
            width: 150px;
        }
        .card-header-info .info-value {
            flex: 1;
        }
        .timeline-steps {
            display: flex;
            flex-wrap: wrap;
            margin-top: 20px;
        }
        .timeline-step {
            flex: 1;
            min-width: 140px;
            text-align: center;
            position: relative;
            padding-bottom: 20px;
        }
        .timeline-step:not(:last-child):before {
            content: '';
            position: absolute;
            width: 100%;
            height: 3px;
            background-color: #e9ecef;
            top: 30px;
            left: 50%;
            z-index: 0;
        }
        .timeline-step-icon {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background-color: #e9ecef;
            color: #6c757d;
            position: relative;
            z-index: 1;
            margin-bottom: 10px;
        }
        .timeline-step.completed .timeline-step-icon {
            background-color: #28a745;
            color: white;
        }
        .timeline-step.active .timeline-step-icon {
            background-color: #007bff;
            color: white;
        }
        .timeline-step-title {
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 5px;
        }
        .timeline-step-date {
            font-size: 12px;
            color: #6c757d;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Container Transport', 'title' => ($action === 'edit' ? 'Edit Truck Details' : 'Add Truck Details'))); ?>
                    
                    <?php if (isset($_SESSION['success_message'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <h4 class="card-title mb-0">
                                            <?php echo $action === 'edit' ? 'Edit Truck Details' : 'Add Truck Details'; ?>
                                        </h4>
                                        <div>
                                            <a href="truck_list.php" class="btn btn-primary">
                                                <i class="ri-arrow-left-line align-middle me-1"></i> Back to List
                                            </a>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <?php if ($file_details): ?>
                                    <div class="card-header-info">
                                        <h5 class="mb-3">File Information</h5>
                                        <div class="row">
                                            <div class="col-md-4">
                                                <div class="info-item">
                                                    <div class="info-label">File Number:</div>
                                                    <div class="info-value"><?php echo htmlspecialchars($file_details['file_number']); ?></div>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="info-item">
                                                    <div class="info-label">Consignee:</div>
                                                    <div class="info-value"><?php echo htmlspecialchars($file_details['consignee_name'] ?? 'N/A'); ?></div>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="info-item">
                                                    <div class="info-label">Destination:</div>
                                                    <div class="info-value"><?php echo htmlspecialchars($file_details['destination'] ?? 'N/A'); ?></div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row mt-2">
                                            <div class="col-md-4">
                                                <div class="info-item">
                                                    <div class="info-label">BL Number:</div>
                                                    <div class="info-value"><?php echo htmlspecialchars($file_details['obl_no'] ?? 'N/A'); ?></div>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="info-item">
                                                    <div class="info-label">Type:</div>
                                                    <div class="info-value">
                                                        <?php 
                                                        if (isset($file_details['local/transit'])) {
                                                            echo $file_details['local/transit'] == 1 ? 'Local' : 'Transit';
                                                        } else {
                                                            echo 'N/A';
                                                        }
                                                        ?>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="info-item">
                                                    <div class="info-label">Created Date:</div>
                                                    <div class="info-value">
                                                        <?php 
                                                        if (!empty($file_details['created_date'])) {
                                                            echo date('d M Y', strtotime($file_details['created_date']));
                                                        } else {
                                                            echo 'N/A';
                                                        }
                                                        ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($action === 'edit' && $truck_details): ?>
                                    <!-- Transport Timeline for Edit mode -->
                                    <div class="timeline-section mb-4">
                                        <h5 class="mb-3">Transport Timeline</h5>
                                        <div class="timeline-steps">
                                            <div class="timeline-step <?php echo !empty($truck_details['load_date']) ? 'completed' : ''; ?>">
                                                <div class="timeline-step-icon">
                                                    <i class="ri-truck-line fs-22"></i>
                                                </div>
                                                <div class="timeline-step-title">Loading</div>
                                                <div class="timeline-step-date">
                                                    <?php 
                                                    echo !empty($truck_details['load_date']) ? 
                                                        date('d M Y', strtotime($truck_details['load_date'])) : 
                                                        'Not Started';
                                                    ?>
                                                </div>
                                            </div>
                                            
                                            <div class="timeline-step <?php echo !empty($truck_details['port_date']) ? 'completed' : ''; ?>">
                                                <div class="timeline-step-icon">
                                                    <i class="ri-ship-line fs-22"></i>
                                                </div>
                                                <div class="timeline-step-title">Port Exit</div>
                                                <div class="timeline-step-date">
                                                    <?php 
                                                    echo !empty($truck_details['port_date']) ? 
                                                        date('d M Y', strtotime($truck_details['port_date'])) : 
                                                        'Pending';
                                                    ?>
                                                </div>
                                            </div>
                                            
                                            <div class="timeline-step <?php echo !empty($truck_details['border_date']) ? 'completed' : ''; ?>">
                                                <div class="timeline-step-icon">
                                                    <i class="ri-road-map-line fs-22"></i>
                                                </div>
                                                <div class="timeline-step-title">At Border</div>
                                                <div class="timeline-step-date">
                                                    <?php 
                                                    echo !empty($truck_details['border_date']) ? 
                                                        date('d M Y', strtotime($truck_details['border_date'])) : 
                                                        'Pending';
                                                    ?>
                                                </div>
                                            </div>
                                            
                                            <div class="timeline-step <?php echo !empty($truck_details['border_crossing_date']) ? 'completed' : ''; ?>">
                                                <div class="timeline-step-icon">
                                                    <i class="ri-flag-line fs-22"></i>
                                                </div>
                                                <div class="timeline-step-title">Border Crossing</div>
                                                <div class="timeline-step-date">
                                                    <?php 
                                                    echo !empty($truck_details['border_crossing_date']) ? 
                                                        date('d M Y', strtotime($truck_details['border_crossing_date'])) : 
                                                        'Pending';
                                                    ?>
                                                </div>
                                            </div>
                                            
                                            <div class="timeline-step <?php echo !empty($truck_details['dest_date']) ? 'completed' : ''; ?>">
                                                <div class="timeline-step-icon">
                                                    <i class="ri-map-pin-line fs-22"></i>
                                                </div>
                                                <div class="timeline-step-title">Arrival</div>
                                                <div class="timeline-step-date">
                                                    <?php 
                                                    echo !empty($truck_details['dest_date']) ? 
                                                        date('d M Y', strtotime($truck_details['dest_date'])) : 
                                                        'Pending';
                                                    ?>
                                                </div>
                                            </div>
                                            
                                            <div class="timeline-step <?php echo !empty($truck_details['offload_date']) ? 'completed' : ''; ?>">
                                                <div class="timeline-step-icon">
                                                    <i class="ri-inbox-unarchive-line fs-22"></i>
                                                </div>
                                                <div class="timeline-step-title">Offloading</div>
                                                <div class="timeline-step-date">
                                                    <?php 
                                                    echo !empty($truck_details['offload_date']) ? 
                                                        date('d M Y', strtotime($truck_details['offload_date'])) : 
                                                        'Pending';
                                                    ?>
                                                </div>
                                            </div>
                                            
                                            <div class="timeline-step <?php echo !empty($truck_details['empty_return_date']) ? 'completed' : ''; ?>">
                                                <div class="timeline-step-icon">
                                                    <i class="ri-arrow-go-back-line fs-22"></i>
                                                </div>
                                                <div class="timeline-step-title">Empty Return</div>
                                                <div class="timeline-step-date">
                                                    <?php 
                                                    echo !empty($truck_details['empty_return_date']) ? 
                                                        date('d M Y', strtotime($truck_details['empty_return_date'])) : 
                                                        'Pending';
                                                    ?>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <form action="" method="POST" id="truckDetailsForm">
                                        <input type="hidden" name="file_no" value="<?php echo htmlspecialchars($file_number); ?>">
                                        
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label for="container_code" class="form-label">Container <span class="required">*</span></label>
                                                <select name="container_code" id="container_code" class="form-select" required <?php echo ($action === 'edit') ? 'disabled' : ''; ?>>
                                                    <option value="">Select Container</option>
                                                    <?php foreach ($containers as $container): ?>
                                                        <option value="<?php echo htmlspecialchars($container['container_code']); ?>" 
                                                            <?php echo ($action === 'edit' && $truck_details['container_code'] === $container['container_code']) ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($container['container_code']); ?> 
                                                            (<?php echo htmlspecialchars($container['container_size']); ?>ft)
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                                <?php if ($action === 'edit'): ?>
                                                    <input type="hidden" name="container_code" value="<?php echo htmlspecialchars($truck_details['container_code']); ?>">
                                                <?php endif; ?>
                                            </div>
                                            
                                            <div class="col-md-6">
                                                <label for="transporter_name" class="form-label">Transporter <span class="required">*</span></label>
                                                <select name="transporter_name" id="transporter_name" class="form-select select2" required>
                                                    <option value="">Select Transporter</option>
                                                    <?php foreach ($transporters as $transporter): ?>
                                                        <option value="<?php echo htmlspecialchars($transporter['name']); ?>" 
                                                            <?php echo ($action === 'edit' && $truck_details['transporter_name'] === $transporter['name']) ? 'selected' : ''; ?>>
                                                            <?php echo htmlspecialchars($transporter['name']); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </div>
                                        
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label for="load_date" class="form-label">Load Date</label>
                                                <input type="date" class="form-control" id="load_date" name="load_date" 
                                                    value="<?php echo ($action === 'edit' && !empty($truck_details['load_date'])) ? date('Y-m-d', strtotime($truck_details['load_date'])) : ''; ?>">
                                            </div>
                                            
                                            <div class="col-md-6">
                                                <label for="truck_trailer_no" class="form-label">Truck/Trailer Number</label>
                                                <input type="text" class="form-control" id="truck_trailer_no" name="truck_trailer_no" 
                                                    value="<?php echo ($action === 'edit') ? htmlspecialchars($truck_details['truck_trailer_no'] ?? '') : ''; ?>">
                                            </div>
                                        </div>
                                        
                                        <div class="row mb-3">
                                            <div class="col-md-4">
                                                <label for="driver_name" class="form-label">Driver Name</label>
                                                <input type="text" class="form-control" id="driver_name" name="driver_name" 
                                                    value="<?php echo ($action === 'edit') ? htmlspecialchars($truck_details['driver_name'] ?? '') : ''; ?>">
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label for="driver_phone_number" class="form-label">Driver Phone</label>
                                                <input type="text" class="form-control" id="driver_phone_number" name="driver_phone_number" 
                                                    value="<?php echo ($action === 'edit') ? htmlspecialchars($truck_details['driver_phone_number'] ?? '') : ''; ?>">
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label for="driver_license" class="form-label">Driver License</label>
                                                <input type="text" class="form-control" id="driver_license" name="driver_license" 
                                                    value="<?php echo ($action === 'edit') ? htmlspecialchars($truck_details['driver_license'] ?? '') : ''; ?>">
                                            </div>
                                        </div>
                                        
                                        <h5 class="my-4">Transport Timeline</h5>
                                        
                                        <div class="row mb-3">
                                            <div class="col-md-4">
                                                <label for="port_date" class="form-label">Port Exit Date</label>
                                                <input type="date" class="form-control" id="port_date" name="port_date" 
                                                    value="<?php echo ($action === 'edit' && !empty($truck_details['port_date'])) ? date('Y-m-d', strtotime($truck_details['port_date'])) : ''; ?>">
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label for="border_date" class="form-label">Arrival at Border Date</label>
                                                <input type="date" class="form-control" id="border_date" name="border_date" 
                                                    value="<?php echo ($action === 'edit' && !empty($truck_details['border_date'])) ? date('Y-m-d', strtotime($truck_details['border_date'])) : ''; ?>">
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label for="border_crossing_date" class="form-label">Border Crossing Date</label>
                                                <input type="date" class="form-control" id="border_crossing_date" name="border_crossing_date" 
                                                    value="<?php echo ($action === 'edit' && !empty($truck_details['border_crossing_date'])) ? date('Y-m-d', strtotime($truck_details['border_crossing_date'])) : ''; ?>">
                                            </div>
                                        </div>
                                        
                                        <div class="row mb-3">
                                            <div class="col-md-4">
                                                <label for="dest_date" class="form-label">Arrival at Destination Date</label>
                                                <input type="date" class="form-control" id="dest_date" name="dest_date" 
                                                    value="<?php echo ($action === 'edit' && !empty($truck_details['dest_date'])) ? date('Y-m-d', strtotime($truck_details['dest_date'])) : ''; ?>">
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label for="offload_date" class="form-label">Offload Date</label>
                                                <input type="date" class="form-control" id="offload_date" name="offload_date" 
                                                    value="<?php echo ($action === 'edit' && !empty($truck_details['offload_date'])) ? date('Y-m-d', strtotime($truck_details['offload_date'])) : ''; ?>">
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label for="empty_return_date" class="form-label">Empty Return Date</label>
                                                <input type="date" class="form-control" id="empty_return_date" name="empty_return_date" 
                                                    value="<?php echo ($action === 'edit' && !empty($truck_details['empty_return_date'])) ? date('Y-m-d', strtotime($truck_details['empty_return_date'])) : ''; ?>">
                                            </div>
                                        </div>
                                        
                                        <div class="row mt-4">
                                            <div class="col-12 text-end">
                                                <a href="truck_list.php" class="btn btn-light me-2">Cancel</a>
                                                <button type="submit" name="save_truck_details" class="btn btn-primary">
                                                    <?php echo $action === 'edit' ? 'Update' : 'Save'; ?> Truck Details
                                                </button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize Select2
            $('.select2').select2({
                width: '100%',
                placeholder: 'Select an option'
            });
            
            // Date validation
            const loadDate = document.getElementById('load_date');
            const portDate = document.getElementById('port_date');
            const borderDate = document.getElementById('border_date');
            const borderCrossingDate = document.getElementById('border_crossing_date');
            const destDate = document.getElementById('dest_date');
            const offloadDate = document.getElementById('offload_date');
            const emptyReturnDate = document.getElementById('empty_return_date');
            
            // Form validation
            $('#truckDetailsForm').on('submit', function(e) {
                // Validate container and transporter
                const container = $('#container_code').val();
                const transporter = $('#transporter_name').val();
                
                if (!container || !transporter) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: 'Required Fields',
                        text: 'Please select container and transporter'
                    });
                    return false;
                }
                
                // Validate date sequence
                let hasError = false;
                let errorMessage = '';
                
                // Load date to port date
                if (loadDate.value && portDate.value && new Date(loadDate.value) > new Date(portDate.value)) {
                    hasError = true;
                    errorMessage = 'Port exit date cannot be earlier than load date';
                }
                
                // Port date to border date
                if (!hasError && portDate.value && borderDate.value && new Date(portDate.value) > new Date(borderDate.value)) {
                    hasError = true;
                    errorMessage = 'Border arrival date cannot be earlier than port exit date';
                }
                
                // Border date to border crossing date
                if (!hasError && borderDate.value && borderCrossingDate.value && new Date(borderDate.value) > new Date(borderCrossingDate.value)) {
                    hasError = true;
                    errorMessage = 'Border crossing date cannot be earlier than border arrival date';
                }
                
                // Border crossing date to destination date
                if (!hasError && borderCrossingDate.value && destDate.value && new Date(borderCrossingDate.value) > new Date(destDate.value)) {
                    hasError = true;
                    errorMessage = 'Destination arrival date cannot be earlier than border crossing date';
                }
                
                // Destination date to offload date
                if (!hasError && destDate.value && offloadDate.value && new Date(destDate.value) > new Date(offloadDate.value)) {
                    hasError = true;
                    errorMessage = 'Offload date cannot be earlier than destination arrival date';
                }
                
                // Offload date to empty return date
                if (!hasError && offloadDate.value && emptyReturnDate.value && new Date(offloadDate.value) > new Date(emptyReturnDate.value)) {
                    hasError = true;
                    errorMessage = 'Empty return date cannot be earlier than offload date';
                }
                
                if (hasError) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: 'Date Sequence Error',
                        text: errorMessage
                    });
                    return false;
                }
                
                // Add loading indicator
                Swal.fire({
                    title: 'Processing',
                    text: 'Saving truck details...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                
                return true;
            });
        });
    </script>
</body>
</html>