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

date_default_timezone_set('Africa/Nairobi');

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role_name'] ?? 'User';

$sql_user = "SELECT u.*, ur.role_name FROM users u 
             INNER JOIN user_roles ur ON u.role_id = ur.role_id 
             WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if (!$user_details) {
    header('Location: logout.php');
    exit();
}

if ($_POST && isset($_POST['action']) && $_POST['action'] === 'create_manifest') {
    header('Content-Type: application/json');
    
    try {
        $manifest_type = $_POST['manifest_type'];
        $origin_warehouse = intval($_POST['origin_warehouse']);
        $destination_warehouse = intval($_POST['destination_warehouse']);
        $departure_date = $_POST['departure_date'];
        $vehicle_number = $_POST['vehicle_number'] ?? '';
        $flight_number = $_POST['flight_number'] ?? '';
        $container_number = $_POST['container_number'] ?? '';
        $driver_name = $_POST['driver_name'] ?? '';
        $driver_phone = $_POST['driver_phone'] ?? '';
        $driver_license = $_POST['driver_license'] ?? '';
        $remarks = $_POST['remarks'] ?? '';
        $shipment_ids = json_decode($_POST['shipment_ids'], true);
        
        if (empty($shipment_ids)) {
            echo json_encode(['success' => false, 'message' => 'Please select at least one shipment']);
            exit();
        }
        
        $year = date('Y');
        $manifest_sql = "SELECT COALESCE(MAX(CAST(SUBSTRING(manifest_number, 4) AS UNSIGNED)), 0) + 1 as next_number 
                        FROM manifests WHERE manifest_number LIKE 'MAN{$year}%'";
        $result = $conn->query($manifest_sql);
        $next_number = $result->fetch_assoc()['next_number'];
        $manifest_number = 'MAN' . $year . str_pad($next_number, 6, '0', STR_PAD_LEFT);
        
        $total_pieces = 0;
        $total_weight = 0;
        $shipment_placeholders = str_repeat('?,', count($shipment_ids) - 1) . '?';
        
        $shipment_sql = "SELECT SUM(pieces) as total_pieces, SUM(chargeable_weight) as total_weight 
                        FROM shipments WHERE shipment_id IN ($shipment_placeholders)";
        $stmt_shipment = $conn->prepare($shipment_sql);
        $stmt_shipment->bind_param(str_repeat('i', count($shipment_ids)), ...$shipment_ids);
        $stmt_shipment->execute();
        $totals = $stmt_shipment->get_result()->fetch_assoc();
        
        $total_pieces = $totals['total_pieces'] ?? 0;
        $total_weight = $totals['total_weight'] ?? 0;
        
        $create_sql = "INSERT INTO manifests (
                        manifest_number, manifest_type, vehicle_number, flight_number, 
                        container_number, origin_warehouse_id, destination_warehouse_id, 
                        departure_date, total_pieces, total_weight, driver_name, 
                        driver_phone, driver_license, remarks, status, created_by
                       ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'DRAFT', ?)";
        
        $stmt_create = $conn->prepare($create_sql);
        $stmt_create->bind_param("sssssiisisssssi", 
            $manifest_number, $manifest_type, $vehicle_number, $flight_number, 
            $container_number, $origin_warehouse, $destination_warehouse, 
            $departure_date, $total_pieces, $total_weight, $driver_name, 
            $driver_phone, $driver_license, $remarks, $user_id
        );
        
        if ($stmt_create->execute()) {
            $manifest_id = $conn->insert_id;
            
            $item_sql = "INSERT INTO manifest_items (manifest_id, shipment_id, pieces, weight, added_by)
                        SELECT ?, shipment_id, pieces, chargeable_weight, ?
                        FROM shipments WHERE shipment_id = ?";
            $stmt_item = $conn->prepare($item_sql);
            
            foreach ($shipment_ids as $shipment_id) {
                $stmt_item->bind_param("iii", $manifest_id, $user_id, $shipment_id);
                $stmt_item->execute();
            }
            
            $update_sql = "UPDATE shipments SET status = 'IN_TRANSIT', updated_by = ?, updated_at = NOW() 
                          WHERE shipment_id IN ($shipment_placeholders)";
            $stmt_update = $conn->prepare($update_sql);
            $params = array_merge([$user_id], $shipment_ids);
            $types = 'i' . str_repeat('i', count($shipment_ids));
            $stmt_update->bind_param($types, ...$params);
            $stmt_update->execute();
            
            echo json_encode([
                'success' => true, 
                'message' => 'Manifest created successfully',
                'manifest_id' => $manifest_id,
                'manifest_number' => $manifest_number
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to create manifest']);
        }
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
    }
    
    exit();
}

if (isset($_GET['action']) && $_GET['action'] === 'get_shipments') {
    header('Content-Type: application/json');
    
    $origin_warehouse = intval($_GET['origin_warehouse']);
    $destination_warehouse = intval($_GET['destination_warehouse']);
    
    // Get warehouse cities for filtering
    $origin_city = null;
    $destination_city = null;
    
    if ($origin_warehouse > 0) {
        $city_sql = "SELECT city FROM warehouses WHERE warehouse_id = ?";
        $stmt_city = $conn->prepare($city_sql);
        $stmt_city->bind_param("i", $origin_warehouse);
        $stmt_city->execute();
        $result = $stmt_city->get_result();
        if ($row = $result->fetch_assoc()) {
            $origin_city = $row['city'];
        }
    }
    
    if ($destination_warehouse > 0) {
        $city_sql = "SELECT city FROM warehouses WHERE warehouse_id = ?";
        $stmt_city = $conn->prepare($city_sql);
        $stmt_city->bind_param("i", $destination_warehouse);
        $stmt_city->execute();
        $result = $stmt_city->get_result();
        if ($row = $result->fetch_assoc()) {
            $destination_city = $row['city'];
        }
    }
    
    // Build WHERE conditions
    $where_conditions = ["s.status IN ('BOOKED', 'COLLECTED')"];
    $where_conditions[] = "s.shipment_id NOT IN (SELECT shipment_id FROM manifest_items WHERE shipment_id IS NOT NULL)";
    
    $params = [];
    $param_types = '';
    
    if ($origin_city) {
        $where_conditions[] = "ol.city = ?";
        $params[] = $origin_city;
        $param_types .= 's';
    }
    
    if ($destination_city) {
        $where_conditions[] = "dl.city = ?";
        $params[] = $destination_city;
        $param_types .= 's';
    }
    
    $where_clause = 'WHERE ' . implode(' AND ', $where_conditions);
    
    $shipments_sql = "
        SELECT 
            s.shipment_id,
            s.tracking_number,
            s.sender_name,
            s.receiver_name,
            s.content_description,
            s.pieces,
            s.chargeable_weight,
            s.total_charges,
            s.currency,
            s.booking_date,
            s.status,
            ol.location_name as origin_location,
            ol.city as origin_city,
            dl.location_name as destination_location,
            dl.city as destination_city,
            st.service_name
        FROM shipments s
        LEFT JOIN locations ol ON s.origin_location_id = ol.location_id
        LEFT JOIN locations dl ON s.destination_location_id = dl.location_id
        LEFT JOIN service_types st ON s.service_id = st.service_id
        $where_clause
        ORDER BY s.booking_date DESC
        LIMIT 100";
    
    $stmt_shipments = $conn->prepare($shipments_sql);
    if (!empty($params)) {
        $stmt_shipments->bind_param($param_types, ...$params);
    }
    $stmt_shipments->execute();
    $result = $stmt_shipments->get_result();
    
    $shipments = [];
    while ($row = $result->fetch_assoc()) {
        $shipments[] = $row;
    }
    
    echo json_encode($shipments);
    exit();
}

$sql_warehouses = "SELECT * FROM warehouses WHERE is_active = 1 ORDER BY warehouse_name";
$warehouses_result = $conn->query($sql_warehouses);

$sql_vehicles = "SELECT * FROM vehicles WHERE status = 'ACTIVE' ORDER BY vehicle_number";
$vehicles_result = $conn->query($sql_vehicles);

$sql_drivers = "SELECT * FROM drivers WHERE status = 'ACTIVE' ORDER BY first_name, last_name";
$drivers_result = $conn->query($sql_drivers);

$sql_routes = "SELECT r.*, ol.location_name as origin_name, dl.location_name as destination_name
               FROM routes r
               LEFT JOIN locations ol ON r.origin_location_id = ol.location_id
               LEFT JOIN locations dl ON r.destination_location_id = dl.location_id
               WHERE r.is_active = 1
               ORDER BY r.route_name";
$routes_result = $conn->query($sql_routes);

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Create Manifest')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
    
    <style>
        /* Form Input Padding Fix */
        .form-control,
        .form-select {
            padding: 0.75rem 1rem !important;
        }
        
        .form-label {
            margin-bottom: 0.5rem;
            font-weight: 500;
            color: #374151;
        }
        
        textarea.form-control {
            padding: 1rem !important;
        }
        
        .manifest-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
            position: relative;
            overflow: hidden;
        }
        
        .manifest-header::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -50%;
            width: 200%;
            height: 200%;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><rect x="20" y="20" width="60" height="60" fill="rgba(255,255,255,0.1)"/></svg>') repeat;
            transform: rotate(45deg);
            animation: float 30s linear infinite;
        }
        
        @keyframes float {
            0% { transform: translateX(-100%) rotate(45deg); }
            100% { transform: translateX(100%) rotate(45deg); }
        }
        
        .manifest-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            border: 1px solid #e5e7eb;
            transition: all 0.3s ease;
            margin-bottom: 1.5rem;
            position: relative;
            overflow: hidden;
        }
        
        .manifest-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 4px;
            height: 100%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        .manifest-card:hover {
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
            transform: translateY(-2px);
        }
        
        .card-header {
            padding: 1.25rem 1.5rem;
        }
        
        .card-body {
            padding: 1.5rem;
        }
        
        .shipment-item {
            border: 2px solid #e5e7eb;
            border-radius: 10px;
            padding: 1.25rem;
            margin-bottom: 0.75rem;
            transition: all 0.2s ease;
            cursor: pointer;
            background: white;
        }
        
        .shipment-item:hover {
            border-color: #667eea;
            background: #f8faff;
            transform: translateX(4px);
        }
        
        .shipment-item.selected {
            border-color: #667eea;
            background: #eff6ff;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
        }
        
        .shipment-checkbox {
            width: 20px;
            height: 20px;
            margin-right: 1rem;
            cursor: pointer;
            accent-color: #667eea;
        }
        
        .weight-indicator {
            display: inline-block;
            padding: 0.4rem 0.75rem;
            border-radius: 8px;
            font-size: 0.8rem;
            font-weight: 600;
            background: #e3f2fd;
            color: #1976d2;
        }
        
        .summary-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px;
            padding: 1.5rem;
            text-align: center;
            margin-bottom: 1.5rem;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }
        
        .summary-value {
            font-size: 2.25rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        .summary-label {
            font-size: 0.9rem;
            opacity: 0.95;
            font-weight: 500;
        }
        
        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.95);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 10;
            border-radius: 15px;
        }
        
        .driver-info {
            background: linear-gradient(135deg, #d1ecf1 0%, #bee5eb 100%);
            border: 2px solid #17a2b8;
            border-radius: 12px;
            padding: 1.25rem;
            margin-top: 1.5rem;
        }
        
        .driver-info h6 {
            color: #0c5460;
            font-weight: 600;
        }
        
        .empty-state {
            text-align: center;
            padding: 3rem 2rem;
        }
        
        .empty-state i {
            font-size: 4rem;
            color: #d1d5db;
            margin-bottom: 1rem;
        }
        
        .empty-state p {
            color: #6b7280;
            font-size: 1.1rem;
            margin-bottom: 0.5rem;
        }
        
        .empty-state small {
            color: #9ca3af;
        }
        
        .btn {
            padding: 0.75rem 1.5rem;
            font-weight: 500;
        }
        
        .btn-lg {
            padding: 1rem 2rem;
            font-size: 1.05rem;
        }
        
        @media (max-width: 768px) {
            .manifest-header {
                padding: 1.5rem;
                text-align: center;
            }
            
            .summary-value {
                font-size: 1.75rem;
            }
            
            .card-body {
                padding: 1rem;
            }
            
            .shipment-item {
                padding: 1rem;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0"><i class="ri-file-list-3-line me-2"></i>Create Manifest</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="warehouse_management.php">Warehouse</a></li>
                                        <li class="breadcrumb-item active">Create Manifest</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="manifest-header">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <h2 class="mb-1">Create New Manifest</h2>
                                <p class="mb-0 opacity-90">
                                    Organize shipments into manifests for efficient transportation and tracking
                                </p>
                            </div>
                            <div class="col-md-4 text-md-end">
                                <a href="manifests.php" class="btn btn-light btn-lg">
                                    <i class="ri-list-check-line me-2"></i>View All Manifests
                                </a>
                            </div>
                        </div>
                    </div>

                    <form id="createManifestForm">
                        <div class="row">
                            <div class="col-xl-8">
                                <div class="manifest-card">
                                    <div class="card-header bg-transparent border-bottom">
                                        <h5 class="card-title mb-0">
                                            <i class="ri-information-line me-2"></i>Manifest Information
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row g-3">
                                            <div class="col-md-6">
                                                <label for="manifest_type" class="form-label">Manifest Type *</label>
                                                <select class="form-select" id="manifest_type" name="manifest_type" required>
                                                    <option value="">Select Type</option>
                                                    <option value="TRUCK">Truck Manifest</option>
                                                    <option value="FLIGHT">Flight Manifest</option>
                                                    <option value="CONTAINER">Container Manifest</option>
                                                    <option value="VESSEL">Vessel Manifest</option>
                                                </select>
                                            </div>
                                            
                                            <div class="col-md-6">
                                                <label for="departure_date" class="form-label">Departure Date & Time *</label>
                                                <input type="datetime-local" class="form-control" id="departure_date" 
                                                       name="departure_date" required 
                                                       value="<?php echo date('Y-m-d\TH:i', strtotime('+1 day')); ?>">
                                            </div>
                                            
                                            <div class="col-md-6">
                                                <label for="origin_warehouse" class="form-label">Origin Warehouse *</label>
                                                <select class="form-select" id="origin_warehouse" name="origin_warehouse" 
                                                        onchange="loadAvailableShipments()" required>
                                                    <option value="">Select Origin</option>
                                                    <?php while ($warehouse = $warehouses_result->fetch_assoc()): ?>
                                                    <option value="<?php echo $warehouse['warehouse_id']; ?>">
                                                        <?php echo $warehouse['warehouse_name']; ?> - <?php echo $warehouse['city']; ?>
                                                    </option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>
                                            
                                            <div class="col-md-6">
                                                <label for="destination_warehouse" class="form-label">Destination Warehouse *</label>
                                                <select class="form-select" id="destination_warehouse" name="destination_warehouse" 
                                                        onchange="loadAvailableShipments()" required>
                                                    <option value="">Select Destination</option>
                                                    <?php 
                                                    $warehouses_result->data_seek(0);
                                                    while ($warehouse = $warehouses_result->fetch_assoc()): 
                                                    ?>
                                                    <option value="<?php echo $warehouse['warehouse_id']; ?>">
                                                        <?php echo $warehouse['warehouse_name']; ?> - <?php echo $warehouse['city']; ?>
                                                    </option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="manifest-card">
                                    <div class="card-header bg-transparent border-bottom">
                                        <h5 class="card-title mb-0">
                                            <i class="ri-truck-line me-2"></i>Transport Details
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row g-3">
                                            <div class="col-md-4">
                                                <label for="vehicle_selection" class="form-label">Select Vehicle</label>
                                                <select class="form-select" id="vehicle_selection" onchange="fillVehicleDetails()">
                                                    <option value="">Choose from registered vehicles</option>
                                                    <?php while ($vehicle = $vehicles_result->fetch_assoc()): ?>
                                                    <option value="<?php echo $vehicle['vehicle_id']; ?>" 
                                                            data-number="<?php echo $vehicle['vehicle_number']; ?>"
                                                            data-type="<?php echo $vehicle['vehicle_type']; ?>"
                                                            data-capacity="<?php echo $vehicle['capacity_weight']; ?>">
                                                        <?php echo $vehicle['vehicle_number']; ?> - <?php echo ucfirst($vehicle['vehicle_type']); ?>
                                                        (<?php echo number_format($vehicle['capacity_weight']); ?>kg)
                                                    </option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label for="vehicle_number" class="form-label">Vehicle Number</label>
                                                <input type="text" class="form-control" id="vehicle_number" 
                                                       name="vehicle_number" placeholder="Enter vehicle number">
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label for="flight_number" class="form-label">Flight Number</label>
                                                <input type="text" class="form-control" id="flight_number" 
                                                       name="flight_number" placeholder="Enter flight number">
                                            </div>
                                            
                                            <div class="col-md-12">
                                                <label for="container_number" class="form-label">Container Number</label>
                                                <input type="text" class="form-control" id="container_number" 
                                                       name="container_number" placeholder="Enter container number">
                                            </div>
                                        </div>
                                        
                                        <div class="driver-info">
                                            <h6 class="mb-3"><i class="ri-user-line me-2"></i>Driver Information</h6>
                                            <div class="row g-3">
                                                <div class="col-md-12">
                                                    <label for="driver_selection" class="form-label">Select Driver</label>
                                                    <select class="form-select" id="driver_selection" onchange="fillDriverDetails()">
                                                        <option value="">Choose from registered drivers</option>
                                                        <?php while ($driver = $drivers_result->fetch_assoc()): ?>
                                                        <option value="<?php echo $driver['driver_id']; ?>"
                                                                data-name="<?php echo $driver['first_name'] . ' ' . $driver['last_name']; ?>"
                                                                data-phone="<?php echo $driver['phone']; ?>"
                                                                data-license="<?php echo $driver['license_number']; ?>">
                                                            <?php echo $driver['first_name'] . ' ' . $driver['last_name']; ?> 
                                                            (<?php echo $driver['driver_code']; ?>)
                                                        </option>
                                                        <?php endwhile; ?>
                                                    </select>
                                                </div>
                                                
                                                <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" placeholder="Enter driver name">
                                                </div>
                                                
                                                <div class="col-md-4">
                                                    <label for="driver_phone" class="form-label">Driver Phone</label>
                                                    <input type="text" class="form-control" id="driver_phone" 
                                                           name="driver_phone" placeholder="Enter phone number">
                                                </div>
                                                
                                                <div class="col-md-4">
                                                    <label for="driver_license" class="form-label">License Number</label>
                                                    <input type="text" class="form-control" id="driver_license" 
                                                           name="driver_license" placeholder="Enter license number">
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="mt-3">
                                            <label for="remarks" class="form-label">Remarks</label>
                                            <textarea class="form-control" id="remarks" name="remarks" rows="3" 
                                                     placeholder="Enter any additional remarks or special instructions..."></textarea>
                                        </div>
                                    </div>
                                </div>

                                <div class="manifest-card">
                                    <div class="card-header bg-transparent border-bottom">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <h5 class="card-title mb-0">
                                                <i class="ri-package-line me-2"></i>Available Shipments
                                            </h5>
                                            <div class="btn-group" role="group">
                                                <button type="button" class="btn btn-sm btn-outline-primary" onclick="selectAllShipments()">
                                                    <i class="ri-check-double-line me-1"></i>Select All
                                                </button>
                                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="clearAllShipments()">
                                                    <i class="ri-close-line me-1"></i>Clear All
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="card-body">
                                        <div id="shipmentsContainer" style="position: relative; min-height: 200px;">
                                            <div class="empty-state">
                                                <i class="ri-ship-line"></i>
                                                <p>Select origin and destination warehouses</p>
                                                <small>Available shipments will be displayed here</small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-xl-4">
                                <div class="summary-card">
                                    <div class="summary-value" id="selectedCount">0</div>
                                    <div class="summary-label">Shipments Selected</div>
                                </div>
                                
                                <div class="summary-card" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
                                    <div class="summary-value" id="totalWeight">0.0kg</div>
                                    <div class="summary-label">Total Weight</div>
                                </div>
                                
                                <div class="summary-card" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);">
                                    <div class="summary-value" id="totalPieces">0</div>
                                    <div class="summary-label">Total Pieces</div>
                                </div>

                                <div class="manifest-card">
                                    <div class="card-header bg-transparent border-bottom">
                                        <h6 class="card-title mb-0">
                                            <i class="ri-route-line me-2"></i>Popular Routes
                                        </h6>
                                    </div>
                                    <div class="card-body">
                                        <?php if ($routes_result->num_rows > 0): ?>
                                            <?php while ($route = $routes_result->fetch_assoc()): ?>
                                            <div class="mb-2 p-2 border rounded small">
                                                <div class="fw-bold"><?php echo $route['route_name']; ?></div>
                                                <div class="text-muted">
                                                    <?php echo $route['origin_name']; ?> → <?php echo $route['destination_name']; ?>
                                                </div>
                                                <?php if ($route['distance_km']): ?>
                                                <small class="text-info"><?php echo number_format($route['distance_km']); ?>km</small>
                                                <?php endif; ?>
                                            </div>
                                            <?php endwhile; ?>
                                        <?php else: ?>
                                        <p class="text-muted small">No routes configured</p>
                                        <?php endif; ?>
                                    </div>
                                </div>

                                <div class="d-grid gap-2">
                                    <button type="submit" class="btn btn-success btn-lg">
                                        <i class="ri-file-add-line me-2"></i>Create Manifest
                                    </button>
                                    <button type="button" class="btn btn-outline-secondary" onclick="resetForm()">
                                        <i class="ri-refresh-line me-2"></i>Reset Form
                                    </button>
                                    <a href="manifests.php" class="btn btn-outline-primary">
                                        <i class="ri-arrow-left-line me-2"></i>Back to Manifests
                                    </a>
                                </div>
                            </div>
                        </div>
                    </form>

                </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://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>
    
    <script>
$(document).ready(function() {
    // Auto-load shipments on page load
    setTimeout(function() {
        loadAvailableShipments();
    }, 500);

    $('#createManifestForm').on('submit', function(e) {
        e.preventDefault();
        
        const selectedShipments = [];
        $('.shipment-checkbox:checked').each(function() {
            selectedShipments.push(this.value);
        });
        
        if (selectedShipments.length === 0) {
            Swal.fire({
                title: 'No Shipments Selected',
                text: 'Please select at least one shipment to include in the manifest.',
                icon: 'warning',
                confirmButtonText: 'OK',
                confirmButtonColor: '#667eea'
            });
            return;
        }
        
        // Validate required fields
        const manifestType = $('#manifest_type').val();
        const originWarehouse = $('#origin_warehouse').val();
        const destinationWarehouse = $('#destination_warehouse').val();
        const departureDate = $('#departure_date').val();
        
        if (!manifestType || !originWarehouse || !destinationWarehouse || !departureDate) {
            Swal.fire({
                title: 'Missing Required Fields',
                text: 'Please fill in all required fields before creating the manifest.',
                icon: 'warning',
                confirmButtonText: 'OK',
                confirmButtonColor: '#667eea'
            });
            return;
        }
        
        if (originWarehouse === destinationWarehouse) {
            Swal.fire({
                title: 'Invalid Route',
                text: 'Origin and destination warehouses cannot be the same.',
                icon: 'warning',
                confirmButtonText: 'OK',
                confirmButtonColor: '#667eea'
            });
            return;
        }
        
        const formData = new FormData(this);
        formData.append('action', 'create_manifest');
        formData.append('shipment_ids', JSON.stringify(selectedShipments));
        
        Swal.fire({
            title: 'Creating Manifest...',
            html: '<div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div><p class="mt-3">Please wait while we generate your manifest.</p>',
            allowOutsideClick: false,
            showConfirmButton: false
        });
        
        $.ajax({
            url: 'create_manifest.php',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        title: 'Manifest Created!',
                        html: `<p>Manifest <strong>${response.manifest_number}</strong> has been created successfully with ${selectedShipments.length} shipment(s).</p>`,
                        icon: 'success',
                        showCancelButton: true,
                        confirmButtonText: '<i class="ri-eye-line me-1"></i>View Manifest',
                        cancelButtonText: '<i class="ri-add-line me-1"></i>Create Another',
                        confirmButtonColor: '#667eea',
                        cancelButtonColor: '#10b981'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.location.href = `view_manifest.php?id=${response.manifest_id}`;
                        } else {
                            resetForm();
                        }
                    });
                } else {
                    Swal.fire({
                        title: 'Error',
                        text: response.message,
                        icon: 'error',
                        confirmButtonColor: '#667eea'
                    });
                }
            },
            error: function(xhr, status, error) {
                console.error('Error:', error);
                Swal.fire({
                    title: 'Error',
                    text: 'An error occurred while creating the manifest. Please try again.',
                    icon: 'error',
                    confirmButtonColor: '#667eea'
                });
            }
        });
    });

    $(document).on('change', '.shipment-checkbox', function() {
        updateManifestSummary();
    });
});

function loadAvailableShipments() {
    const originWarehouse = $('#origin_warehouse').val();
    const destinationWarehouse = $('#destination_warehouse').val();
    const container = $('#shipmentsContainer');
    
    // Show loading state
    container.html(`
        <div class="loading-overlay">
            <div class="text-center">
                <div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p class="mt-3 fw-bold">Loading available shipments...</p>
                <small class="text-muted">This may take a moment</small>
            </div>
        </div>
    `);
    
    $.ajax({
        url: 'create_manifest.php',
        method: 'GET',
        data: {
            action: 'get_shipments',
            origin_warehouse: originWarehouse || 0,
            destination_warehouse: destinationWarehouse || 0
        },
        dataType: 'json',
        success: function(shipments) {
            console.log('Loaded shipments:', shipments.length);
            
            if (shipments.length === 0) {
                container.html(`
                    <div class="empty-state">
                        <i class="ri-inbox-line"></i>
                        <p>No shipments available for the selected route</p>
                        <small>Shipments must be in 'BOOKED' or 'COLLECTED' status and not already in a manifest</small>
                        ${originWarehouse || destinationWarehouse ? '<br><small class="text-info mt-2 d-block">Try selecting different warehouses</small>' : ''}
                    </div>
                `);
                updateManifestSummary();
                return;
            }
            
            let html = '<div class="mb-3 alert alert-info"><i class="ri-information-line me-2"></i>Found <strong>' + shipments.length + '</strong> shipment(s) available for this route</div>';
            
            shipments.forEach(function(shipment) {
                html += `
                    <div class="shipment-item" data-shipment-id="${shipment.shipment_id}">
                        <div class="d-flex align-items-start">
                            <input type="checkbox" class="shipment-checkbox" value="${shipment.shipment_id}" 
                                   data-weight="${shipment.chargeable_weight}" 
                                   data-pieces="${shipment.pieces}"
                                   id="shipment_${shipment.shipment_id}">
                            <label for="shipment_${shipment.shipment_id}" class="flex-grow-1" style="cursor: pointer;">
                                <div class="d-flex justify-content-between align-items-start mb-2">
                                    <div>
                                        <div class="fw-bold text-primary" style="font-size: 1.05rem;">${shipment.tracking_number}</div>
                                        <div class="text-muted small">
                                            <i class="ri-apps-line me-1"></i>${shipment.service_name}
                                            <span class="badge bg-soft-primary text-primary ms-2">${shipment.status}</span>
                                        </div>
                                    </div>
                                    <div class="text-end">
                                        <span class="weight-indicator mb-1">${parseFloat(shipment.chargeable_weight).toFixed(1)}kg</span>
                                        <div class="small text-muted mt-1">
                                            <i class="ri-archive-line me-1"></i>${shipment.pieces} piece(s)
                                        </div>
                                    </div>
                                </div>
                                <div class="mb-2">
                                    <div class="small mb-1">
                                        <i class="ri-user-line me-1"></i><strong>From:</strong> ${shipment.sender_name}
                                    </div>
                                    <div class="small mb-1">
                                        <i class="ri-user-received-line me-1"></i><strong>To:</strong> ${shipment.receiver_name}
                                    </div>
                                    <div class="small text-muted">
                                        <i class="ri-file-text-line me-1"></i>${shipment.content_description}
                                    </div>
                                </div>
                                <div class="d-flex justify-content-between align-items-center pt-2 border-top">
                                    <div class="small" style="color: #6b7280;">
                                        <i class="ri-map-pin-line me-1"></i>${shipment.origin_location || shipment.origin_city} → ${shipment.destination_location || shipment.destination_city}
                                    </div>
                                    <div class="small text-muted">
                                        <i class="ri-calendar-line me-1"></i>${new Date(shipment.booking_date).toLocaleDateString('en-US', {month: 'short', day: 'numeric', year: 'numeric'})}
                                    </div>
                                </div>
                            </label>
                        </div>
                    </div>
                `;
            });
            
            html += `
                <div class="mt-3 p-3 rounded" style="background: linear-gradient(135deg, #f8faff 0%, #eff6ff 100%); border: 2px solid #667eea;">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <strong style="color: #667eea;">${shipments.length} shipment(s) available</strong>
                        </div>
                        <div>
                            <button type="button" class="btn btn-sm btn-primary me-2" onclick="selectAllShipments()">
                                <i class="ri-check-double-line me-1"></i>Select All
                            </button>
                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="clearAllShipments()">
                                <i class="ri-close-line me-1"></i>Clear All
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            container.html(html);
            updateManifestSummary();
        },
        error: function(xhr, status, error) {
            console.error('Error loading shipments:', error);
            container.html(`
                <div class="empty-state">
                    <i class="ri-error-warning-line text-danger"></i>
                    <p class="text-danger">Error loading shipments</p>
                    <small class="text-muted">${error || 'Please try again'}</small>
                    <br>
                    <button class="btn btn-outline-primary btn-sm mt-3" onclick="loadAvailableShipments()">
                        <i class="ri-refresh-line me-1"></i>Retry
                    </button>
                </div>
            `);
        }
    });
}

function updateManifestSummary() {
    let totalCount = 0;
    let totalWeight = 0;
    let totalPieces = 0;
    
    $('.shipment-checkbox:checked').each(function() {
        totalCount++;
        totalWeight += parseFloat($(this).data('weight')) || 0;
        totalPieces += parseInt($(this).data('pieces')) || 0;
        
        // Add selected class to parent item
        $(this).closest('.shipment-item').addClass('selected');
    });
    
    // Remove selected class from unchecked items
    $('.shipment-checkbox:not(:checked)').each(function() {
        $(this).closest('.shipment-item').removeClass('selected');
    });
    
    $('#selectedCount').text(totalCount);
    $('#totalWeight').text(totalWeight.toFixed(1) + 'kg');
    $('#totalPieces').text(totalPieces);
}

function selectAllShipments() {
    $('.shipment-checkbox').prop('checked', true);
    $('.shipment-item').addClass('selected');
    updateManifestSummary();
    
    Swal.fire({
        toast: true,
        position: 'top-end',
        icon: 'success',
        title: 'All shipments selected',
        showConfirmButton: false,
        timer: 2000
    });
}

function clearAllShipments() {
    $('.shipment-checkbox').prop('checked', false);
    $('.shipment-item').removeClass('selected');
    updateManifestSummary();
    
    Swal.fire({
        toast: true,
        position: 'top-end',
        icon: 'info',
        title: 'Selection cleared',
        showConfirmButton: false,
        timer: 2000
    });
}

function fillVehicleDetails() {
    const selectedOption = $('#vehicle_selection option:selected');
    
    if (selectedOption.val()) {
        $('#vehicle_number').val(selectedOption.data('number'));
        
        Swal.fire({
            toast: true,
            position: 'top-end',
            icon: 'success',
            title: 'Vehicle details filled',
            showConfirmButton: false,
            timer: 1500
        });
    } else {
        $('#vehicle_number').val('');
    }
}

function fillDriverDetails() {
    const selectedOption = $('#driver_selection option:selected');
    
    if (selectedOption.val()) {
        $('#driver_name').val(selectedOption.data('name'));
        $('#driver_phone').val(selectedOption.data('phone'));
        $('#driver_license').val(selectedOption.data('license'));
        
        Swal.fire({
            toast: true,
            position: 'top-end',
            icon: 'success',
            title: 'Driver details filled',
            showConfirmButton: false,
            timer: 1500
        });
    } else {
        $('#driver_name').val('');
        $('#driver_phone').val('');
        $('#driver_license').val('');
    }
}

function resetForm() {
    Swal.fire({
        title: 'Reset Form?',
        text: 'This will clear all entered data and selections.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, Reset',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#667eea',
        cancelButtonColor: '#6b7280'
    }).then((result) => {
        if (result.isConfirmed) {
            $('#createManifestForm')[0].reset();
            $('#shipmentsContainer').html(`
                <div class="empty-state">
                    <i class="ri-ship-line"></i>
                    <p>Select origin and destination warehouses</p>
                    <small>Available shipments will be displayed here</small>
                </div>
            `);
            updateManifestSummary();
            
            Swal.fire({
                toast: true,
                position: 'top-end',
                icon: 'success',
                title: 'Form has been reset',
                showConfirmButton: false,
                timer: 2000
            });
        }
    });
}

// Auto-refresh shipments when warehouse selection changes
$('#origin_warehouse, #destination_warehouse').on('change', function() {
    const origin = $('#origin_warehouse').val();
    const destination = $('#destination_warehouse').val();
    
    if (origin && destination && origin === destination) {
        Swal.fire({
            toast: true,
            position: 'top-end',
            icon: 'warning',
            title: 'Origin and destination cannot be the same',
            showConfirmButton: false,
            timer: 3000
        });
    }
});
</script>

    <script src="assets/js/app.js"></script>
</body>
</html>