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

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

// Get user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email, role_id FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['user_role'];
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
    $role_id = $row_user_details['role_id'];
} else {
    // Redirect if user details not found
    header('Location: login.php');
    exit();
}

// Check if the user is admin - redirect to admin dashboard if true
if ($role_id == 1) {
    header('Location: index.php');
    exit();
}

// Process search parameters
$search_term = isset($_GET['search']) ? $conn->real_escape_string($_GET['search']) : '';
$status_filter = isset($_GET['status']) ? $conn->real_escape_string($_GET['status']) : '';
$date_from = isset($_GET['date_from']) ? $conn->real_escape_string($_GET['date_from']) : '';
$date_to = isset($_GET['date_to']) ? $conn->real_escape_string($_GET['date_to']) : '';
$shipment_type = isset($_GET['shipment_type']) ? $conn->real_escape_string($_GET['shipment_type']) : '';

// Pagination parameters
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$items_per_page = isset($_GET['items_per_page']) ? (int)$_GET['items_per_page'] : 10;
$offset = ($page - 1) * $items_per_page;

// Role-based restrictions for dashboard statistics
// Only show data relevant to the user's role

// Dashboard statistics - default values
$today_files = 0;
$active_transit = 0;
$pending_invoices = 0;
$trucks_transit = 0;

// Implement role-based data access
switch ($role_id) {
    case 2: // General Manager - can see all data
        // Today's files
        $today_files_sql = "SELECT COUNT(*) as count FROM files WHERE DATE(created_date) = CURDATE()";
        $today_files_result = $conn->query($today_files_sql);
        $today_files = $today_files_result->fetch_assoc()['count'] ?? 0;

        // Active transit shipments
        $active_transit_sql = "SELECT COUNT(*) as count FROM files WHERE `local/transit` = 2 AND close_file IS NULL";
        $active_transit_result = $conn->query($active_transit_sql);
        $active_transit = $active_transit_result->fetch_assoc()['count'] ?? 0;

        // Pending invoices
        $pending_invoices_sql = "SELECT COUNT(*) as count FROM invoices WHERE status = 'pending'";
        $pending_invoices_result = $conn->query($pending_invoices_sql);
        $pending_invoices = $pending_invoices_result->fetch_assoc()['count'] ?? 0;

        // Trucks in transit
        $trucks_transit_sql = "SELECT COUNT(*) as count FROM truck_details WHERE load_date IS NOT NULL";
        $trucks_transit_result = $conn->query($trucks_transit_sql);
        $trucks_transit = $trucks_transit_result->fetch_assoc()['count'] ?? 0;
        break;
        
    case 3: // Operations
        // Today's files
        $today_files_sql = "SELECT COUNT(*) as count FROM files WHERE DATE(created_date) = CURDATE()";
        $today_files_result = $conn->query($today_files_sql);
        $today_files = $today_files_result->fetch_assoc()['count'] ?? 0;

        // Active transit shipments
        $active_transit_sql = "SELECT COUNT(*) as count FROM files WHERE `local/transit` = 2 AND close_file IS NULL";
        $active_transit_result = $conn->query($active_transit_sql);
        $active_transit = $active_transit_result->fetch_assoc()['count'] ?? 0;

        // Trucks in transit
        $trucks_transit_sql = "SELECT COUNT(*) as count FROM truck_details WHERE load_date IS NOT NULL";
        $trucks_transit_result = $conn->query($trucks_transit_sql);
        $trucks_transit = $trucks_transit_result->fetch_assoc()['count'] ?? 0;
        break;
        
    case 4: // Finance
        // Today's files
        $today_files_sql = "SELECT COUNT(*) as count FROM files WHERE DATE(created_date) = CURDATE()";
        $today_files_result = $conn->query($today_files_sql);
        $today_files = $today_files_result->fetch_assoc()['count'] ?? 0;
        
        // Pending invoices
        $pending_invoices_sql = "SELECT COUNT(*) as count FROM invoices WHERE status = 'pending'";
        $pending_invoices_result = $conn->query($pending_invoices_sql);
        $pending_invoices = $pending_invoices_result->fetch_assoc()['count'] ?? 0;
        
        // Count expenses
        $expenses_sql = "SELECT COUNT(*) as count FROM expenses WHERE status = 'Pending'";
        $expenses_result = $conn->query($expenses_sql);
        $pending_expenses = $expenses_result->fetch_assoc()['count'] ?? 0;
        break;
        
    case 5: // Declaration Officer
        // Today's files
        $today_files_sql = "SELECT COUNT(*) as count FROM files WHERE DATE(created_date) = CURDATE()";
        $today_files_result = $conn->query($today_files_sql);
        $today_files = $today_files_result->fetch_assoc()['count'] ?? 0;

        // Active transit shipments
        $active_transit_sql = "SELECT COUNT(*) as count FROM files WHERE `local/transit` = 2 AND close_file IS NULL";
        $active_transit_result = $conn->query($active_transit_sql);
        $active_transit = $active_transit_result->fetch_assoc()['count'] ?? 0;
        break;
        
    case 6: // Shipping Line Clerk
        // Today's files assigned to them or relevant to shipping
        $today_files_sql = "SELECT COUNT(*) as count FROM files 
                           WHERE DATE(created_date) = CURDATE() 
                           AND EXISTS (SELECT 1 FROM shipping_line WHERE shipping_line.file_no = files.file_number)";
        $today_files_result = $conn->query($today_files_sql);
        $today_files = $today_files_result->fetch_assoc()['count'] ?? 0;
        
        // Container deposits
        $container_deposits_sql = "SELECT COUNT(*) as count FROM container_deposit";
        $container_deposits_result = $conn->query($container_deposits_sql);
        $container_deposits = $container_deposits_result->fetch_assoc()['count'] ?? 0;
        break;
        
    case 7: // Transport Supervisor
        // Trucks in transit
        $trucks_transit_sql = "SELECT COUNT(*) as count FROM truck_details WHERE load_date IS NOT NULL";
        $trucks_transit_result = $conn->query($trucks_transit_sql);
        $trucks_transit = $trucks_transit_result->fetch_assoc()['count'] ?? 0;
        
        // Today's files related to transport
        $today_files_sql = "SELECT COUNT(DISTINCT f.id) as count 
                           FROM files f 
                           JOIN truck_details t ON f.file_number = t.file_no
                           WHERE DATE(f.created_date) = CURDATE()";
        $today_files_result = $conn->query($today_files_sql);
        $today_files = $today_files_result->fetch_assoc()['count'] ?? 0;

        // Trucks assigned today
        $trucks_assigned_sql = "SELECT COUNT(*) as count FROM truck_details WHERE DATE(created_at) = CURDATE()";
        $trucks_assigned_result = $conn->query($trucks_assigned_sql);
        $trucks_assigned = $trucks_assigned_result->fetch_assoc()['count'] ?? 0;
        break;
}

// Build the search condition for files based on user role
$search_condition = "1=1"; // Default condition that's always true

// Add role-based restrictions to the search condition
switch ($role_id) {
    case 6: // Shipping Line Clerk - only see shipping related files
        $search_condition .= " AND EXISTS (SELECT 1 FROM shipping_line WHERE shipping_line.file_no = f.file_number)";
        break;
    case 7: // Transport Supervisor - only see files with truck assignments
        $search_condition .= " AND EXISTS (SELECT 1 FROM truck_details WHERE truck_details.file_no = f.file_number)";
        break;
}

if (!empty($search_term)) {
    $search_condition .= " AND (
        f.file_number LIKE '%$search_term%' OR 
        f.consignee_name LIKE '%$search_term%' OR 
        c.first_name LIKE '%$search_term%' OR 
        c.last_name LIKE '%$search_term%' OR 
        f.destination LIKE '%$search_term%'
    )";
}

if (!empty($status_filter)) {
    if ($status_filter === 'active') {
        $search_condition .= " AND f.close_file IS NULL";
    } elseif ($status_filter === 'closed') {
        $search_condition .= " AND f.close_file IS NOT NULL";
    }
}

if (!empty($date_from)) {
    $search_condition .= " AND f.created_date >= '$date_from 00:00:00'";
}

if (!empty($date_to)) {
    $search_condition .= " AND f.created_date <= '$date_to 23:59:59'";
}

if (!empty($shipment_type)) {
    $search_condition .= " AND f.`local/transit` = '$shipment_type'";
}

// Count total records for pagination
$count_sql = "SELECT COUNT(*) as total FROM files f 
              LEFT JOIN customers c ON f.customer = c.customer_id 
              WHERE $search_condition";
$count_result = $conn->query($count_sql);
$total_records = $count_result->fetch_assoc()['total'];
$total_pages = ceil($total_records / $items_per_page);

// Recent shipments
$recent_files_sql = "SELECT f.*, c.first_name, c.last_name 
                    FROM files f 
                    LEFT JOIN customers c ON f.customer = c.customer_id 
                    WHERE $search_condition
                    ORDER BY f.created_date DESC 
                    LIMIT $offset, $items_per_page";
$recent_files_result = $conn->query($recent_files_sql);

// Recent invoices - with search term if applicable and role-based access
$invoice_search_condition = "1=1";

// Role-based restrictions for invoices
if ($role_id == 4) {
    // Finance role can see all invoices
} elseif ($role_id == 2) {
    // General Manager can see all invoices
} else {
    // Other roles can't see invoices
    $invoice_search_condition = "1=0"; // No results
}

if (!empty($search_term)) {
    $invoice_search_condition .= " AND (
        i.invoice_number LIKE '%$search_term%' OR 
        c.first_name LIKE '%$search_term%' OR 
        c.last_name LIKE '%$search_term%' OR
        i.file_number LIKE '%$search_term%'
    )";
}

$recent_invoices_sql = "SELECT i.*, c.first_name, c.last_name 
                        FROM invoices i 
                        LEFT JOIN customers c ON i.customer_id = c.customer_id 
                        WHERE $invoice_search_condition
                        ORDER BY i.issue_date DESC LIMIT 5";
$recent_invoices_result = $conn->query($recent_invoices_sql);

// Recent truck assignments - with search term if applicable and role-based access
$truck_search_condition = "1=1";

// Role-based restrictions for trucks
if (in_array($role_id, [2, 3, 5, 7])) {
    // These roles can see truck assignments
} else {
    // Other roles can't see truck assignments
    $truck_search_condition = "1=0"; // No results
}

if (!empty($search_term)) {
    $truck_search_condition .= " AND (
        td.file_no LIKE '%$search_term%' OR 
        td.container_code LIKE '%$search_term%' OR 
        td.truck_trailer_no LIKE '%$search_term%' OR
        td.driver_name LIKE '%$search_term%' OR
        f.consignee_name LIKE '%$search_term%'
    )";
}

$recent_trucks_sql = "SELECT td.*, f.file_number, f.consignee_name
                      FROM truck_details td
                      LEFT JOIN files f ON td.file_no = f.file_number
                      WHERE $truck_search_condition
                      ORDER BY td.created_at DESC LIMIT 5";
$recent_trucks_result = $conn->query($recent_trucks_sql);

// Get system name
$system_name_sql = "SELECT setting_value FROM settings WHERE setting_key = 'system_name'";
$system_name_result = $conn->query($system_name_sql);
$system_name = ($system_name_result && $system_name_result->num_rows > 0) ? 
               $system_name_result->fetch_assoc()['setting_value'] : 
               "Royal Freight";

// Function to check if user has access to specific menu
function hasAccess($user_role, $allowed_roles) {
    return in_array($user_role, $allowed_roles);
}

// Function to check if there's an active filter
function hasActiveFilter() {
    return !empty($_GET['search']) || 
           !empty($_GET['status']) || 
           !empty($_GET['date_from']) || 
           !empty($_GET['date_to']) || 
           !empty($_GET['shipment_type']);
}

// Build the pagination URL
function getPaginationUrl($page, $items_per_page = null) {
    $params = $_GET;
    $params['page'] = $page;
    if ($items_per_page !== null) {
        $params['items_per_page'] = $items_per_page;
    }
    return '?' . http_build_query($params);
}

// Get user's unread messages count
$unread_count_sql = "SELECT COUNT(*) as count FROM messages WHERE receiver_id = $user_id AND is_read = 0";
$unread_count_result = $conn->query($unread_count_sql);
$unread_messages = $unread_count_result->fetch_assoc()['count'] ?? 0;

// Get appropriate role name
$role_names = [
    1 => 'Administrator',
    2 => 'General Manager',
    3 => 'Operations',
    4 => 'Finance',
    5 => 'Declaration Officer',
    6 => 'Shipping Line Clerk',
    7 => 'Transport Supervisor'
];
$role_name = $role_names[$role_id] ?? 'User';
?>

<!doctype html>
<html lang="en" data-layout="vertical" data-topbar="light" data-sidebar="dark" data-sidebar-size="lg" data-sidebar-image="none" data-preloader="disable">

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Dashboard')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <style>
        .search-box {
            position: relative;
        }
        
        .search-box .search-icon {
            position: absolute;
            left: 13px;
            top: 50%;
            transform: translateY(-50%);
            color: #878a99;
        }
        
        .search-box .form-control {
            height: 38px;
            padding-left: 40px;
            padding-right: 20px;
            border-radius: 6px;
        }
        
        .advanced-search-toggle {
            cursor: pointer;
            user-select: none;
        }
        
        .dashboard-stat-card {
            transition: all 0.3s ease;
        }
        
        .dashboard-stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .quick-action-card {
            transition: all 0.3s ease;
        }
        
        .quick-action-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .pagination-info {
            font-size: 14px;
            color: #6c757d;
        }
        
        .items-per-page-select {
            width: 80px;
            display: inline-block;
        }
        
        @media (max-width: 767.98px) {
            .dashboard-search-form {
                flex-direction: column;
                gap: 10px;
            }
            
            .dashboard-search-form .search-box {
                width: 100%;
            }
            
            .dashboard-search-form .btn {
                width: 100%;
            }
            
            .pagination-container {
                flex-direction: column;
                align-items: center;
                gap: 15px;
            }
            
            .pagination-info {
                text-align: center;
            }
        }
        
        /* Notification badge */
        .notification-badge {
            position: absolute;
            top: -5px;
            right: -5px;
            padding: 0.25rem 0.5rem;
            border-radius: 50%;
            font-size: 0.75rem;
        }

        /* Status indicators */
        .status-indicator {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 5px;
        }
        
        .status-active {
            background-color: #0ab39c;
        }
        
        .status-pending {
            background-color: #f7b84b;
        }
        
        .status-delivered {
            background-color: #405189;
        }
        
        .status-inactive {
            background-color: #f06548;
        }
        
        .role-badge {
            position: relative;
            top: -2px;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Dashboard</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item active">
                                            Welcome <?php echo htmlspecialchars($full_name); ?>
                                            <span class="badge bg-soft-primary text-primary fs-12 role-badge">
                                                <?php echo htmlspecialchars($role_name); ?>
                                            </span>
                                        </li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Global Search and Filter -->
                    <div class="card mb-4">
                        <div class="card-body">
                            <form action="" method="GET" class="d-flex align-items-center gap-2 dashboard-search-form">
                                <div class="search-box flex-grow-1">
                                    <i class="ri-search-line search-icon"></i>
                                    <input type="text" name="search" class="form-control" placeholder="Search for file number, customer, consignee..." value="<?php echo htmlspecialchars($search_term); ?>">
                                </div>
                                <button type="submit" class="btn btn-primary">
                                    <i class="ri-search-line align-bottom me-1"></i> Search
                                </button>
                                <button type="button" class="btn btn-soft-secondary advanced-search-toggle" data-bs-toggle="collapse" data-bs-target="#advancedSearch">
                                    <i class="ri-filter-3-line align-bottom me-1"></i> Filters
                                </button>
                                <?php if (hasActiveFilter()): ?>
                                <a href="dashboard.php" class="btn btn-soft-danger">
                                    <i class="ri-close-circle-line align-bottom me-1"></i> Clear
                                </a>
                                <?php endif; ?>
                            </form>
                            
                            <div id="advancedSearch" class="collapse mt-3 <?php echo hasActiveFilter() ? 'show' : ''; ?>">
                                <form action="" method="GET" class="row g-3">
                                    <?php if (!empty($search_term)): ?>
                                    <input type="hidden" name="search" value="<?php echo htmlspecialchars($search_term); ?>">
                                    <?php endif; ?>
                                    
                                    <div class="col-md-3">
                                        <label class="form-label">Status</label>
                                        <select name="status" class="form-select">
                                            <option value="">All Status</option>
                                            <option value="active" <?php echo $status_filter === 'active' ? 'selected' : ''; ?>>Active</option>
                                            <option value="closed" <?php echo $status_filter === 'closed' ? 'selected' : ''; ?>>Closed</option>
                                        </select>
                                    </div>
                                    
                                    <div class="col-md-3">
                                        <label class="form-label">From Date</label>
                                        <input type="text" name="date_from" class="form-control datepicker" placeholder="YYYY-MM-DD" value="<?php echo htmlspecialchars($date_from); ?>">
                                    </div>
                                    
                                    <div class="col-md-3">
                                        <label class="form-label">To Date</label>
                                        <input type="text" name="date_to" class="form-control datepicker" placeholder="YYYY-MM-DD" value="<?php echo htmlspecialchars($date_to); ?>">
                                    </div>
                                    
                                    <div class="col-md-3">
                                        <label class="form-label">Shipment Type</label>
                                        <select name="shipment_type" class="form-select">
                                            <option value="">All Types</option>
                                            <option value="1" <?php echo $shipment_type === '1' ? 'selected' : ''; ?>>Local</option>
                                            <option value="2" <?php echo $shipment_type === '2' ? 'selected' : ''; ?>>Transit</option>
                                        </select>
                                    </div>
                                    
                                    <div class="col-12 text-end">
                                        <button type="submit" class="btn btn-primary">Apply Filters</button>
                                        <a href="dashboard.php" class="btn btn-light">Reset</a>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <!-- Performance Metrics Row -->
                    <div class="row">
                        <?php if (in_array($role_id, [2, 3, 4, 5])): ?>
                        <!-- Today's Shipments Card -->
                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate dashboard-stat-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <h6 class="text-muted mb-3">Today's Shipments</h6>
                                            <h2 class="mb-0">
                                                <span class="counter-value" data-target="<?php echo $today_files; ?>">
                                                    <?php echo $today_files; ?>
                                                </span>
                                            </h2>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-primary-subtle text-primary rounded fs-3">
                                                <i class="ri-file-list-3-line"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="animation-effect-6 text-primary opacity-25">
                                    <i class="ri-file-list-3-line"></i>
                                </div>
                                <div class="animation-effect-4 text-primary opacity-25">
                                    <i class="ri-file-list-3-line"></i>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>

                        <?php if (in_array($role_id, [2, 3, 5])): ?>
                        <!-- Active Transit Shipments Card -->
                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate dashboard-stat-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <h6 class="text-muted mb-3">Transit Shipments</h6>
                                            <h2 class="mb-0">
                                                <span class="counter-value" data-target="<?php echo $active_transit; ?>">
                                                    <?php echo $active_transit; ?>
                                                </span>
                                            </h2>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-success-subtle text-success rounded fs-3">
                                                <i class="ri-ship-line"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="animation-effect-6 text-success opacity-25">
                                    <i class="ri-ship-line"></i>
                                </div>
                                <div class="animation-effect-4 text-success opacity-25">
                                    <i class="ri-ship-line"></i>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>

                        <?php if (in_array($role_id, [2, 4])): ?>
                        <!-- Pending Invoices Card -->
                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate dashboard-stat-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <h6 class="text-muted mb-3">Pending Invoices</h6>
                                            <h2 class="mb-0">
                                                <span class="counter-value" data-target="<?php echo $pending_invoices; ?>">
                                                    <?php echo $pending_invoices; ?>
                                                </span>
                                            </h2>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-warning-subtle text-warning rounded fs-3">
                                                <i class="ri-bill-line"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="animation-effect-6 text-warning opacity-25">
                                    <i class="ri-bill-line"></i>
                                </div>
                                <div class="animation-effect-4 text-warning opacity-25">
                                    <i class="ri-bill-line"></i>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>

                        <?php if (in_array($role_id, [2, 3, 7])): ?>
                        <!-- Trucks in Transit Card -->
                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate dashboard-stat-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <h6 class="text-muted mb-3">Trucks in Transit</h6>
                                            <h2 class="mb-0">
                                                <span class="counter-value" data-target="<?php echo $trucks_transit; ?>">
                                                    <?php echo $trucks_transit; ?>
                                                </span>
                                            </h2>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-info-subtle text-info rounded fs-3">
                                                <i class="ri-truck-line"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="animation-effect-6 text-info opacity-25">
                                    <i class="ri-truck-line"></i>
                                </div>
                               <div class="animation-effect-4 text-info opacity-25">
                                    <i class="ri-truck-line"></i>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <?php if ($role_id == 4): ?>
                        <!-- Pending Expenses Card (Finance Only) -->
                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate dashboard-stat-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <h6 class="text-muted mb-3">Pending Expenses</h6>
                                            <h2 class="mb-0">
                                                <span class="counter-value" data-target="<?php echo $pending_expenses; ?>">
                                                    <?php echo $pending_expenses; ?>
                                                </span>
                                            </h2>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-danger-subtle text-danger rounded fs-3">
                                                <i class="ri-money-dollar-circle-line"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="animation-effect-6 text-danger opacity-25">
                                    <i class="ri-money-dollar-circle-line"></i>
                                </div>
                                <div class="animation-effect-4 text-danger opacity-25">
                                    <i class="ri-money-dollar-circle-line"></i>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <?php if ($role_id == 6): ?>
                        <!-- Container Deposits Card (Shipping Line Clerk Only) -->
                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate dashboard-stat-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <h6 class="text-muted mb-3">Container Deposits</h6>
                                            <h2 class="mb-0">
                                                <span class="counter-value" data-target="<?php echo $container_deposits; ?>">
                                                    <?php echo $container_deposits; ?>
                                                </span>
                                            </h2>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-purple-subtle text-purple rounded fs-3">
                                                <i class="ri-box-3-line"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="animation-effect-6 text-purple opacity-25">
                                    <i class="ri-box-3-line"></i>
                                </div>
                                <div class="animation-effect-4 text-purple opacity-25">
                                    <i class="ri-box-3-line"></i>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <?php if ($role_id == 7): ?>
                        <!-- Trucks Assigned Today Card (Transport Supervisor Only) -->
                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate dashboard-stat-card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <h6 class="text-muted mb-3">Trucks Assigned Today</h6>
                                            <h2 class="mb-0">
                                                <span class="counter-value" data-target="<?php echo $trucks_assigned; ?>">
                                                    <?php echo $trucks_assigned; ?>
                                                </span>
                                            </h2>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-secondary-subtle text-secondary rounded fs-3">
                                                <i class="ri-road-map-line"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="animation-effect-6 text-secondary opacity-25">
                                    <i class="ri-road-map-line"></i>
                                </div>
                                <div class="animation-effect-4 text-secondary opacity-25">
                                    <i class="ri-road-map-line"></i>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>

                    <!-- Recent Shipments -->
                    <div class="row">
                        <!-- Recent Files -->
                        <div class="col-xl-8">
                            <div class="card">
                                <div class="card-header d-flex align-items-center">
                                    <h5 class="card-title mb-0 flex-grow-1">Recent Shipments<?php if (!empty($search_term)): ?> <span class="text-muted fs-13">- Search: "<?php echo htmlspecialchars($search_term); ?>"</span><?php endif; ?></h5>
                                    <div class="flex-shrink-0">
                                        <div class="dropdown">
                                            <button class="btn btn-soft-secondary btn-sm" type="button" data-bs-toggle="dropdown">
                                                <i class="ri-more-fill align-middle"></i>
                                            </button>
                                            <ul class="dropdown-menu dropdown-menu-end">
                                                <li><a class="dropdown-item" href="file_list.php">View All Shipments</a></li>
                                                <li><a class="dropdown-item" href="file_list.php?status=active">Active Shipments</a></li>
                                                <li><a class="dropdown-item" href="file_list.php?shipment_type=2">Transit Shipments</a></li>
                                                <li><a class="dropdown-item" href="file_list.php?shipment_type=1">Local Shipments</a></li>
                                                <?php if (hasAccess($role_id, [2, 5])): ?>
                                                <li><hr class="dropdown-divider"></li>
                                                <li><a class="dropdown-item" href="file_data.php">Create New Shipment</a></li>
                                                <?php endif; ?>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover table-striped align-middle">
                                            <thead class="table-light">
                                                <tr>
                                                    <th scope="col">File Number</th>
                                                    <th scope="col">Customer</th>
                                                    <th scope="col">Consignee</th>
                                                    <th scope="col">Destination</th>
                                                    <th scope="col">Created Date</th>
                                                    <th scope="col">Type</th>
                                                    <th scope="col">Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($recent_files_result && $recent_files_result->num_rows > 0): ?>
                                                    <?php while($file = $recent_files_result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td>
                                                                <div class="d-flex align-items-center">
                                                                    <div class="status-indicator <?php echo isset($file['close_file']) ? 'status-inactive' : 'status-active'; ?>"></div>
                                                                    <?php echo htmlspecialchars($file['file_number']); ?>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <?php 
                                                                    $customer_name = '';
                                                                    if (!empty($file['first_name'])) {
                                                                        $customer_name = htmlspecialchars($file['first_name'] . ' ' . $file['last_name']);
                                                                    } else {
                                                                        $customer_name = 'N/A';
                                                                    }
                                                                    echo $customer_name;
                                                                ?>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($file['consignee_name'] ?? 'N/A'); ?></td>
                                                            <td>
                                                                <?php if (!empty($file['destination'])): ?>
                                                                    <span class="badge bg-soft-primary text-primary"><?php echo htmlspecialchars($file['destination']); ?></span>
                                                                <?php else: ?>
                                                                    <span class="text-muted">N/A</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <?php 
                                                                    if (!empty($file['created_date'])) {
                                                                        echo date('d M Y', strtotime($file['created_date']));
                                                                    } else {
                                                                        echo 'N/A';
                                                                    }
                                                                ?>
                                                            </td>
                                                            <td>
                                                                <?php 
                                                                    $file_type = isset($file['local/transit']) ? $file['local/transit'] : null;
                                                                    if ($file_type == 1) {
                                                                        echo '<span class="badge bg-success">Local</span>';
                                                                    } elseif ($file_type == 2) {
                                                                        echo '<span class="badge bg-info">Transit</span>';
                                                                    } else {
                                                                        echo '<span class="badge bg-secondary">Unknown</span>';
                                                                    }
                                                                ?>
                                                            </td>
                                                            <td>
                                                                <div class="dropdown">
                                                                    <button class="btn btn-soft-secondary btn-sm dropdown" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                                                        <i class="ri-more-fill align-middle"></i>
                                                                    </button>
                                                                    <ul class="dropdown-menu dropdown-menu-end">
                                                                        <li>
                                                                            <a class="dropdown-item" href="view_file.php?id=<?php echo $file['id']; ?>">
                                                                                <i class="ri-eye-fill align-bottom me-2 text-muted"></i> View
                                                                            </a>
                                                                        </li>
                                                                        <?php if (hasAccess($role_id, [2, 5])): ?>
                                                                        <li>
                                                                            <a class="dropdown-item" href="edit_transit_file.php?id=<?php echo $file['id']; ?>">
                                                                                <i class="ri-pencil-fill align-bottom me-2 text-muted"></i> Edit
                                                                            </a>
                                                                        </li>
                                                                        <?php endif; ?>
                                                                        <li>
                                                                            <a class="dropdown-item" href="digital_data.php?file_number=<?php echo $file['file_number']; ?>">
                                                                                <i class="ri-file-list-line align-bottom me-2 text-muted"></i> Documents
                                                                            </a>
                                                                        </li>
                                                                        <?php if ($file_type == 2 && hasAccess($role_id, [2, 3, 5, 7])): ?>
                                                                        <li>
                                                                            <a class="dropdown-item" href="tracking_data.php?file_number=<?php echo $file['file_number']; ?>">
                                                                                <i class="ri-map-pin-line align-bottom me-2 text-muted"></i> Tracking
                                                                            </a>
                                                                        </li>
                                                                        <?php endif; ?>
                                                                    </ul>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="7" class="text-center">
                                                            <div class="py-4">
                                                                <i class="ri-search-line display-6 text-muted"></i>
                                                                <h5 class="mt-2">No shipments found</h5>
                                                                <p class="text-muted">Try different search terms or clear the filters</p>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <!-- Pagination -->
                                    <?php if ($total_records > 0): ?>
                                    <div class="d-flex justify-content-between align-items-center mt-3 pagination-container">
                                        <div class="pagination-info">
                                            Showing <?php echo min(($page - 1) * $items_per_page + 1, $total_records); ?> to 
                                            <?php echo min($page * $items_per_page, $total_records); ?> of 
                                            <?php echo $total_records; ?> entries
                                        </div>
                                        
                                        <div>
                                            <nav aria-label="Page navigation">
                                                <ul class="pagination mb-0">
                                                    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                                        <a class="page-link" href="<?php echo getPaginationUrl(1); ?>" aria-label="First">
                                                            <i class="ri-arrow-left-double-line"></i>
                                                        </a>
                                                    </li>
                                                    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                                                        <a class="page-link" href="<?php echo getPaginationUrl($page - 1); ?>" aria-label="Previous">
                                                            <i class="ri-arrow-left-s-line"></i>
                                                        </a>
                                                    </li>
                                                    
                                                    <?php 
                                                        $start_page = max(1, min($page - 2, $total_pages - 4));
                                                        $end_page = min($total_pages, max($page + 2, 5));
                                                        
                                                        for ($i = $start_page; $i <= $end_page; $i++):
                                                    ?>
                                                        <li class="page-item <?php echo $page == $i ? 'active' : ''; ?>">
                                                            <a class="page-link" href="<?php echo getPaginationUrl($i); ?>"><?php echo $i; ?></a>
                                                        </li>
                                                    <?php endfor; ?>
                                                    
                                                    <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                                                        <a class="page-link" href="<?php echo getPaginationUrl($page + 1); ?>" aria-label="Next">
                                                            <i class="ri-arrow-right-s-line"></i>
                                                        </a>
                                                    </li>
                                                    <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                                                        <a class="page-link" href="<?php echo getPaginationUrl($total_pages); ?>" aria-label="Last">
                                                            <i class="ri-arrow-right-double-line"></i>
                                                        </a>
                                                    </li>
                                                </ul>
                                            </nav>
                                        </div>
                                        
                                        <div>
                                            <select class="form-select form-select-sm items-per-page-select" onchange="window.location.href='<?php echo getPaginationUrl(1); ?>&items_per_page=' + this.value">
                                                <option value="10" <?php echo $items_per_page == 10 ? 'selected' : ''; ?>>10</option>
                                                <option value="25" <?php echo $items_per_page == 25 ? 'selected' : ''; ?>>25</option>
                                                <option value="50" <?php echo $items_per_page == 50 ? 'selected' : ''; ?>>50</option>
                                                <option value="100" <?php echo $items_per_page == 100 ? 'selected' : ''; ?>>100</option>
                                            </select>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <!-- Recent Invoices and Notifications -->
                        <div class="col-xl-4">
                            <?php if (in_array($role_id, [2, 4])): // Only Finance and GM can see invoices ?>
                            <div class="card">
                                <div class="card-header d-flex align-items-center">
                                    <h5 class="card-title mb-0 flex-grow-1">Recent Invoices</h5>
                                    <a href="invoices.php" class="btn btn-primary btn-sm">
                                        <i class="ri-eye-line align-middle me-1"></i> View All
                                    </a>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover">
                                            <thead class="table-light">
                                                <tr>
                                                    <th scope="col">Invoice #</th>
                                                    <th scope="col">Amount</th>
                                                    <th scope="col">Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($recent_invoices_result && $recent_invoices_result->num_rows > 0): ?>
                                                    <?php while($invoice = $recent_invoices_result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td>
                                                                <a href="view_invoice.php?id=<?php echo $invoice['invoice_id']; ?>" class="fw-medium text-primary">
                                                                    <?php echo htmlspecialchars($invoice['invoice_number']); ?>
                                                                </a>
                                                            </td>
                                                            <td>
                                                                <?php echo '$' . number_format($invoice['total_amount'], 2); ?>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-<?php
                                                                switch($invoice['status']) {
                                                                    case 'paid':
                                                                        echo 'success';
                                                                        break;
                                                                    case 'pending':
                                                                        echo 'warning';
                                                                        break;
                                                                    case 'cancelled':
                                                                        echo 'danger';
                                                                        break;
                                                                    default:
                                                                        echo 'secondary';
                                                                }
                                                                ?>">
                                                                    <?php echo ucfirst($invoice['status']); ?>
                                                                </span>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="3" class="text-center">No recent invoices found</td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <!-- Unread Messages Panel -->
                            <div class="card">
                                <div class="card-header d-flex align-items-center">
                                    <h5 class="card-title mb-0 flex-grow-1">Recent Messages</h5>
                                    <a href="chat.php" class="btn btn-primary btn-sm position-relative">
                                        <i class="ri-message-2-line align-middle me-1"></i> Messages
                                        <?php if ($unread_messages > 0): ?>
                                        <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
                                            <?php echo $unread_messages; ?>
                                        </span>
                                        <?php endif; ?>
                                    </a>
                                </div>
                                <div class="card-body p-0">
                                    <div class="list-group list-group-flush">
                                        <?php 
                                        // Fetch recent messages
                                        $messages_sql = "SELECT m.*, u.full_name as sender_name 
                                                       FROM messages m 
                                                       JOIN users u ON m.sender_id = u.user_id 
                                                       WHERE m.receiver_id = $user_id 
                                                       ORDER BY m.created_at DESC LIMIT 5";
                                        $messages_result = $conn->query($messages_sql);
                                        
                                        if ($messages_result && $messages_result->num_rows > 0):
                                            while($message = $messages_result->fetch_assoc()):
                                        ?>
                                        <a href="chat.php?user=<?php echo $message['sender_id']; ?>" class="list-group-item list-group-item-action">
                                            <div class="d-flex align-items-center">
                                                <div class="flex-shrink-0 me-3">
                                                    <div class="avatar-xs">
                                                        <span class="avatar-title rounded-circle bg-soft-primary text-primary">
                                                            <?php echo strtoupper(substr($message['sender_name'], 0, 1)); ?>
                                                        </span>
                                                    </div>
                                                </div>
                                                <div class="flex-grow-1 overflow-hidden">
                                                    <h6 class="mb-1 text-truncate"><?php echo htmlspecialchars($message['sender_name']); ?></h6>
                                                    <p class="mb-0 text-truncate text-muted">
                                                        <?php 
                                                        $msg_preview = $message['is_file'] ? 
                                                            'Sent you a file' : 
                                                            htmlspecialchars(substr($message['message'], 0, 40) . (strlen($message['message']) > 40 ? '...' : ''));
                                                        echo $msg_preview;
                                                        ?>
                                                    </p>
                                                </div>
                                                <div class="flex-shrink-0 ms-2">
                                                    <div class="fs-11 text-muted">
                                                        <?php 
                                                            $msg_date = new DateTime($message['created_at']);
                                                            $now = new DateTime();
                                                            $interval = $now->diff($msg_date);
                                                            
                                                            if ($interval->d == 0) {
                                                                echo date('H:i', strtotime($message['created_at']));
                                                            } else if ($interval->d == 1) {
                                                                echo 'Yesterday';
                                                            } else {
                                                                echo date('M d', strtotime($message['created_at']));
                                                            }
                                                        ?>
                                                    </div>
                                                    <?php if (!$message['is_read']): ?>
                                                    <span class="badge bg-soft-primary rounded-circle">•</span>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </a>
                                        <?php 
                                            endwhile;
                                        else: 
                                        ?>
                                        <div class="text-center p-3">
                                            <i class="ri-message-2-line d-block fs-24 text-muted mb-2"></i>
                                            <h6 class="mb-1 text-muted">No messages yet</h6>
                                            <p class="small text-muted">Check your internal messages here</p>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Recent Notifications -->
                            <div class="card">
                                <div class="card-header d-flex align-items-center">
                                    <h5 class="card-title mb-0 flex-grow-1">Recent Notifications</h5>
                                </div>
                                <div class="card-body p-0">
                                    <div class="list-group list-group-flush">
                                        <?php 
                                        // Role-based notification filters
                                        $notification_condition = "1=1";
                                        if ($role_id == 6) { // Shipping Line
                                            $notification_condition .= " AND EXISTS (SELECT 1 FROM shipping_line WHERE shipping_line.file_no = f.file_number)"; 
                                        } elseif ($role_id == 7) { // Transport
                                            $notification_condition .= " AND EXISTS (SELECT 1 FROM truck_details WHERE truck_details.file_no = f.file_number)";
                                        }
                                        
                                        // Fetch recent notifications
                                        $notifications_sql = "SELECT n.*, f.file_number 
                                                            FROM notifications n 
                                                            LEFT JOIN files f ON n.file_id = f.id 
                                                            WHERE $notification_condition
                                                            ORDER BY n.created_at DESC LIMIT 5";
                                        $notifications_result = $conn->query($notifications_sql);
                                        
                                        if ($notifications_result && $notifications_result->num_rows > 0):
                                            while($notification = $notifications_result->fetch_assoc()):
                                        ?>
                                        <a href="view_file.php?file_number=<?php echo $notification['file_number']; ?>" class="list-group-item list-group-item-action">
                                            <div class="d-flex align-items-center">
                                                <div class="flex-shrink-0 me-3">
                                                    <div class="avatar-xs">
                                                        <span class="avatar-title rounded-circle bg-soft-primary text-primary">
                                                            <i class="ri-notification-3-line"></i>
                                                        </span>
                                                    </div>
                                                </div>
                                                <div class="flex-grow-1">
                                                    <h6 class="mb-1"><?php echo htmlspecialchars($notification['notif_message']); ?></h6>
                                                    <small class="text-muted">
                                                        <?php 
                                                            $notif_date = new DateTime($notification['created_at']);
                                                            $now = new DateTime();
                                                            $interval = $now->diff($notif_date);
                                                            
                                                            if ($interval->y > 0) {
                                                                echo $interval->y . ' year' . ($interval->y > 1 ? 's' : '') . ' ago';
                                                            } elseif ($interval->m > 0) {
                                                                echo $interval->m . ' month' . ($interval->m > 1 ? 's' : '') . ' ago';
                                                            } elseif ($interval->d > 0) {
                                                                echo $interval->d . ' day' . ($interval->d > 1 ? 's' : '') . ' ago';
                                                            } elseif ($interval->h > 0) {
                                                                echo $interval->h . ' hour' . ($interval->h > 1 ? 's' : '') . ' ago';
                                                            } elseif ($interval->i > 0) {
                                                                echo $interval->i . ' minute' . ($interval->i > 1 ? 's' : '') . ' ago';
                                                            } else {
                                                                echo 'Just now';
                                                            }
                                                        ?>
                                                    </small>
                                                </div>
                                                <?php if (!$notification['is_read']): ?>
                                                <div class="flex-shrink-0">
                                                    <span class="badge badge-soft-primary rounded-pill">New</span>
                                                </div>
                                                <?php endif; ?>
                                            </div>
                                        </a>
                                        <?php 
                                            endwhile;
                                        else: 
                                        ?>
                                        <div class="text-center p-3">
                                            <i class="ri-notification-off-line d-block fs-24 text-muted mb-2"></i>
                                            <h6 class="mb-1 text-muted">No notifications yet</h6>
                                            <p class="small text-muted">You'll see important updates here</p>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Truck Assignments -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header d-flex align-items-center">
                                    <h5 class="card-title mb-0 flex-grow-1">Recent Truck Assignments</h5>
                                    <a href="truck_list.php" class="btn btn-primary btn-sm">
                                        <i class="ri-eye-line align-middle me-1"></i> View All
                                    </a>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover table-striped align-middle">
                                            <thead class="table-light">
                                                <tr>
                                                    <th scope="col">File Number</th>
                                                    <th scope="col">Container</th>
                                                    <th scope="col">Truck/Trailer</th>
                                                    <th scope="col">Driver</th>
                                                    <th scope="col">Phone Number</th>
                                                    <th scope="col">Load Date</th>
                                                    <th scope="col">Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($recent_trucks_result && $recent_trucks_result->num_rows > 0): ?>
                                                    <?php while($truck = $recent_trucks_result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td>
                                                                <a href="view_file.php?file_number=<?php echo $truck['file_no']; ?>" class="fw-medium text-primary">
                                                                    <?php echo htmlspecialchars($truck['file_no']); ?>
                                                                </a>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-dark">
                                                                    <?php echo htmlspecialchars($truck['container_code']); ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($truck['truck_trailer_no'] ?? 'N/A'); ?></td>
                                                            <td>
                                                                <div class="d-flex align-items-center gap-2">
                                                                    <div class="avatar-xs flex-shrink-0">
                                                                        <div class="avatar-title bg-light text-primary rounded-circle">
                                                                            <i class="ri-user-line"></i>
                                                                        </div>
                                                                    </div>
                                                                    <div class="flex-grow-1">
                                                                        <?php echo htmlspecialchars($truck['driver_name'] ?? 'N/A'); ?>
                                                                    </div>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <?php if (!empty($truck['driver_phone_number'])): ?>
                                                                    <a href="tel:<?php echo $truck['driver_phone_number']; ?>" class="text-body">
                                                                        <?php echo htmlspecialchars($truck['driver_phone_number']); ?>
                                                                    </a>
                                                                <?php else: ?>
                                                                    <span class="text-muted">N/A</span>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <?php 
                                                                    if (!empty($truck['load_date'])) {
                                                                        echo date('d M Y', strtotime($truck['load_date']));
                                                                    } else {
                                                                        echo '<span class="text-muted">Not loaded</span>';
                                                                    }
                                                                ?>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                    if (!empty($truck['delivery_date'])) {
                                                                        echo '<span class="badge bg-success">Delivered</span>';
                                                                    } elseif (!empty($truck['border_crossing_date'])) {
                                                                        echo '<span class="badge bg-info">Border Crossed</span>';
                                                                    } elseif (!empty($truck['truck_at_border_date'])) {
                                                                        echo '<span class="badge bg-info">At Border</span>';
                                                                    } elseif (!empty($truck['truck_exit_date'])) {
                                                                        echo '<span class="badge bg-warning">In Transit</span>';
                                                                    } elseif (!empty($truck['load_date'])) {
                                                                        echo '<span class="badge bg-primary">Loaded</span>';
                                                                    } else {
                                                                        echo '<span class="badge bg-secondary">Pending</span>';
                                                                    }
                                                                ?>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="7" class="text-center">
                                                            <div class="py-4">
                                                                <i class="ri-truck-line display-6 text-muted"></i>
                                                                <h5 class="mt-2">No truck assignments found</h5>
                                                                <p class="text-muted">No recent truck assignments are available</p>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Quick Actions Row -->
                    

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/apexcharts/apexcharts.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <script src="assets/js/app.js"></script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize date pickers
            flatpickr(".datepicker", {
                dateFormat: "Y-m-d",
                allowInput: true
            });
            
            // Initialize tooltips
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
            var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl)
            });
            
            // Success message if present
            <?php if(isset($_SESSION['success_message'])): ?>
            Swal.fire({
                title: "Success!",
                text: "<?php echo $_SESSION['success_message']; ?>",
                icon: "success",
                confirmButtonClass: "btn btn-primary w-xs mt-2",
                buttonsStyling: false
            });
            <?php unset($_SESSION['success_message']); endif; ?>
            
            // Error message if present
            <?php if(isset($_SESSION['error_message'])): ?>
            Swal.fire({
                title: "Error!",
                text: "<?php echo $_SESSION['error_message']; ?>",
                icon: "error",
                confirmButtonClass: "btn btn-primary w-xs mt-2",
                buttonsStyling: false
            });
            <?php unset($_SESSION['error_message']); endif; ?>
        });
    </script>
</body>
</html>