<?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();
}

// Handle AJAX requests
if (isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    switch ($_POST['action']) {
        case 'update_status':
            $manifest_id = intval($_POST['manifest_id']);
            $new_status = $_POST['status'];
            
            $allowed_statuses = ['DRAFT', 'CONFIRMED', 'DEPARTED', 'ARRIVED', 'CLOSED'];
            if (!in_array($new_status, $allowed_statuses)) {
                echo json_encode(['success' => false, 'message' => 'Invalid status']);
                exit();
            }
            
            $update_sql = "UPDATE manifests SET status = ?, updated_at = NOW() WHERE manifest_id = ?";
            $stmt = $conn->prepare($update_sql);
            $stmt->bind_param("si", $new_status, $manifest_id);
            
            if ($stmt->execute()) {
                // Log activity
                $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, old_values, new_values) 
                           VALUES (?, 'UPDATE', 'manifests', ?, 'status_change', ?)";
                $stmt_log = $conn->prepare($log_sql);
                $stmt_log->bind_param("iss", $user_id, $manifest_id, $new_status);
                $stmt_log->execute();
                
                echo json_encode(['success' => true, 'message' => 'Manifest status updated successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to update manifest status']);
            }
            break;
            
        case 'delete_manifest':
            $manifest_id = intval($_POST['manifest_id']);
            
            // Check if manifest can be deleted (only DRAFT status)
            $check_sql = "SELECT status FROM manifests WHERE manifest_id = ?";
            $stmt_check = $conn->prepare($check_sql);
            $stmt_check->bind_param("i", $manifest_id);
            $stmt_check->execute();
            $result = $stmt_check->get_result();
            $manifest = $result->fetch_assoc();
            
            if ($manifest['status'] !== 'DRAFT') {
                echo json_encode(['success' => false, 'message' => 'Only DRAFT manifests can be deleted']);
                exit();
            }
            
            // Delete manifest items first
            $delete_items_sql = "DELETE FROM manifest_items WHERE manifest_id = ?";
            $stmt_items = $conn->prepare($delete_items_sql);
            $stmt_items->bind_param("i", $manifest_id);
            $stmt_items->execute();
            
            // Delete manifest
            $delete_sql = "DELETE FROM manifests WHERE manifest_id = ?";
            $stmt_delete = $conn->prepare($delete_sql);
            $stmt_delete->bind_param("i", $manifest_id);
            
            if ($stmt_delete->execute()) {
                echo json_encode(['success' => true, 'message' => 'Manifest deleted successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to delete manifest']);
            }
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
    exit();
}

// Filter parameters
$status_filter = $_GET['status'] ?? '';
$type_filter = $_GET['type'] ?? '';
$warehouse_filter = $_GET['warehouse'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';

// Build WHERE clause
$where_conditions = [];
$params = [];
$param_types = '';

if ($status_filter) {
    $where_conditions[] = "m.status = ?";
    $params[] = $status_filter;
    $param_types .= 's';
}

if ($type_filter) {
    $where_conditions[] = "m.manifest_type = ?";
    $params[] = $type_filter;
    $param_types .= 's';
}

if ($warehouse_filter) {
    $where_conditions[] = "(m.origin_warehouse_id = ? OR m.destination_warehouse_id = ?)";
    $params[] = $warehouse_filter;
    $params[] = $warehouse_filter;
    $param_types .= 'ii';
}

if ($date_from) {
    $where_conditions[] = "DATE(m.departure_date) >= ?";
    $params[] = $date_from;
    $param_types .= 's';
}

if ($date_to) {
    $where_conditions[] = "DATE(m.departure_date) <= ?";
    $params[] = $date_to;
    $param_types .= 's';
}

$where_clause = empty($where_conditions) ? '' : 'WHERE ' . implode(' AND ', $where_conditions);

// Get manifests with details
$sql_manifests = "
    SELECT 
        m.*,
        ow.warehouse_name as origin_warehouse,
        ow.city as origin_city,
        dw.warehouse_name as destination_warehouse,
        dw.city as destination_city,
        creator.full_name as created_by_name,
        COUNT(mi.item_id) as shipment_count,
        DATEDIFF(m.departure_date, NOW()) as days_until_departure
    FROM manifests m
    LEFT JOIN warehouses ow ON m.origin_warehouse_id = ow.warehouse_id
    LEFT JOIN warehouses dw ON m.destination_warehouse_id = dw.warehouse_id
    LEFT JOIN users creator ON m.created_by = creator.user_id
    LEFT JOIN manifest_items mi ON m.manifest_id = mi.manifest_id
    $where_clause
    GROUP BY m.manifest_id, m.manifest_number, m.manifest_type, m.vehicle_number, 
             m.flight_number, m.container_number, m.origin_warehouse_id, 
             m.destination_warehouse_id, m.departure_date, m.arrival_date, 
             m.total_pieces, m.total_weight, m.status, m.created_at,
             ow.warehouse_name, ow.city, dw.warehouse_name, dw.city, creator.full_name
    ORDER BY m.created_at DESC";

$stmt_manifests = $conn->prepare($sql_manifests);
if (!empty($params)) {
    $stmt_manifests->bind_param($param_types, ...$params);
}
$stmt_manifests->execute();
$manifests_result = $stmt_manifests->get_result();

// Get summary statistics
$sql_summary = "
    SELECT 
        COUNT(*) as total_manifests,
        SUM(CASE WHEN m.status = 'DRAFT' THEN 1 ELSE 0 END) as draft_count,
        SUM(CASE WHEN m.status = 'CONFIRMED' THEN 1 ELSE 0 END) as confirmed_count,
        SUM(CASE WHEN m.status = 'DEPARTED' THEN 1 ELSE 0 END) as departed_count,
        SUM(CASE WHEN m.status = 'ARRIVED' THEN 1 ELSE 0 END) as arrived_count,
        SUM(m.total_pieces) as total_pieces,
        SUM(m.total_weight) as total_weight
    FROM manifests m
    $where_clause";

$stmt_summary = $conn->prepare($sql_summary);
if (!empty($params)) {
    $stmt_summary->bind_param($param_types, ...$params);
}
$stmt_summary->execute();
$summary = $stmt_summary->get_result()->fetch_assoc();

// Get warehouses for filter
$sql_warehouses = "SELECT warehouse_id, warehouse_name, city FROM warehouses WHERE is_active = 1 ORDER BY warehouse_name";
$warehouses_result = $conn->query($sql_warehouses);

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Manifest Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- DataTables CSS -->
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap5.min.css" rel="stylesheet">
    
    <!-- SweetAlert2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    
    <!-- Remix Icons -->
    <link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
    
    <style>
        .manifest-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border: 1px solid #e3e6f0;
            transition: all 0.3s ease;
            margin-bottom: 1.5rem;
        }
        
        .manifest-card:hover {
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
            transform: translateY(-2px);
        }
        
        .summary-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 1.5rem;
            position: relative;
            overflow: hidden;
        }
        
        .summary-card::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 100px;
            height: 100px;
            background: rgba(255,255,255,0.1);
            border-radius: 50%;
            transform: translate(30px, -30px);
        }
        
        .summary-value {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .summary-label {
            font-size: 0.9rem;
            opacity: 0.9;
        }
        
        .status-badge {
            padding: 0.35rem 0.75rem;
            border-radius: 15px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .status-draft { background: #f8f9fa; color: #6c757d; }
        .status-confirmed { background: #cff4fc; color: #055160; }
        .status-departed { background: #fff3cd; color: #664d03; }
        .status-arrived { background: #d1e7dd; color: #0a3622; }
        .status-closed { background: #f1f3f4; color: #3c4043; }
        
        .type-badge {
            display: inline-block;
            padding: 0.25rem 0.6rem;
            border-radius: 8px;
            font-size: 0.7rem;
            font-weight: 600;
            margin: 0.1rem;
        }
        
        .type-truck { background: #e3f2fd; color: #1976d2; }
        .type-flight { background: #f3e5f5; color: #7b1fa2; }
        .type-container { background: #e8f5e8; color: #2e7d32; }
        .type-vessel { background: #fff3e0; color: #ef6c00; }
        
        .action-btn {
            padding: 0.25rem 0.5rem;
            border-radius: 6px;
            font-size: 0.75rem;
            margin: 0.1rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-view { background: #e3f2fd; color: #1976d2; }
        .btn-edit { background: #fff3e0; color: #ef6c00; }
        .btn-delete { background: #ffebee; color: #c62828; }
        .btn-print { background: #f3e5f5; color: #7b1fa2; }
        
        .action-btn:hover {
            transform: scale(1.05);
        }
        
        .filter-section {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            border: 1px solid #e9ecef;
        }
        
        .create-manifest-btn {
            background: linear-gradient(45deg, #667eea, #764ba2);
            border: none;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 10px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        }
        
        .create-manifest-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
            color: white;
        }
        
        .route-indicator {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.875rem;
        }
        
        .route-arrow {
            color: #667eea;
            font-weight: bold;
        }
        
        .weight-display {
            background: #e8f5e8;
            color: #2e7d32;
            padding: 0.25rem 0.5rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .urgent-indicator {
            background: #dc3545;
            color: white;
            padding: 0.1rem 0.3rem;
            border-radius: 3px;
            font-size: 0.6rem;
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }
        
        @media (max-width: 768px) {
            .summary-card {
                margin-bottom: 1rem;
            }
            
            .summary-value {
                font-size: 1.5rem;
            }
            
            .table-responsive {
                font-size: 0.875rem;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <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>Manifest Management</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">Manifests</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Summary Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                                <div class="summary-value"><?php echo number_format($summary['total_manifests']); ?></div>
                                <div class="summary-label">Total Manifests</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                                <div class="summary-value"><?php echo number_format($summary['draft_count']); ?></div>
                                <div class="summary-label">Draft Manifests</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                                <div class="summary-value"><?php echo number_format($summary['departed_count']); ?></div>
                                <div class="summary-label">In Transit</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
                                <div class="summary-value"><?php echo number_format($summary['total_weight'], 0); ?>kg</div>
                                <div class="summary-label">Total Weight</div>
                            </div>
                        </div>
                    </div>

                    <!-- Actions and Filters -->
                    <div class="row">
                        <div class="col-12">
                            <div class="manifest-card">
                                <div class="card-body">
                                    <div class="row align-items-center">
                                        <div class="col-md-6">
                                            <a href="create_manifest.php" class="btn create-manifest-btn me-2">
                                                <i class="ri-add-line me-1"></i>Create Manifest
                                            </a>
                                            <button class="btn btn-outline-success me-2" onclick="exportManifests()">
                                                <i class="ri-download-line me-1"></i>Export
                                            </button>
                                            <button class="btn btn-outline-info" onclick="printManifests()">
                                                <i class="ri-printer-line me-1"></i>Print
                                            </button>
                                        </div>
                                        <div class="col-md-6 text-end">
                                            <button class="btn btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#filterSection">
                                                <i class="ri-filter-3-line me-1"></i>Filters
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filter Section -->
                    <div class="collapse" id="filterSection">
                        <div class="filter-section">
                            <form method="GET" class="row g-3">
                                <div class="col-md-2">
                                    <label for="status" class="form-label">Status</label>
                                    <select class="form-select" name="status" id="status">
                                        <option value="">All Status</option>
                                        <option value="DRAFT" <?php echo $status_filter == 'DRAFT' ? 'selected' : ''; ?>>Draft</option>
                                        <option value="CONFIRMED" <?php echo $status_filter == 'CONFIRMED' ? 'selected' : ''; ?>>Confirmed</option>
                                        <option value="DEPARTED" <?php echo $status_filter == 'DEPARTED' ? 'selected' : ''; ?>>Departed</option>
                                        <option value="ARRIVED" <?php echo $status_filter == 'ARRIVED' ? 'selected' : ''; ?>>Arrived</option>
                                        <option value="CLOSED" <?php echo $status_filter == 'CLOSED' ? 'selected' : ''; ?>>Closed</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-2">
                                    <label for="type" class="form-label">Type</label>
                                    <select class="form-select" name="type" id="type">
                                        <option value="">All Types</option>
                                        <option value="TRUCK" <?php echo $type_filter == 'TRUCK' ? 'selected' : ''; ?>>Truck</option>
                                        <option value="FLIGHT" <?php echo $type_filter == 'FLIGHT' ? 'selected' : ''; ?>>Flight</option>
                                        <option value="CONTAINER" <?php echo $type_filter == 'CONTAINER' ? 'selected' : ''; ?>>Container</option>
                                        <option value="VESSEL" <?php echo $type_filter == 'VESSEL' ? 'selected' : ''; ?>>Vessel</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-3">
                                    <label for="warehouse" class="form-label">Warehouse</label>
                                    <select class="form-select" name="warehouse" id="warehouse">
                                        <option value="">All Warehouses</option>
                                        <?php while ($warehouse = $warehouses_result->fetch_assoc()): ?>
                                        <option value="<?php echo $warehouse['warehouse_id']; ?>" <?php echo $warehouse_filter == $warehouse['warehouse_id'] ? 'selected' : ''; ?>>
                                            <?php echo $warehouse['warehouse_name']; ?> - <?php echo $warehouse['city']; ?>
                                        </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                
                                <div class="col-md-2">
                                    <label for="date_from" class="form-label">Date From</label>
                                    <input type="date" class="form-control" name="date_from" id="date_from" value="<?php echo $date_from; ?>">
                                </div>
                                
                                <div class="col-md-2">
                                    <label for="date_to" class="form-label">Date To</label>
                                    <input type="date" class="form-control" name="date_to" id="date_to" value="<?php echo $date_to; ?>">
                                </div>
                                
                                <div class="col-md-1">
                                    <label class="form-label">&nbsp;</label>
                                    <button type="submit" class="btn btn-primary d-block w-100">
                                        <i class="ri-search-line"></i>
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Manifests Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="manifest-card">
                                <div class="card-header bg-transparent border-bottom">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-file-list-3-line me-2"></i>Manifests List
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover" id="manifestsTable">
                                            <thead>
                                                <tr>
                                                    <th>Manifest #</th>
                                                    <th>Type</th>
                                                    <th>Route</th>
                                                    <th>Departure</th>
                                                    <th>Status</th>
                                                    <th>Shipments</th>
                                                    <th>Weight</th>
                                                    <th>Transport</th>
                                                    <th>Created By</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($manifest = $manifests_result->fetch_assoc()): ?>
                                                <?php
                                                    $is_urgent = ($manifest['days_until_departure'] >= 0 && $manifest['days_until_departure'] <= 1 && $manifest['status'] == 'CONFIRMED');
                                                ?>
                                                <tr>
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <strong><?php echo $manifest['manifest_number']; ?></strong>
                                                            <?php if ($is_urgent): ?>
                                                            <span class="urgent-indicator ms-2">URGENT</span>
                                                            <?php endif; ?>
                                                        </div>
                                                        <small class="text-muted"><?php echo date('M j, Y', strtotime($manifest['created_at'])); ?></small>
                                                    </td>
                                                    <td>
                                                        <span class="type-badge type-<?php echo strtolower($manifest['manifest_type']); ?>">
                                                            <i class="ri-<?php 
                                                                echo $manifest['manifest_type'] == 'TRUCK' ? 'truck' : 
                                                                    ($manifest['manifest_type'] == 'FLIGHT' ? 'flight-takeoff' : 
                                                                    ($manifest['manifest_type'] == 'CONTAINER' ? 'archive' : 'ship'));
                                                            ?>-line me-1"></i>
                                                            <?php echo ucfirst(strtolower($manifest['manifest_type'])); ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <div class="route-indicator">
                                                            <div>
                                                                <div class="fw-bold"><?php echo $manifest['origin_warehouse']; ?></div>
                                                                <small class="text-muted"><?php echo $manifest['origin_city']; ?></small>
                                                            </div>
                                                            <span class="route-arrow">→</span>
                                                            <div>
                                                                <div class="fw-bold"><?php echo $manifest['destination_warehouse']; ?></div>
                                                                <small class="text-muted"><?php echo $manifest['destination_city']; ?></small>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div><?php echo date('M j, Y', strtotime($manifest['departure_date'])); ?></div>
                                                        <small class="text-muted"><?php echo date('H:i', strtotime($manifest['departure_date'])); ?></small>
                                                        <?php if ($manifest['days_until_departure'] >= 0): ?>
                                                        <div class="mt-1">
                                                            <span class="badge bg-soft-info text-info">
                                                                <?php echo $manifest['days_until_departure'] == 0 ? 'Today' : 'In ' . $manifest['days_until_departure'] . ' day(s)'; ?>
                                                            </span>
                                                        </div>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <select class="form-select form-select-sm status-badge status-<?php echo strtolower($manifest['status']); ?>" 
                                                                onchange="updateManifestStatus(<?php echo $manifest['manifest_id']; ?>, this.value)" 
                                                                style="border: none; background: transparent; font-weight: 600; width: auto;">
                                                            <option value="DRAFT" <?php echo $manifest['status'] == 'DRAFT' ? 'selected' : ''; ?>>Draft</option>
                                                            <option value="CONFIRMED" <?php echo $manifest['status'] == 'CONFIRMED' ? 'selected' : ''; ?>>Confirmed</option>
                                                            <option value="DEPARTED" <?php echo $manifest['status'] == 'DEPARTED' ? 'selected' : ''; ?>>Departed</option>
                                                            <option value="ARRIVED" <?php echo $manifest['status'] == 'ARRIVED' ? 'selected' : ''; ?>>Arrived</option>
                                                            <option value="CLOSED" <?php echo $manifest['status'] == 'CLOSED' ? 'selected' : ''; ?>>Closed</option>
                                                        </select>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-primary"><?php echo $manifest['shipment_count']; ?> shipments</span>
                                                        <div class="mt-1">
                                                            <small class="text-muted"><?php echo number_format($manifest['total_pieces']); ?> pieces</small>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <span class="weight-display">
                                                            <?php echo number_format($manifest['total_weight'], 1); ?>kg
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <?php if ($manifest['vehicle_number']): ?>
                                                        <div><i class="ri-truck-line me-1"></i><?php echo $manifest['vehicle_number']; ?></div>
                                                        <?php endif; ?>
                                                        <?php if ($manifest['flight_number']): ?>
                                                        <div><i class="ri-flight-takeoff-line me-1"></i><?php echo $manifest['flight_number']; ?></div>
                                                        <?php endif; ?>
                                                        <?php if ($manifest['container_number']): ?>
                                                        <div><i class="ri-archive-line me-1"></i><?php echo $manifest['container_number']; ?></div>
                                                        <?php endif; ?>
                                                        <?php if ($manifest['driver_name']): ?>
                                                        <div class="mt-1"><small class="text-muted"><i class="ri-user-line me-1"></i><?php echo $manifest['driver_name']; ?></small></div>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <div class="fw-bold"><?php echo $manifest['created_by_name']; ?></div>
                                                        <small class="text-muted"><?php echo date('M j, H:i', strtotime($manifest['created_at'])); ?></small>
                                                    </td>
                                                    <td>
                                                        <div class="btn-group" role="group">
                                                            <button class="action-btn btn-view" onclick="viewManifest(<?php echo $manifest['manifest_id']; ?>)" 
                                                                    title="View Manifest">
                                                                <i class="ri-eye-line"></i>
                                                            </button>
                                                            <?php if ($manifest['status'] == 'DRAFT'): ?>
                                                            <button class="action-btn btn-edit" onclick="editManifest(<?php echo $manifest['manifest_id']; ?>)" 
                                                                    title="Edit Manifest">
                                                                <i class="ri-edit-line"></i>
                                                            </button>
                                                            <button class="action-btn btn-delete" onclick="deleteManifest(<?php echo $manifest['manifest_id']; ?>)" 
                                                                    title="Delete Manifest">
                                                                <i class="ri-delete-bin-line"></i>
                                                            </button>
                                                            <?php endif; ?>
                                                            <button class="action-btn btn-print" onclick="printManifest(<?php echo $manifest['manifest_id']; ?>)" 
                                                                    title="Print Manifest">
                                                                <i class="ri-printer-line"></i>
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </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>
    
    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/responsive.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>
    
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>
    
    <script>
$(document).ready(function() {
    // Initialize DataTable
    $('#manifestsTable').DataTable({
        responsive: true,
        pageLength: 25,
        order: [[0, 'desc']],
        columnDefs: [
            { targets: [6], className: 'text-end' },
            { targets: [4, 5], className: 'text-center' },
            { targets: [9], orderable: false }
        ],
        dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>rt<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>',
        language: {
            search: "_INPUT_",
            searchPlaceholder: "Search manifests...",
            lengthMenu: "Show _MENU_ manifests"
        }
    });

    // Store original values for status selects
    $('.status-badge').each(function() {
        $(this).attr('data-original-value', $(this).val());
    });
});

function updateManifestStatus(manifestId, newStatus) {
    const originalSelect = event.target;
    const originalValue = originalSelect.getAttribute('data-original-value') || originalSelect.value;
    
    if (newStatus === originalValue) return;
    
    Swal.fire({
        title: 'Update Manifest Status',
        text: `Change manifest status to ${newStatus.toLowerCase()}?`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, Update',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#667eea',
        cancelButtonColor: '#6b7280'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: 'manifests.php',
                method: 'POST',
                data: {
                    action: 'update_status',
                    manifest_id: manifestId,
                    status: newStatus
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        originalSelect.setAttribute('data-original-value', newStatus);
                        originalSelect.className = `form-select form-select-sm status-badge status-${newStatus.toLowerCase()}`;
                        
                        Swal.fire({
                            title: 'Success',
                            text: response.message,
                            icon: 'success',
                            timer: 2000,
                            showConfirmButton: false
                        }).then(() => {
                            // Reload page to update summary cards
                            location.reload();
                        });
                    } else {
                        originalSelect.value = originalValue;
                        Swal.fire({
                            title: 'Error',
                            text: response.message,
                            icon: 'error',
                            confirmButtonColor: '#667eea'
                        });
                    }
                },
                error: function() {
                    originalSelect.value = originalValue;
                    Swal.fire({
                        title: 'Error',
                        text: 'An error occurred while updating the status.',
                        icon: 'error',
                        confirmButtonColor: '#667eea'
                    });
                }
            });
        } else {
            originalSelect.value = originalValue;
        }
    });
}

function viewManifest(manifestId) {
    window.location.href = `view_manifest.php?id=${manifestId}`;
}

function editManifest(manifestId) {
    window.location.href = `edit_manifest.php?id=${manifestId}`;
}

function deleteManifest(manifestId) {
    Swal.fire({
        title: 'Delete Manifest',
        html: '<p>Are you sure you want to delete this manifest?</p><p class="text-danger"><strong>This action cannot be undone.</strong></p><p class="text-muted small">Only DRAFT manifests can be deleted.</p>',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Delete',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#dc3545',
        cancelButtonColor: '#6b7280'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: 'manifests.php',
                method: 'POST',
                data: {
                    action: 'delete_manifest',
                    manifest_id: manifestId
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            title: 'Deleted!',
                            text: response.message,
                            icon: 'success',
                            timer: 2000,
                            showConfirmButton: false
                        }).then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            title: 'Error',
                            text: response.message,
                            icon: 'error',
                            confirmButtonColor: '#667eea'
                        });
                    }
                },
                error: function() {
                    Swal.fire({
                        title: 'Error',
                        text: 'An error occurred while deleting the manifest.',
                        icon: 'error',
                        confirmButtonColor: '#667eea'
                    });
                }
            });
        }
    });
}

function printManifest(manifestId) {
    window.open(`print_manifest.php?id=${manifestId}`, '_blank');
}

function exportManifests() {
    Swal.fire({
        title: 'Export Manifests',
        html: `
            <div class="mb-3">
                <label class="form-label">Export Format:</label>
                <select class="form-select" id="exportFormat">
                    <option value="excel">Excel (.xlsx)</option>
                    <option value="pdf">PDF Report</option>
                    <option value="csv">CSV Data</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">Include:</label>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="includeShipments" checked>
                    <label class="form-check-label" for="includeShipments">Shipment Details</label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="includeDriver" checked>
                    <label class="form-check-label" for="includeDriver">Driver Information</label>
                </div>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Export',
        confirmButtonColor: '#667eea',
        cancelButtonColor: '#6b7280',
        preConfirm: () => {
            return {
                format: document.getElementById('exportFormat').value,
                includeShipments: document.getElementById('includeShipments').checked,
                includeDriver: document.getElementById('includeDriver').checked
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const { format, includeShipments, includeDriver } = result.value;
            
            Swal.fire({
                title: 'Generating Export...',
                html: '<div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div><p class="mt-3">Please wait while we prepare your export.</p>',
                allowOutsideClick: false,
                showConfirmButton: false
            });
            
            setTimeout(() => {
                Swal.close();
                const link = document.createElement('a');
                link.href = `export_manifests.php?format=${format}&shipments=${includeShipments}&driver=${includeDriver}`;
                link.download = `manifests_${new Date().toISOString().split('T')[0]}.${format}`;
                link.click();
                
                Swal.fire({
                    toast: true,
                    position: 'top-end',
                    icon: 'success',
                    title: 'Export started',
                    showConfirmButton: false,
                    timer: 2000
                });
            }, 2000);
        }
    });
}

function printManifests() {
    Swal.fire({
        title: 'Print Manifests',
        html: `
            <p>Select which manifests to print:</p>
            <div class="mb-3">
                <select class="form-select" id="printFilter">
                    <option value="all">All Manifests</option>
                    <option value="draft">Draft Only</option>
                    <option value="confirmed">Confirmed Only</option>
                    <option value="departed">Departed Only</option>
                    <option value="today">Today's Departures</option>
                </select>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Print',
        confirmButtonColor: '#667eea',
        cancelButtonColor: '#6b7280',
        preConfirm: () => {
            return document.getElementById('printFilter').value;
        }
    }).then((result) => {
        if (result.isConfirmed) {
            window.open(`print_manifests.php?filter=${result.value}`, '_blank');
        }
    });
}

// Keyboard shortcuts
document.addEventListener('keydown', function(e) {
    // Ctrl/Cmd + N = New Manifest
    if ((e.ctrlKey || e.metaKey) && e.key === 'n') {
        e.preventDefault();
        window.location.href = 'create_manifest.php';
    }
    
    // Ctrl/Cmd + E = Export
    if ((e.ctrlKey || e.metaKey) && e.key === 'e') {
        e.preventDefault();
        exportManifests();
    }
    
    // Ctrl/Cmd + P = Print
    if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
        e.preventDefault();
        printManifests();
    }
});

// Auto-refresh every 5 minutes for status updates
let autoRefresh = setInterval(function() {
    // Only refresh if user is on the page (not in another tab)
    if (!document.hidden) {
        console.log('Auto-refreshing manifest data...');
        location.reload();
    }
}, 300000); // 5 minutes

// Clear interval when leaving page
window.addEventListener('beforeunload', function() {
    clearInterval(autoRefresh);
});
</script>

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