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

$current_month = date('m');
$current_year = date('Y');

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

// Fetch user details with proper cargo management schema alignment
$user_id = $_SESSION['user_id'];
$sql_user_details = "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_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_data = $stmt_user->get_result()->fetch_assoc();

if ($user_data) {
    $username = $user_data['username'];
    $role_name = $user_data['role_name'];
    $full_name = $user_data['full_name'];
    $email = $user_data['email'];
    $phone_number = $user_data['phone'] ?? null;
    $profile_picture = $user_data['avatar'] ?? null;
}

// Fetch recent shipment activity as notifications
$notifications_query = "SELECT 
    s.shipment_id,
    s.tracking_number,
    s.sender_name,
    s.receiver_name,
    s.status,
    s.total_charges,
    s.booking_date,
    st.service_name,
    'SHIPMENT' as activity_type
FROM shipments s
LEFT JOIN service_types st ON s.service_id = st.service_id
WHERE s.booking_date >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
ORDER BY s.booking_date DESC 
LIMIT 10";

$notifications_result = $conn->query($notifications_query);
$notifications = [];
if ($notifications_result) {
    $notifications = $notifications_result->fetch_all(MYSQLI_ASSOC);
}

// Count pending shipments as unread notifications
$unread_count_query = "SELECT COUNT(*) as count FROM shipments 
                      WHERE status IN ('DRAFT', 'BOOKED') 
                      AND booking_date >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
$unread_result = $conn->query($unread_count_query);
$unread_count = $unread_result ? $unread_result->fetch_assoc()['count'] : 0;

// Get team members (other active users)
$team_query = "SELECT u.user_id, u.full_name, ur.role_name, u.avatar 
              FROM users u 
              LEFT JOIN user_roles ur ON u.role_id = ur.role_id 
              WHERE u.status = 'ACTIVE' AND u.user_id != ? 
              ORDER BY u.full_name
              LIMIT 5";
$stmt_team = $conn->prepare($team_query);
$stmt_team->bind_param("i", $user_id);
$stmt_team->execute();
$team_members = $stmt_team->get_result()->fetch_all(MYSQLI_ASSOC);

// Get quick stats for current user based on role
$quick_stats = [];
if (in_array($role_name, ['Administrator', 'Operations Manager'])) {
    // Get manager's stats
    $manager_stats_query = "SELECT 
        COUNT(DISTINCT s.shipment_id) as total_shipments,
        COUNT(DISTINCT c.customer_id) as total_customers,
        COALESCE(SUM(s.total_charges), 0) as total_revenue,
        COUNT(CASE WHEN DATE(s.booking_date) = CURDATE() THEN 1 END) as today_shipments
        FROM shipments s
        LEFT JOIN customers c ON s.sender_customer_id = c.customer_id
        WHERE s.status != 'CANCELLED'
        AND MONTH(s.booking_date) = MONTH(CURRENT_DATE())
        AND YEAR(s.booking_date) = YEAR(CURRENT_DATE())";
    $manager_result = $conn->query($manager_stats_query);
    $quick_stats = $manager_result->fetch_assoc();
} elseif ($role_name === 'Customer Service') {
    // Get customer service daily stats
    $cs_stats_query = "SELECT 
        COUNT(DISTINCT s.shipment_id) as daily_shipments,
        COUNT(DISTINCT i.invoice_id) as daily_invoices,
        COALESCE(SUM(i.total_amount), 0) as daily_revenue,
        COUNT(CASE WHEN s.status = 'BOOKED' THEN 1 END) as booked_shipments
        FROM shipments s
        LEFT JOIN invoices i ON DATE(i.invoice_date) = CURDATE()
        WHERE DATE(s.booking_date) = CURDATE()";
    $cs_result = $conn->query($cs_stats_query);
    $quick_stats = $cs_result->fetch_assoc();
} elseif ($role_name === 'Warehouse Staff') {
    // Get warehouse stats
    $warehouse_stats_query = "SELECT 
        COUNT(CASE WHEN s.status = 'COLLECTED' THEN 1 END) as collected_shipments,
        COUNT(CASE WHEN s.status = 'IN_TRANSIT' THEN 1 END) as in_transit_shipments,
        COUNT(CASE WHEN s.status = 'OUT_FOR_DELIVERY' THEN 1 END) as out_for_delivery,
        COUNT(CASE WHEN DATE(s.booking_date) = CURDATE() THEN 1 END) as today_shipments
        FROM shipments s
        WHERE s.status NOT IN ('CANCELLED', 'DELIVERED')";
    $warehouse_result = $conn->query($warehouse_stats_query);
    $quick_stats = $warehouse_result->fetch_assoc();
}

// Helper functions for activity formatting
function getActivityColor($status) {
    return match($status) {
        'DELIVERED' => 'success',
        'IN_TRANSIT', 'OUT_FOR_DELIVERY' => 'primary',
        'BOOKED', 'COLLECTED' => 'info',
        'DRAFT' => 'warning',
        'CANCELLED', 'RETURNED' => 'danger',
        default => 'secondary'
    };
}

function getActivityIcon($status) {
    return match($status) {
        'DELIVERED' => 'ph-check-circle',
        'IN_TRANSIT' => 'ph-truck',
        'OUT_FOR_DELIVERY' => 'ph-package',
        'BOOKED' => 'ph-calendar-check',
        'COLLECTED' => 'ph-hand-grabbing',
        'DRAFT' => 'ph-file-dashed',
        'CANCELLED' => 'ph-x-circle',
        'RETURNED' => 'ph-arrow-u-up-left',
        default => 'ph-package'
    };
}

function formatActivityMessage($notification) {
    $sender = $notification['sender_name'];
    $receiver = $notification['receiver_name'];
    $tracking = $notification['tracking_number'];
    $status = $notification['status'];
    
    return match($status) {
        'DELIVERED' => "Shipment {$tracking} delivered to {$receiver}",
        'IN_TRANSIT' => "Shipment {$tracking} is in transit",
        'OUT_FOR_DELIVERY' => "Shipment {$tracking} out for delivery",
        'BOOKED' => "New shipment {$tracking} booked by {$sender}",
        'COLLECTED' => "Shipment {$tracking} collected from {$sender}",
        default => "Shipment {$tracking} status: {$status}"
    };
}

function getTimeAgo($datetime) {
    $time = strtotime($datetime);
    $now = time();
    $diff = $now - $time;
    
    if ($diff < 60) return 'Just now';
    if ($diff < 3600) return floor($diff / 60) . 'm ago';
    if ($diff < 86400) return floor($diff / 3600) . 'h ago';
    if ($diff < 604800) return floor($diff / 86400) . 'd ago';
    return date('M j', $time);
}
?>

<header id="page-topbar">
    <div class="layout-width">
        <div class="navbar-header">
            <div class="d-flex">
                <!-- LOGO -->
                <div class="navbar-brand-box horizontal-logo">
                    <a href="index.php" class="logo logo-dark">
                        <span class="logo-sm">
                            <a href="index.php" class="d-block">
                                <img src="assets/images/polakis.png" alt="Cargo Management System" height="50" class="mb-3">
                            </a>
                        </span>
                    </a>
                </div>

                <button type="button" class="btn btn-sm px-3 fs-16 header-item vertical-menu-btn topnav-hamburger" id="topnav-hamburger-icon">
                    <span class="hamburger-icon">
                        <span></span>
                        <span></span>
                        <span></span>
                    </span>
                </button>

                <!-- Enhanced Search for Cargo Management -->
                <form class="app-search d-none d-md-block" id="search-form">
                    <div class="position-relative">
                        <input type="text" class="form-control search-input" 
                               placeholder="Search shipments, customers, tracking..." 
                               autocomplete="off" id="search-options">
                        <span class="search-widget-icon">
                            <i class="ph-magnifying-glass"></i>
                        </span>
                        <div class="search-loading d-none">
                            <div class="spinner-border spinner-border-sm" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                        </div>
                    </div>

                    <div class="dropdown-menu dropdown-menu-lg search-dropdown" id="search-dropdown">
                        <div data-simplebar style="max-height: 350px;">
                            <!-- Quick Actions -->
                            <div class="dropdown-header bg-light">
                                <h6 class="text-overflow text-muted mb-0 text-uppercase">
                                    <i class="ph-lightning me-1"></i>Quick Actions
                                </h6>
                            </div>

                            <div class="dropdown-item bg-transparent text-wrap p-2">
                                <div class="d-flex flex-wrap gap-1">
                                    <a href="new_shipment.php" class="btn btn-soft-primary btn-sm">
                                        <i class="ph-plus-circle me-1"></i>New Shipment
                                    </a>
                                    <a href="add_customer.php" class="btn btn-soft-success btn-sm">
                                        <i class="ph-user-plus me-1"></i>Add Customer
                                    </a>
                                    <a href="track_shipment.php" class="btn btn-soft-info btn-sm">
                                        <i class="ph-magnifying-glass me-1"></i>Track Shipment
                                    </a>
                                    <a href="create_manifest.php" class="btn btn-soft-warning btn-sm">
                                        <i class="ph-list-checks me-1"></i>Create Manifest
                                    </a>
                                </div>
                            </div>

                            <!-- Cargo Management Modules -->
                            <div class="dropdown-header bg-light">
                                <h6 class="text-overflow text-muted mb-1 text-uppercase">
                                    <i class="ph-truck me-1"></i>Cargo Operations
                                </h6>
                            </div>

                            <a href="shipments.php" class="dropdown-item notify-item">
                                <i class="ph-package align-middle fs-18 text-primary me-2"></i>
                                <span>Shipments</span>
                                <small class="text-muted ms-auto">Ctrl+Shift+S</small>
                            </a>

                            <a href="customers.php" class="dropdown-item notify-item">
                                <i class="ph-users align-middle fs-18 text-success me-2"></i>
                                <span>Customers</span>
                                <small class="text-muted ms-auto">Ctrl+Shift+C</small>
                            </a>

                            <a href="manifests.php" class="dropdown-item notify-item">
                                <i class="ph-list-checks align-middle fs-18 text-info me-2"></i>
                                <span>Manifests</span>
                                <small class="text-muted ms-auto">Ctrl+Shift+M</small>
                            </a>

                            <a href="invoices.php" class="dropdown-item notify-item">
                                <i class="ph-receipt align-middle fs-18 text-warning me-2"></i>
                                <span>Invoices</span>
                                <small class="text-muted ms-auto">Ctrl+Shift+I</small>
                            </a>

                            <a href="reports.php" class="dropdown-item notify-item">
                                <i class="ph-chart-line align-middle fs-18 text-danger me-2"></i>
                                <span>Reports</span>
                                <small class="text-muted ms-auto">Ctrl+Shift+R</small>
                            </a>

                            <!-- Search Results Container -->
                            <div id="search-results-container" style="display: none;">
                                <div class="dropdown-header bg-light">
                                    <h6 class="text-overflow text-muted mb-2 text-uppercase">
                                        <i class="ph-magnifying-glass me-1"></i>Search Results
                                    </h6>
                                </div>
                                <div id="search-results"></div>
                            </div>

                            <!-- Team Members -->
                            <?php if(!empty($team_members)): ?>
                            <div class="dropdown-header bg-light">
                                <h6 class="text-overflow text-muted mb-2 text-uppercase">
                                    <i class="ph-users me-1"></i>Team Members
                                </h6>
                            </div>

                            <div class="notification-list">
                                <?php foreach($team_members as $member): ?>
                                <a href="view_user.php?id=<?php echo $member['user_id']; ?>" class="dropdown-item notify-item py-2">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0 me-2">
                                            <?php if($member['avatar']): ?>
                                                <img src="assets/images/users/<?php echo $member['avatar']; ?>" 
                                                     class="rounded-circle avatar-xs" alt="user-pic">
                                            <?php else: ?>
                                                <div class="avatar-xs">
                                                    <span class="avatar-title bg-soft-primary text-primary rounded-circle">
                                                        <?php echo strtoupper(substr($member['full_name'], 0, 1)); ?>
                                                    </span>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                        <div class="flex-grow-1">
                                            <h6 class="m-0 fs-13"><?php echo htmlspecialchars($member['full_name']); ?></h6>
                                            <span class="fs-11 mb-0 text-muted">
                                                <?php echo htmlspecialchars($member['role_name']); ?>
                                            </span>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-xs">
                                                <span class="avatar-title bg-soft-success text-success rounded-circle">
                                                    <i class="ph-check fs-10"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </a>
                                <?php endforeach; ?>
                            </div>
                            <?php endif; ?>
                        </div>

                        <div class="text-center p-3 border-top">
                            <a href="advanced_search.php" class="btn btn-primary btn-sm w-100">
                                <i class="ph-magnifying-glass me-1"></i>Advanced Search
                            </a>
                        </div>
                    </div>
                </form>
            </div>

            <div class="d-flex align-items-center">
                <!-- Country/Region Flag -->
                <div class="ms-1 header-item d-none d-sm-flex">
                    <img src="assets/images/flags/ke.svg" alt="Kenya Flag" class="me-2 rounded" height="20">
                    <span class="align-middle text-white fw-medium">Kenya</span>
                </div>

                <!-- Shipment Notifications Dropdown -->
                <div class="dropdown topbar-head-dropdown ms-1 header-item" id="notificationDropdown">
                    <button type="button" class="btn btn-icon btn-topbar btn-ghost-secondary rounded-circle" 
                            id="page-header-notifications-dropdown" data-bs-toggle="dropdown" 
                            data-bs-auto-close="outside" aria-haspopup="true" aria-expanded="false">
                        <i class='ph-bell fs-22'></i>
                        <?php if ($unread_count > 0): ?>
                        <span class="position-absolute topbar-badge fs-10 translate-middle badge rounded-pill bg-danger">
                            <?php echo min($unread_count, 99); ?>
                            <span class="visually-hidden">pending shipments</span>
                        </span>
                        <?php endif; ?>
                    </button>
                    
                    <div class="dropdown-menu dropdown-menu-lg dropdown-menu-end p-0" aria-labelledby="page-header-notifications-dropdown">
                        <!-- Header -->
                        <div class="dropdown-head bg-primary bg-pattern rounded-top">
                            <div class="p-3">
                                <div class="row align-items-center">
                                    <div class="col">
                                        <h6 class="m-0 fs-16 fw-semibold text-white">
                                            <i class="ph-bell me-1"></i>Recent Shipments
                                        </h6>
                                    </div>
                                    <div class="col-auto dropdown-tabs">
                                        <span class="badge bg-light-subtle text-body fs-13">
                                            <?php echo $unread_count; ?> Pending
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    
                        <!-- Content -->
                        <div class="tab-content position-relative" id="notificationItemsTabContent">
                            <div class="tab-pane fade show active py-2 ps-2" id="all-noti-tab" role="tabpanel">
                                <div data-simplebar style="max-height: 300px;" class="pe-2">
                                    <?php if(empty($notifications)): ?>
                                        <div class="text-center text-muted p-4">
                                            <i class="ph-bell-slash fs-1 text-muted mb-3 d-block"></i>
                                            <h6 class="mb-1">No recent shipments</h6>
                                            <p class="mb-0 fs-12">When new shipments are created, they'll appear here</p>
                                        </div>
                                    <?php else: ?>
                                        <?php foreach($notifications as $notification): ?>
                                            <div class="text-reset notification-item d-block dropdown-item position-relative">
                                                <div class="d-flex">
                                                    <div class="avatar-xs me-3 flex-shrink-0">
                                                        <span class="avatar-title bg-<?php echo getActivityColor($notification['status']); ?>-subtle text-<?php echo getActivityColor($notification['status']); ?> rounded-circle fs-16">
                                                            <i class="<?php echo getActivityIcon($notification['status']); ?>"></i>
                                                        </span>
                                                    </div>
                                                    <div class="flex-grow-1">
                                                        <h6 class="mt-0 mb-2 lh-base fs-13">
                                                            <?php echo formatActivityMessage($notification); ?>
                                                        </h6>
                                                        <p class="mb-0 fs-11 fw-medium text-uppercase text-muted">
                                                            <span>
                                                                <i class="ph-clock"></i> 
                                                                <?php echo getTimeAgo($notification['booking_date']); ?>
                                                            </span>
                                                        </p>
                                                    </div>
                                                    <div class="px-2 fs-15">
                                                        <div class="avatar-xs">
                                                            <span class="avatar-title bg-light text-muted rounded-circle">
                                                                <i class="ph-dots-three fs-12"></i>
                                                            </span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                                
                                <?php if(!empty($notifications)): ?>
                                <div class="p-2 border-top text-center">
                                    <div class="d-grid">
                                        <a class="btn btn-sm btn-link fw-semibold" href="shipments.php">
                                            View All Shipments <i class="ph-arrow-right align-middle"></i>
                                        </a>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- User Profile Dropdown -->
                <div class="dropdown ms-sm-3 header-item topbar-user">
                    <button type="button" class="btn shadow-none" id="page-header-user-dropdown" 
                            data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        <span class="d-flex align-items-center">
                            <div class="me-2">
                                <?php if($profile_picture): ?>
                                    <img class="rounded-circle header-profile-user" 
                                         src="assets/images/users/<?php echo $profile_picture; ?>" 
                                         alt="Header Avatar">
                                <?php else: ?>
                                    <div class="avatar-xs">
                                        <span class="avatar-title bg-white text-primary rounded-circle">
                                            <?php echo strtoupper(substr($full_name, 0, 1)); ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <span class="text-start ms-xl-2">
                                <span class="d-none d-xl-inline-block ms-1 fw-semibold user-name-text text-white">
                                    <?php echo htmlspecialchars($full_name); ?>
                                </span>
                                <span class="d-none d-xl-block ms-1 fs-13 user-name-sub-text text-white-50">
                                    <?php echo htmlspecialchars($role_name); ?>
                                </span>
                            </span>
                        </span>
                    </button>
                    
                    <div class="dropdown-menu dropdown-menu-end">
                        <!-- User Info Header -->
                        <div class="dropdown-header bg-light">
                            <div class="d-flex align-items-center">
                                <div class="flex-shrink-0 me-2">
                                    <?php if($profile_picture): ?>
                                        <img class="rounded-circle" 
                                             src="assets/images/users/<?php echo $profile_picture; ?>" 
                                             alt="Avatar" width="32" height="32">
                                    <?php else: ?>
                                        <div class="avatar-sm">
                                            <span class="avatar-title bg-primary text-white rounded-circle">
                                                <?php echo strtoupper(substr($full_name, 0, 1)); ?>
                                            </span>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                <div class="flex-grow-1">
                                    <h6 class="mb-0"><?php echo htmlspecialchars($full_name); ?></h6>
                                    <small class="text-muted"><?php echo htmlspecialchars($email); ?></small>
                                    <div class="mt-1">
                                        <span class="badge bg-soft-primary text-primary fs-11">
                                            <?php echo htmlspecialchars($role_name); ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="dropdown-divider"></div>
                        
                        <!-- Main Menu Items based on Role -->
                        <a class="dropdown-item" href="profile.php">
                            <i class="ph-user-circle text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">My Profile</span>
                        </a>
                        
                        <?php if($role_name === 'Administrator'): ?>
                        <a class="dropdown-item" href="system_settings.php">
                            <i class="ph-gear text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">System Settings</span>
                        </a>
                        
                        <a class="dropdown-item" href="users.php">
                            <i class="ph-users-three text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">User Management</span>
                        </a>
                        
                        <a class="dropdown-item" href="backup_restore.php">
                            <i class="ph-database text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Backup & Restore</span>
                        </a>
                        
                        <?php elseif($role_name === 'Operations Manager'): ?>
                        <a class="dropdown-item" href="shipments.php">
                            <i class="ph-package text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">All Shipments</span>
                        </a>
                        
                        <a class="dropdown-item" href="manifests.php">
                            <i class="ph-list-checks text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Manifests</span>
                        </a>
                        
                        <a class="dropdown-item" href="reports.php">
                            <i class="ph-chart-line text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Reports</span>
                        </a>
                        
                        <?php elseif($role_name === 'Customer Service'): ?>
                        <a class="dropdown-item" href="new_shipment.php">
                            <i class="ph-plus-circle text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">New Shipment</span>
                        </a>
                        
                        <a class="dropdown-item" href="track_shipment.php">
                            <i class="ph-magnifying-glass text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Track Shipment</span>
                        </a>
                        
                        <a class="dropdown-item" href="customers.php">
                            <i class="ph-users text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Customers</span>
                        </a>
                        
                        <?php elseif($role_name === 'Warehouse Staff'): ?>
                        <a class="dropdown-item" href="pending_collection.php">
                            <i class="ph-clock text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Pending Collection</span>
                            <?php if(isset($quick_stats['collected_shipments']) && $quick_stats['collected_shipments'] > 0): ?>
                                <span class="badge bg-warning ms-2 fs-11"><?php echo $quick_stats['collected_shipments']; ?></span>
                            <?php endif; ?>
                        </a>
                        
                        <a class="dropdown-item" href="in_transit.php">
                            <i class="ph-truck text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">In Transit</span>
                            <?php if(isset($quick_stats['in_transit_shipments']) && $quick_stats['in_transit_shipments'] > 0): ?>
                                <span class="badge bg-primary ms-2 fs-11"><?php echo $quick_stats['in_transit_shipments']; ?></span>
                            <?php endif; ?>
                        </a>
                        
                        <a class="dropdown-item" href="warehouse_inventory.php">
                            <i class="ph-warehouse text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Warehouse Inventory</span>
                        </a>
                        
                        <?php elseif($role_name === 'Finance Manager'): ?>
                        <a class="dropdown-item" href="invoices.php">
                            <i class="ph-receipt text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Invoices</span>
                        </a>
                        
                        <a class="dropdown-item" href="payments.php">
                            <i class="ph-credit-card text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Payments</span>
                        </a>
                        
                        <a class="dropdown-item" href="financial_reports.php">
                            <i class="ph-chart-bar text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Financial Reports</span>
                        </a>
                        <?php endif; ?>
                        
                        <div class="dropdown-divider"></div>
                        
                        <!-- System Info -->
                        <?php if($phone_number): ?>
                        <div class="dropdown-item-text">
                            <small class="text-muted">
                                <i class="ph-phone text-muted me-1"></i>
                                Phone: <?php echo htmlspecialchars($phone_number); ?>
                            </small>
                        </div>
                        <?php endif; ?>
                        
                        <div class="dropdown-item-text">
                            <small class="text-muted">
                                <i class="ph-clock text-muted me-1"></i>
                                Last Login: <?php echo $user_data['last_login'] ? date('M j, Y g:i A', strtotime($user_data['last_login'])) : 'First time'; ?>
                            </small>
                        </div>
                        
                        <div class="dropdown-divider"></div>
                        
                        <!-- Account Actions -->
                        <a class="dropdown-item" href="change_password.php">
                            <i class="ph-lock text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Change Password</span>
                        </a>
                        
                        <a class="dropdown-item" href="#" onclick="lockScreen()" title="Lock your session">
                            <i class="ph-lock text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Lock Screen</span>
                            <small class="text-muted ms-auto">Ctrl+L</small>
                        </a>
                        
                        <div class="dropdown-divider"></div>
                        
                        <a class="dropdown-item text-danger" href="logout.php">
                            <i class="ph-sign-out text-danger fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Logout</span>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</header>

<!-- Add proper spacing after topbar -->
<div class="topbar-spacer"></div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Enhanced search functionality for cargo management
    const searchInput = document.getElementById('search-options');
    const searchDropdown = document.getElementById('search-dropdown');
    const resultsContainer = document.getElementById('search-results-container');
    const resultsDiv = document.getElementById('search-results');
    const searchLoading = document.querySelector('.search-loading');
    
    let searchTimeout;
    
    if (searchInput) {
        // Search input handler
        searchInput.addEventListener('input', function(e) {
            const query = e.target.value.trim();
            
            clearTimeout(searchTimeout);
            
            if (query.length >= 3) {
                showSearchLoading(true);
                searchTimeout = setTimeout(() => {
                    performSearch(query);
                }, 300);
            } else {
                hideSearchResults();
                showSearchLoading(false);
            }
        });
        
        // Show dropdown on focus
        searchInput.addEventListener('focus', function() {
            searchDropdown.classList.add('show');
        });
        
        // Hide dropdown when clicking outside
        document.addEventListener('click', function(e) {
            if (!searchInput.contains(e.target) && !searchDropdown.contains(e.target)) {
                searchDropdown.classList.remove('show');
            }
        });
    }
    
    function showSearchLoading(show) {
        if (searchLoading) {
            searchLoading.classList.toggle('d-none', !show);
        }
    }
    
    function hideSearchResults() {
        if (resultsContainer) {
            resultsContainer.style.display = 'none';
        }
    }
    
    function performSearch(query) {
        fetch('cargo_search_api.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify({ query: query })
        })
        .then(response => response.json())
        .then(data => {
            showSearchLoading(false);
            if (data.success && data.results.length > 0) {
                displaySearchResults(data.results);
                resultsContainer.style.display = 'block';
            } else {
                displayNoResults(query);
                resultsContainer.style.display = 'block';
            }
        })
        .catch(error => {
            console.error('Search error:', error);
            showSearchLoading(false);
            hideSearchResults();
        });
    }
    
    function displaySearchResults(results) {
        resultsDiv.innerHTML = results.map(result => {
            const icon = getResultIcon(result.type);
            const url = getResultUrl(result);
            const badge = getResultBadge(result.type);
            
            return `
                <a href="${url}" class="dropdown-item notify-item">
                    <div class="d-flex align-items-center">
                        <div class="avatar-xs me-3 flex-shrink-0">
                            <span class="avatar-title ${badge} rounded-circle fs-16">
                                <i class="${icon}"></i>
                            </span>
                        </div>
                        <div class="flex-grow-1">
                            <h6 class="mt-0 mb-1 fs-13">${getResultTitle(result)}</h6>
                            <p class="mb-0 fs-11 text-muted">${getResultSubtitle(result)}</p>
                        </div>
                        <div class="flex-shrink-0">
                            <span class="badge ${getBadgeClass(result.type)} fs-11">${result.type}</span>
                        </div>
                    </div>
                </a>
            `;
        }).join('');
    }
    
    function displayNoResults(query) {
        resultsDiv.innerHTML = `
            <div class="text-center p-3">
                <i class="ph-magnifying-glass fs-1 text-muted mb-2 d-block"></i>
                <h6 class="mb-1">No results found</h6>
                <p class="mb-0 fs-12 text-muted">No matches for "${query}"</p>
            </div>
        `;
    }
    
    function getResultIcon(type) {
        const icons = {
            'SHIPMENT': 'ph-package',
            'CUSTOMER': 'ph-user',
            'MANIFEST': 'ph-list-checks',
            'INVOICE': 'ph-receipt',
            'USER': 'ph-user-circle'
        };
        return icons[type] || 'ph-magnifying-glass';
    }
    
    function getResultBadge(type) {
        const badges = {
            'SHIPMENT': 'bg-soft-primary text-primary',
            'CUSTOMER': 'bg-soft-success text-success',
            'MANIFEST': 'bg-soft-info text-info',
            'INVOICE': 'bg-soft-warning text-warning',
            'USER': 'bg-soft-secondary text-secondary'
        };
        return badges[type] || 'bg-soft-light text-muted';
    }
    
    function getBadgeClass(type) {
        const classes = {
            'SHIPMENT': 'bg-soft-primary text-primary',
            'CUSTOMER': 'bg-soft-success text-success',
            'MANIFEST': 'bg-soft-info text-info',
            'INVOICE': 'bg-soft-warning text-warning',
            'USER': 'bg-soft-secondary text-secondary'
        };
        return classes[type] || 'bg-soft-light text-muted';
    }
    
    function getResultUrl(result) {
        const baseUrls = {
            'SHIPMENT': 'view_shipment.php?id=',
            'CUSTOMER': 'view_customer.php?id=',
            'MANIFEST': 'view_manifest.php?id=',
            'INVOICE': 'view_invoice.php?id=',
            'USER': 'view_user.php?id='
        };
        
        const identifier = result.shipment_id || result.customer_id || 
                          result.manifest_id || result.invoice_id || 
                          result.user_id;
        return baseUrls[result.type] + encodeURIComponent(identifier);
    }
    
    function getResultTitle(result) {
        switch(result.type) {
            case 'SHIPMENT':
                return result.tracking_number;
            case 'CUSTOMER':
                return result.customer_code || `${result.first_name || ''} ${result.last_name || ''}`.trim();
            case 'MANIFEST':
                return result.manifest_number;
            case 'INVOICE':
                return result.invoice_number;
            case 'USER':
                return result.full_name;
            default:
                return 'Unknown';
        }
    }
    
    function getResultSubtitle(result) {
        switch(result.type) {
            case 'SHIPMENT':
                return `${result.sender_name} → ${result.receiver_name}`;
            case 'CUSTOMER':
                return `Customer • ${result.customer_type || 'Individual'}`;
            case 'MANIFEST':
                return `Manifest • ${result.manifest_type || 'Standard'}`;
            case 'INVOICE':
                return `Invoice • ${result.total_amount || '0.00'}`;
            case 'USER':
                return `User • ${result.role_name || 'Staff'}`;
            default:
                return '';
        }
    }
    
    // Auto-refresh shipment feed every 2 minutes
    setInterval(refreshShipmentFeed, 120000);
    
    function refreshShipmentFeed() {
        fetch('get_shipment_feed.php')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    updateShipmentCount(data.count);
                }
            })
            .catch(error => console.error('Shipment refresh error:', error));
    }
    
    function updateShipmentCount(count) {
        const countBadge = document.querySelector('.topbar-badge');
        const dropdownCount = document.querySelector('.dropdown-tabs .badge');
        
        if (count > 0) {
            if (countBadge) {
                countBadge.textContent = Math.min(count, 99);
                countBadge.style.display = '';
            }
            if (dropdownCount) {
                dropdownCount.textContent = `${count} Pending`;
            }
        } else {
            if (countBadge) {
                countBadge.style.display = 'none';
            }
            if (dropdownCount) {
                dropdownCount.textContent = '0 Pending';
            }
        }
    }
});

// Lock screen functionality
function lockScreen() {
    if (confirm('Are you sure you want to lock your screen?')) {
        fetch('lock_screen.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                window.location.href = 'lock_screen.php';
            }
        })
        .catch(error => {
            console.error('Lock screen error:', error);
            window.location.href = 'logout.php';
        });
    }
}

// Enhanced keyboard shortcuts for cargo management
document.addEventListener('keydown', function(e) {
    if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.isContentEditable) {
        return;
    }
    
    // Ctrl/Cmd + K for search
    if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
        e.preventDefault();
        document.getElementById('search-options')?.focus();
    }
    
    // Ctrl/Cmd + Shift + S for shipments
    if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'S') {
        e.preventDefault();
        window.location.href = 'shipments.php';
    }
    
    // Ctrl/Cmd + Shift + C for customers
    if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'C') {
        e.preventDefault();
        window.location.href = 'customers.php';
    }
    
    // Ctrl/Cmd + Shift + M for manifests
    if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'M') {
        e.preventDefault();
        window.location.href = 'manifests.php';
    }
    
    // Ctrl/Cmd + Shift + I for invoices
    if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'I') {
        e.preventDefault();
        window.location.href = 'invoices.php';
    }
    
    // Ctrl/Cmd + Shift + R for reports
    if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'R') {
        e.preventDefault();
        window.location.href = 'reports.php';
    }
    
    // Ctrl/Cmd + L for lock screen
    if ((e.ctrlKey || e.metaKey) && e.key === 'l') {
        e.preventDefault();
        lockScreen();
    }
    
    // Escape to close dropdowns
    if (e.key === 'Escape') {
        document.getElementById('search-dropdown')?.classList.remove('show');
        document.querySelector('#notificationDropdown .dropdown-menu')?.classList.remove('show');
        document.querySelector('.topbar-user .dropdown-menu')?.classList.remove('show');
    }
});
</script>

<style>
/* Enhanced topbar styles for Cargo Management System */
#page-topbar {
    background: linear-gradient(135deg, #1e3a8a 0%, #1e40af 100%);
    box-shadow: 0 2px 20px rgba(0,0,0,0.1);
}

.navbar-header {
    padding: 0 1.5rem;
}

.app-search {
    margin-left: 1.5rem;
    min-width: 320px;
    position: relative;
}

.search-input {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    color: white;
    padding-left: 45px;
    padding-right: 45px;
    border-radius: 25px;
    backdrop-filter: blur(10px);
    transition: all 0.3s ease;
}

.search-input::placeholder {
    color: rgba(255, 255, 255, 0.7);
}

.search-input:focus {
    background: rgba(255, 255, 255, 0.2);
    border-color: rgba(255, 255, 255, 0.4);
    box-shadow: 0 0 0 0.2rem rgba(255, 255, 255, 0.25);
    color: white;
}

.search-widget-icon {
    position: absolute;
    top: 50%;
    left: 15px;
    transform: translateY(-50%);
    color: rgba(255, 255, 255, 0.8);
    z-index: 10;
}

.search-loading {
    position: absolute;
    top: 50%;
    right: 15px;
    transform: translateY(-50%);
    z-index: 10;
}

.search-dropdown {
    width: 450px;
    border: none;
    border-radius: 15px;
    box-shadow: 0 10px 40px rgba(0,0,0,0.15);
    margin-top: 10px;
}

.btn-ghost-secondary {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    color: white;
}

.btn-ghost-secondary:hover {
    background: rgba(255, 255, 255, 0.2);
    border-color: rgba(255, 255, 255, 0.3);
    color: white;
    transform: translateY(-2px);
}

.topbar-badge {
    top: -8px;
    right: -8px;
    min-width: 18px;
    height: 18px;
    font-size: 10px;
    line-height: 1;
    animation: pulse 2s infinite;
}

@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); }
}

.dropdown-menu {
    border: none;
    border-radius: 12px;
    box-shadow: 0 10px 40px rgba(0,0,0,0.15);
}

.dropdown-item:hover {
    background: linear-gradient(135deg, #1e3a8a 0%, #1e40af 100%);
    color: white;
    transform: translateX(3px);
}

#page-topbar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1030;
    height: 70px;
}

.topbar-spacer {
    height: 70px;
    width: 100%;
    flex-shrink: 0;
    background: transparent;
}

body {
    padding-top: 20px;
}

@media (max-width: 991.98px) {
    .app-search { display: none !important; }
    .user-name-text, .user-name-sub-text { display: none !important; }
    .navbar-header { padding: 0 1rem; }
    #page-topbar { height: 60px; }
    .topbar-spacer { height: 60px; }
    body { padding-top: 15px; }
}

@media (max-width: 767.98px) {
    .header-item.d-none.d-sm-flex { display: none !important; }
    .dropdown-menu { width: 280px; max-width: 90vw; }
    .search-dropdown { width: 320px; max-width: 95vw; }
    #page-topbar { height: 55px; }
    .topbar-spacer { height: 55px; }
    body { padding-top: 10px; }
}
</style>