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

$manifest_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$manifest_id) {
    header('Location: manifests.php');
    exit();
}

// Fetch manifest details
$sql_manifest = "
    SELECT 
        m.*,
        ow.warehouse_name as origin_warehouse,
        ow.city as origin_city,
        ow.address as origin_address,
        ow.contact_phone as origin_phone,
        dw.warehouse_name as destination_warehouse,
        dw.city as destination_city,
        dw.address as destination_address,
        dw.contact_phone as destination_phone,
        creator.full_name as created_by_name,
        creator.phone as creator_phone,
        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
    WHERE m.manifest_id = ?";

$stmt_manifest = $conn->prepare($sql_manifest);
$stmt_manifest->bind_param("i", $manifest_id);
$stmt_manifest->execute();
$manifest = $stmt_manifest->get_result()->fetch_assoc();

if (!$manifest) {
    header('Location: manifests.php');
    exit();
}

// Fetch manifest shipments
$sql_shipments = "
    SELECT 
        s.*,
        mi.pieces as manifest_pieces,
        mi.weight as manifest_weight,
        mi.added_at,
        ol.location_name as origin_location,
        dl.location_name as destination_location,
        st.service_name,
        c.customer_code,
        c.company_name,
        c.first_name,
        c.last_name
    FROM manifest_items mi
    INNER JOIN shipments s ON mi.shipment_id = s.shipment_id
    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
    LEFT JOIN customers c ON s.sender_customer_id = c.customer_id
    WHERE mi.manifest_id = ?
    ORDER BY mi.added_at ASC";

$stmt_shipments = $conn->prepare($sql_shipments);
$stmt_shipments->bind_param("i", $manifest_id);
$stmt_shipments->execute();
$shipments_result = $stmt_shipments->get_result();

// Get tracking events for this manifest
$sql_events = "
    SELECT 
        te.*,
        u.full_name as event_user
    FROM tracking_events te
    LEFT JOIN users u ON te.created_by = u.user_id
    WHERE te.shipment_id IN (
        SELECT shipment_id FROM manifest_items WHERE manifest_id = ?
    )
    ORDER BY te.event_date DESC
    LIMIT 20";

$stmt_events = $conn->prepare($sql_events);
$stmt_events->bind_param("i", $manifest_id);
$stmt_events->execute();
$events_result = $stmt_events->get_result();

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'View Manifest - ' . $manifest['manifest_number'])); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- 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-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;
            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%);
        }
        
        .card-header {
            padding: 1.25rem 1.5rem;
            border-bottom: 2px solid #f3f4f6;
        }
        
        .card-body {
            padding: 1.5rem;
        }
        
        .status-badge {
            padding: 0.5rem 1rem;
            border-radius: 20px;
            font-size: 0.875rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            display: inline-block;
        }
        
        .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; }
        
        .info-row {
            display: flex;
            justify-content: space-between;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f3f4f6;
        }
        
        .info-row:last-child {
            border-bottom: none;
        }
        
        .info-label {
            color: #6b7280;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .info-value {
            color: #1f2937;
            font-weight: 600;
            text-align: right;
        }
        
        .shipment-item {
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            padding: 1.25rem;
            margin-bottom: 1rem;
            transition: all 0.3s ease;
            background: white;
        }
        
        .shipment-item:hover {
            border-color: #667eea;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
            transform: translateX(4px);
        }
        
        .tracking-badge {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            padding: 0.4rem 0.8rem;
            border-radius: 8px;
            font-size: 0.85rem;
            font-weight: 600;
            text-decoration: none;
            display: inline-block;
            transition: all 0.2s ease;
        }
        
        .tracking-badge:hover {
            transform: scale(1.05);
            color: white;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }
        
        .weight-display {
            background: #e8f5e8;
            color: #2e7d32;
            padding: 0.35rem 0.7rem;
            border-radius: 8px;
            font-size: 0.8rem;
            font-weight: 600;
        }
        
        .route-display {
            display: flex;
            align-items: center;
            gap: 1rem;
            padding: 1rem;
            background: linear-gradient(135deg, #f8faff 0%, #eff6ff 100%);
            border: 2px solid #667eea;
            border-radius: 12px;
            margin: 1rem 0;
        }
        
        .route-location {
            flex: 1;
            text-align: center;
        }
        
        .route-arrow {
            font-size: 2rem;
            color: #667eea;
            font-weight: bold;
        }
        
        .timeline {
            position: relative;
            padding-left: 2rem;
        }
        
        .timeline::before {
            content: '';
            position: absolute;
            left: 0.5rem;
            top: 0;
            bottom: 0;
            width: 2px;
            background: #e5e7eb;
        }
        
        .timeline-item {
            position: relative;
            padding-bottom: 1.5rem;
        }
        
        .timeline-item::before {
            content: '';
            position: absolute;
            left: -1.55rem;
            top: 0.25rem;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: white;
            border: 3px solid #667eea;
        }
        
        .timeline-content {
            background: #f9fafb;
            border-radius: 8px;
            padding: 1rem;
            border-left: 3px solid #667eea;
        }
        
        .action-button {
            padding: 0.75rem 1.5rem;
            border-radius: 10px;
            font-weight: 600;
            transition: all 0.3s ease;
            border: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .btn-primary-gradient {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
        }
        
        .btn-primary-gradient:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
            color: white;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .stat-card {
            background: white;
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            padding: 1.5rem;
            text-align: center;
            transition: all 0.3s ease;
        }
        
        .stat-card:hover {
            border-color: #667eea;
            transform: translateY(-4px);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #667eea;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            color: #6b7280;
            font-size: 0.875rem;
            font-weight: 500;
        }
        
        .urgent-banner {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            color: white;
            padding: 1rem;
            border-radius: 10px;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 1rem;
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.85; }
        }
        
        @media print {
            .no-print {
                display: none !important;
            }
            
            .manifest-card {
                break-inside: avoid;
            }
        }
        
        @media (max-width: 768px) {
            .manifest-header {
                padding: 1.5rem;
            }
            
            .route-display {
                flex-direction: column;
                gap: 0.5rem;
            }
            
            .route-arrow {
                transform: rotate(90deg);
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
        }
    </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 Details
                                </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="manifests.php">Manifests</a></li>
                                        <li class="breadcrumb-item active"><?php echo $manifest['manifest_number']; ?></li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Urgent Banner -->
                    <?php if ($manifest['days_until_departure'] >= 0 && $manifest['days_until_departure'] <= 1 && $manifest['status'] == 'CONFIRMED'): ?>
                    <div class="urgent-banner">
                        <i class="ri-alarm-warning-line" style="font-size: 2rem;"></i>
                        <div>
                            <strong style="font-size: 1.1rem;">Urgent Departure Notice</strong>
                            <p class="mb-0">This manifest is scheduled to depart <?php echo $manifest['days_until_departure'] == 0 ? 'TODAY' : 'TOMORROW'; ?> at <?php echo date('H:i', strtotime($manifest['departure_date'])); ?></p>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Manifest Header -->
                    <div class="manifest-header">
                        <div class="row align-items-center" style="position: relative; z-index: 1;">
                            <div class="col-md-8">
                                <h2 class="mb-2"><?php echo $manifest['manifest_number']; ?></h2>
                                <div class="d-flex flex-wrap gap-3 align-items-center">
                                    <span class="status-badge status-<?php echo strtolower($manifest['status']); ?>">
                                        <?php echo ucfirst(strtolower($manifest['status'])); ?>
                                    </span>
                                    <span style="background: rgba(255,255,255,0.2); padding: 0.5rem 1rem; border-radius: 10px;">
                                        <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>
                                    <span style="background: rgba(255,255,255,0.2); padding: 0.5rem 1rem; border-radius: 10px;">
                                        <i class="ri-calendar-line me-1"></i>
                                        <?php echo date('M j, Y H:i', strtotime($manifest['departure_date'])); ?>
                                    </span>
                                </div>
                            </div>
                            <div class="col-md-4 text-md-end mt-3 mt-md-0">
                                <div class="btn-group no-print" role="group">
                                    <?php if ($manifest['status'] == 'DRAFT'): ?>
                                    <a href="edit_manifest.php?id=<?php echo $manifest_id; ?>" class="btn btn-light">
                                        <i class="ri-edit-line me-1"></i>Edit
                                    </a>
                                    <?php endif; ?>
                                    <button class="btn btn-light" onclick="printManifest()">
                                        <i class="ri-printer-line me-1"></i>Print
                                    </button>
                                    <button class="btn btn-light" onclick="exportManifest()">
                                        <i class="ri-download-line me-1"></i>Export
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Stats Grid -->
                    <div class="stats-grid">
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $shipments_result->num_rows; ?></div>
                            <div class="stat-label">Total Shipments</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo number_format($manifest['total_pieces']); ?></div>
                            <div class="stat-label">Total Pieces</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value"><?php echo number_format($manifest['total_weight'], 1); ?>kg</div>
                            <div class="stat-label">Total Weight</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-value">
                                <?php 
                                if ($manifest['days_until_departure'] < 0) {
                                    echo abs($manifest['days_until_departure']) . ' days ago';
                                } elseif ($manifest['days_until_departure'] == 0) {
                                    echo 'Today';
                                } else {
                                    echo $manifest['days_until_departure'] . ' days';
                                }
                                ?>
                            </div>
                            <div class="stat-label">Departure</div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-xl-8">
                            <!-- Route Information -->
                            <div class="manifest-card">
                                <div class="card-header bg-transparent">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-route-line me-2"></i>Route Information
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="route-display">
                                        <div class="route-location">
                                            <div style="font-size: 0.75rem; color: #6b7280; margin-bottom: 0.25rem;">ORIGIN</div>
                                            <div style="font-size: 1.25rem; font-weight: 700; color: #1f2937;"><?php echo $manifest['origin_warehouse']; ?></div>
                                            <div style="color: #6b7280;"><?php echo $manifest['origin_city']; ?></div>
                                            <?php if ($manifest['origin_phone']): ?>
                                            <small style="color: #9ca3af;"><i class="ri-phone-line me-1"></i><?php echo $manifest['origin_phone']; ?></small>
                                            <?php endif; ?>
                                        </div>
                                        <div class="route-arrow">→</div>
                                        <div class="route-location">
                                            <div style="font-size: 0.75rem; color: #6b7280; margin-bottom: 0.25rem;">DESTINATION</div>
                                            <div style="font-size: 1.25rem; font-weight: 700; color: #1f2937;"><?php echo $manifest['destination_warehouse']; ?></div>
                                            <div style="color: #6b7280;"><?php echo $manifest['destination_city']; ?></div>
                                            <?php if ($manifest['destination_phone']): ?>
                                            <small style="color: #9ca3af;"><i class="ri-phone-line me-1"></i><?php echo $manifest['destination_phone']; ?></small>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Transport Details -->
                            <div class="manifest-card">
                                <div class="card-header bg-transparent">
                                    <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">
                                        <?php if ($manifest['vehicle_number']): ?>
                                        <div class="col-md-6">
                                            <div class="info-row">
                                                <span class="info-label">
                                                    <i class="ri-truck-line"></i>Vehicle Number
                                                </span>
                                                <span class="info-value"><?php echo $manifest['vehicle_number']; ?></span>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($manifest['flight_number']): ?>
                                        <div class="col-md-6">
                                            <div class="info-row">
                                                <span class="info-label">
                                                    <i class="ri-flight-takeoff-line"></i>Flight Number
                                                </span>
                                                <span class="info-value"><?php echo $manifest['flight_number']; ?></span>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($manifest['container_number']): ?>
                                        <div class="col-md-6">
                                            <div class="info-row">
                                                <span class="info-label">
                                                    <i class="ri-archive-line"></i>Container Number
                                                </span>
                                                <span class="info-value"><?php echo $manifest['container_number']; ?></span>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($manifest['driver_name']): ?>
                                        <div class="col-12">
                                            <div style="background: linear-gradient(135deg, #d1ecf1 0%, #bee5eb 100%); border: 2px solid #17a2b8; border-radius: 12px; padding: 1rem; margin-top: 1rem;">
                                                <h6 style="color: #0c5460; margin-bottom: 0.75rem;">
                                                    <i class="ri-user-line me-2"></i>Driver Information
                                                </h6>
                                                <div class="row">
                                                    <div class="col-md-4">
                                                        <div class="info-row">
                                                            <span class="info-label">Name</span>
                                                            <span class="info-value"><?php echo $manifest['driver_name']; ?></span>
                                                        </div>
                                                    </div>
                                                    <?php if ($manifest['driver_phone']): ?>
                                                    <div class="col-md-4">
                                                        <div class="info-row">
                                                            <span class="info-label">Phone</span>
                                                            <span class="info-value"><?php echo $manifest['driver_phone']; ?></span>
                                                        </div>
                                                    </div>
                                                    <?php endif; ?>
                                                    <?php if ($manifest['driver_license']): ?>
                                                    <div class="col-md-4">
                                                        <div class="info-row">
                                                            <span class="info-label">License</span>
                                                            <span class="info-value"><?php echo $manifest['driver_license']; ?></span>
                                                        </div>
                                                    </div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <?php if ($manifest['remarks']): ?>
                                    <div class="mt-3 p-3" style="background: #fffbeb; border-left: 4px solid #f59e0b; border-radius: 8px;">
                                        <strong style="color: #92400e;"><i class="ri-information-line me-1"></i>Remarks:</strong>
                                        <p class="mb-0 mt-2" style="color: #78350f;"><?php echo nl2br(htmlspecialchars($manifest['remarks'])); ?></p>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Shipments List -->
                            <div class="manifest-card">
                                <div class="card-header bg-transparent">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <h5 class="card-title mb-0">
                                            <i class="ri-package-line me-2"></i>Shipments (<?php echo $shipments_result->num_rows; ?>)
                                        </h5>
                                        <button class="btn btn-sm btn-outline-primary no-print" onclick="toggleAllShipments()">
                                            <i class="ri-eye-line me-1"></i>Expand All
                                        </button>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <?php 
                                    $shipments_result->data_seek(0);
                                    while ($shipment = $shipments_result->fetch_assoc()): 
                                    ?>
                                    <div class="shipment-item">
                                        <div class="d-flex justify-content-between align-items-start mb-2">
                                            <div>
                                                <a href="view_shipment.php?tracking=<?php echo $shipment['tracking_number']; ?>" 
                                                   class="tracking-badge">
                                                    <?php echo $shipment['tracking_number']; ?>
                                                </a>
                                                <div class="mt-2">
                                                    <small class="text-muted"><?php echo $shipment['service_name']; ?></small>
                                                </div>
                                            </div>
                                            <div class="text-end">
                                                <span class="weight-display">
                                                    <?php echo number_format($shipment['manifest_weight'], 1); ?>kg
                                                </span>
                                                <div class="mt-2">
                                                    <small class="text-muted"><?php echo $shipment['manifest_pieces']; ?> piece(s)</small>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="row mt-3">
                                            <div class="col-md-6">
                                                <div style="background: #f9fafb; padding: 0.75rem; border-radius: 8px; margin-bottom: 0.5rem;">
                                                    <div style="font-size: 0.75rem; color: #6b7280; margin-bottom: 0.25rem;">SENDER</div>
                                                    <div style="font-weight: 600; color: #1f2937;"><?php echo $shipment['sender_name']; ?></div>
                                                    <small style="color: #6b7280;"><?php echo $shipment['sender_city']; ?>, <?php echo $shipment['sender_country']; ?></small>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div style="background: #f9fafb; padding: 0.75rem; border-radius: 8px; margin-bottom: 0.5rem;">
                                                    <div style="font-size: 0.75rem; color: #6b7280; margin-bottom: 0.25rem;">RECEIVER</div>
                                                    <div style="font-weight: 600; color: #1f2937;"><?php echo $shipment['receiver_name']; ?></div>
                                                    <small style="color: #6b7280;"><?php echo $shipment['receiver_city']; ?>, <?php echo $shipment['receiver_country']; ?></small>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="mt-2">
                                            <small style="color: #6b7280;">
                                                <i class="ri-file-text-line me-1"></i><?php echo $shipment['content_description']; ?>
                                            </small>
                                        </div>
                                        
                                        <div class="mt-2 d-flex justify-content-between align-items-center">
                                            <small style="color: #6b7280;">
                                                <i class="ri-calendar-line me-1"></i>Added: <?php echo date('M j, Y H:i', strtotime($shipment['added_at'])); ?>
                                            </small>
                                            <span class="badge" style="background: <?php 
                                                echo $shipment['status'] == 'DELIVERED' ? '#d1e7dd' : 
                                                    ($shipment['status'] == 'IN_TRANSIT' ? '#fff3cd' : '#e3f2fd'); 
                                            ?>; color: <?php 
                                                echo $shipment['status'] == 'DELIVERED' ? '#0a3622' : 
                                                    ($shipment['status'] == 'IN_TRANSIT' ? '#664d03' : '#1976d2'); 
                                            ?>;">
                                                <?php echo ucfirst(strtolower(str_replace('_', ' ', $shipment['status']))); ?>
                                            </span>
                                        </div>
                                    </div>
                                    <?php endwhile; ?>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-4">
                            <!-- Manifest Details -->
                            <div class="manifest-card">
                                <div class="card-header bg-transparent">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-information-line me-2"></i>Manifest Details
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="info-row">
                                        <span class="info-label">
                                            <i class="ri-file-list-line"></i>Manifest Number
                                        </span>
                                        <span class="info-value"><?php echo $manifest['manifest_number']; ?></span>
                                    </div>
                                    
                                    <div class="info-row">
                                        <span class="info-label">
                                            <i class="ri-calendar-line"></i>Created Date
                                        </span>
                                        <span class="info-value"><?php echo date('M j, Y H:i', strtotime($manifest['created_at'])); ?></span>
                                    </div>
                                    
                                    <div class="info-row">
                                        <span class="info-label">
                                            <i class="ri-user-line"></i>Created By
                                        </span>
                                        <span class="info-value"><?php echo $manifest['created_by_name']; ?></span>
                                    </div>
                                    
                                    <div class="info-row">
                                        <span class="info-label">
                                            <i class="ri-time-line"></i>Departure
                                        </span>
                                        <span class="info-value"><?php echo date('M j, Y H:i', strtotime($manifest['departure_date'])); ?></span>
                                    </div>
                                    
                                    <?php if ($manifest['arrival_date']): ?>
                                    <div class="info-row">
                                        <span class="info-label">
                                            <i class="ri-map-pin-line"></i>Arrival
                                        </span>
                                        <span class="info-value"><?php echo date('M j, Y H:i', strtotime($manifest['arrival_date'])); ?></span>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <div class="info-row">
                                        <span class="info-label">
                                            <i class="ri-checkbox-circle-line"></i>Status
                                        </span>
                                        <span class="info-value">
                                            <span class="status-badge status-<?php echo strtolower($manifest['status']); ?>">
                                                <?php echo ucfirst(strtolower($manifest['status'])); ?>
                                            </span>
                                        </span>
                                    </div>
                                </div>
                            </div>

                            <!-- Quick Actions -->
                            <div class="manifest-card no-print">
                                <div class="card-header bg-transparent">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-settings-3-line me-2"></i>Quick Actions
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="d-grid gap-2">
                                        <?php if ($manifest['status'] == 'DRAFT'): ?>
                                        <button class="action-button btn-primary-gradient" onclick="confirmManifest()">
                                            <i class="ri-check-line"></i>Confirm Manifest
                                        </button>
                                        <?php elseif ($manifest['status'] == 'CONFIRMED'): ?>
                                        <button class="action-button btn-primary-gradient" onclick="departManifest()">
                                            <i class="ri-rocket-line"></i>Mark as Departed
                                        </button>
                                        <?php elseif ($manifest['status'] == 'DEPARTED'): ?>
                                        <button class="action-button btn-primary-gradient" onclick="arriveManifest()">
                                            <i class="ri-map-pin-line"></i>Mark as Arrived
                                        </button>
                                        <?php elseif ($manifest['status'] == 'ARRIVED'): ?>
                                        <button class="action-button btn-primary-gradient" onclick="closeManifest()">
                                            <i class="ri-lock-line"></i>Close Manifest
                                        </button>
                                        <?php endif; ?>
                                        
                                        <button class="btn btn-outline-primary" onclick="printManifest()">
                                            <i class="ri-printer-line me-2"></i>Print Manifest
                                        </button>
                                        
                                        <button class="btn btn-outline-info" onclick="exportManifest()">
                                            <i class="ri-download-line me-2"></i>Export to PDF
                                        </button>
                                        
                                        <button class="btn btn-outline-success" onclick="shareManifest()">
                                            <i class="ri-share-line me-2"></i>Share Manifest
                                        </button>
                                        
                                        <?php if ($manifest['status'] == 'DRAFT'): ?>
                                        <button class="btn btn-outline-danger" onclick="deleteManifest()">
                                            <i class="ri-delete-bin-line me-2"></i>Delete Manifest
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Recent Activity -->
                            <div class="manifest-card">
                                <div class="card-header bg-transparent">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-history-line me-2"></i>Recent Activity
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="timeline">
                                        <?php if ($events_result->num_rows > 0): ?>
                                            <?php while ($event = $events_result->fetch_assoc()): ?>
                                            <div class="timeline-item">
                                                <div class="timeline-content">
                                                    <div style="font-weight: 600; color: #1f2937; margin-bottom: 0.25rem;">
                                                        <?php echo ucfirst(strtolower(str_replace('_', ' ', $event['event_status']))); ?>
                                                    </div>
                                                    <div style="font-size: 0.875rem; color: #6b7280; margin-bottom: 0.25rem;">
                                                        <?php echo $event['event_description']; ?>
                                                    </div>
                                                    <?php if ($event['location']): ?>
                                                    <div style="font-size: 0.75rem; color: #9ca3af;">
                                                        <i class="ri-map-pin-line me-1"></i><?php echo $event['location']; ?>
                                                    </div>
                                                    <?php endif; ?>
                                                    <div style="font-size: 0.75rem; color: #9ca3af; margin-top: 0.5rem;">
                                                        <i class="ri-time-line me-1"></i><?php echo date('M j, Y H:i', strtotime($event['event_date'])); ?>
                                                    </div>
                                                </div>
                                            </div>
                                            <?php endwhile; ?>
                                        <?php else: ?>
                                        <div class="text-center py-4">
                                            <i class="ri-time-line" style="font-size: 2rem; color: #d1d5db;"></i>
                                            <p class="text-muted mt-2 mb-0">No activity recorded yet</p>
                                        </div>
                                        <?php endif; ?>
                                    </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>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>
    
    <script>
function confirmManifest() {
    Swal.fire({
        title: 'Confirm Manifest',
        html: '<p>Are you sure you want to confirm this manifest?</p><p class="text-muted">Once confirmed, the manifest cannot be edited.</p>',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, Confirm',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#667eea',
        cancelButtonColor: '#6b7280'
    }).then((result) => {
        if (result.isConfirmed) {
            updateManifestStatus('CONFIRMED', 'Manifest confirmed successfully');
        }
    });
}

function departManifest() {
    Swal.fire({
        title: 'Mark as Departed',
        html: `
            <p>Confirm that the manifest has departed?</p>
            <div class="mt-3">
                <label class="form-label">Departure Notes (Optional)</label>
                <textarea class="form-control" id="departureNotes" rows="3" placeholder="Enter any departure notes..."></textarea>
            </div>
        `,
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Mark as Departed',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#667eea',
        cancelButtonColor: '#6b7280',
        preConfirm: () => {
            return {
                notes: document.getElementById('departureNotes').value
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            updateManifestStatus('DEPARTED', 'Manifest marked as departed');
        }
    });
}

function arriveManifest() {
    Swal.fire({
        title: 'Mark as Arrived',
        html: `
            <p>Confirm that the manifest has arrived at destination?</p>
            <div class="mt-3">
                <label class="form-label">Arrival Notes (Optional)</label>
                <textarea class="form-control" id="arrivalNotes" rows="3" placeholder="Enter any arrival notes..."></textarea>
            </div>
        `,
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Mark as Arrived',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#667eea',
        cancelButtonColor: '#6b7280',
        preConfirm: () => {
            return {
                notes: document.getElementById('arrivalNotes').value
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            updateManifestStatus('ARRIVED', 'Manifest marked as arrived');
        }
    });
}

function closeManifest() {
    Swal.fire({
        title: 'Close Manifest',
        html: '<p>Are you sure you want to close this manifest?</p><p class="text-muted">This action will finalize the manifest and no further changes can be made.</p>',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Close',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#667eea',
        cancelButtonColor: '#6b7280'
    }).then((result) => {
        if (result.isConfirmed) {
            updateManifestStatus('CLOSED', 'Manifest closed successfully');
        }
    });
}

function updateManifestStatus(newStatus, successMessage) {
    $.ajax({
        url: 'manifests.php',
        method: 'POST',
        data: {
            action: 'update_status',
            manifest_id: <?php echo $manifest_id; ?>,
            status: newStatus
        },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                Swal.fire({
                    title: 'Success',
                    text: successMessage,
                    icon: 'success',
                    confirmButtonColor: '#667eea'
                }).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 updating the status.',
                icon: 'error',
                confirmButtonColor: '#667eea'
            });
        }
    });
}

function printManifest() {
    window.print();
}

function exportManifest() {
    Swal.fire({
        title: 'Export Manifest',
        html: `
            <div class="mb-3">
                <label class="form-label">Export Format:</label>
                <select class="form-select" id="exportFormat">
                    <option value="pdf">PDF Document</option>
                    <option value="excel">Excel Spreadsheet</option>
                    <option value="csv">CSV Data</option>
                </select>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Export',
        confirmButtonColor: '#667eea',
        cancelButtonColor: '#6b7280',
        preConfirm: () => {
            return document.getElementById('exportFormat').value;
        }
    }).then((result) => {
        if (result.isConfirmed) {
            window.open(`export_manifest.php?id=<?php echo $manifest_id; ?>&format=${result.value}`, '_blank');
            
            Swal.fire({
                toast: true,
                position: 'top-end',
                icon: 'success',
                title: 'Export started',
                showConfirmButton: false,
                timer: 2000
            });
        }
    });
}

function shareManifest() {
    const manifestUrl = window.location.href;
    
    Swal.fire({
        title: 'Share Manifest',
        html: `
            <div class="mb-3">
                <label class="form-label">Share via:</label>
                <div class="d-grid gap-2">
                    <button class="btn btn-primary" onclick="shareViaEmail()">
                        <i class="ri-mail-line me-2"></i>Email
                    </button>
                    <button class="btn btn-success" onclick="shareViaWhatsApp()">
                        <i class="ri-whatsapp-line me-2"></i>WhatsApp
                    </button>
                    <button class="btn btn-info" onclick="copyToClipboard('${manifestUrl}')">
                        <i class="ri-file-copy-line me-2"></i>Copy Link
                    </button>
                </div>
            </div>
        `,
        showConfirmButton: false,
        showCloseButton: true
    });
}

function shareViaEmail() {
    const subject = encodeURIComponent('Manifest <?php echo $manifest['manifest_number']; ?>');
    const body = encodeURIComponent(`Please review the manifest details at: ${window.location.href}`);
    window.location.href = `mailto:?subject=${subject}&body=${body}`;
}

function shareViaWhatsApp() {
    const text = encodeURIComponent(`Manifest <?php echo $manifest['manifest_number']; ?>: ${window.location.href}`);
    window.open(`https://wa.me/?text=${text}`, '_blank');
}

function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        Swal.fire({
            toast: true,
            position: 'top-end',
            icon: 'success',
            title: 'Link copied to clipboard',
            showConfirmButton: false,
            timer: 2000
        });
    });
}

function deleteManifest() {
    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>',
        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: <?php echo $manifest_id; ?>
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            title: 'Deleted!',
                            text: response.message,
                            icon: 'success',
                            confirmButtonColor: '#667eea'
                        }).then(() => {
                            window.location.href = 'manifests.php';
                        });
                    } 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 toggleAllShipments() {
    const button = event.target;
    const isExpanded = button.innerHTML.includes('Collapse');
    
    if (isExpanded) {
        button.innerHTML = '<i class="ri-eye-line me-1"></i>Expand All';
    } else {
        button.innerHTML = '<i class="ri-eye-off-line me-1"></i>Collapse All';
    }
}

// Keyboard shortcuts
document.addEventListener('keydown', function(e) {
    // Ctrl/Cmd + P = Print
    if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
        e.preventDefault();
        printManifest();
    }
    
    // Ctrl/Cmd + E = Export
    if ((e.ctrlKey || e.metaKey) && e.key === 'e') {
        e.preventDefault();
        exportManifest();
    }
});
</script>

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