<?php
include_once 'layouts/dbconn.php';

// Only start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$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 from pension system
$user_id = $_SESSION['user_id'];

$sql_user_details = "
    SELECT 
        u.*, 
        r.role_name,
        u.first_name,
        u.last_name,
        u.phone_number,
        u.email
    FROM users u 
    INNER JOIN roles r ON u.role_id = r.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'];
    $role_id = $user_data['role_id'];
    $full_name = trim($user_data['first_name'] . ' ' . $user_data['last_name']);
    $email = $user_data['email'];
    $phone_number = $user_data['phone_number'] ?? '';
    $profile_picture = 'default.png'; // Can be enhanced later
}

// Fetch recent activity from audit_logs (notifications)
$notifications_query = "
    SELECT 
        al.log_id, 
        al.event_type, 
        al.event_category, 
        al.event_description,
        al.created_at,
        al.performed_by
    FROM audit_logs al
    WHERE al.created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
    ORDER BY al.created_at DESC 
    LIMIT 10
";
$notifications_result = $conn->query($notifications_query);
$notifications = $notifications_result ? $notifications_result->fetch_all(MYSQLI_ASSOC) : [];

// Count unread notifications
$unread_count_query = "
    SELECT COUNT(*) AS count 
    FROM audit_logs 
    WHERE created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR) 
      AND event_category IN ('FINANCIAL', 'WITHDRAWAL', 'CONTRIBUTION', 'CLAIM')
";
$unread_result = $conn->query($unread_count_query);
$unread_count = $unread_result ? $unread_result->fetch_assoc()['count'] : 0;

// Get quick stats based on role
$quick_stats = [];

// Role IDs: 1=System Administrator, 2=Trustee, 3=Employer HR, 4=Member, 5=Insurance Officer, 6=Finance Officer, 7=Agent
if ($role_id == 1 || $role_id == 2) { // System Admin or Trustee
    $admin_stats_query = "
        SELECT 
            (SELECT COUNT(*) FROM pension_schemes WHERE is_active = 1) AS total_schemes,
            (SELECT COUNT(*) FROM members WHERE is_active = 1) AS total_members,
            (SELECT COUNT(*) FROM life_policies WHERE policy_status = 'ACTIVE') AS active_policies,
            (SELECT COUNT(*) FROM withdrawal_requests WHERE status = 'PENDING') AS pending_withdrawals,
            (SELECT COUNT(*) FROM life_claims WHERE claim_status = 'PENDING') AS pending_claims,
            (SELECT COALESCE(SUM(accrued_benefits), 0) FROM member_accounts) AS total_assets
    ";
    $admin_result = $conn->query($admin_stats_query);
    $quick_stats = $admin_result->fetch_assoc();
} elseif ($role_id == 3) { // Employer HR
    $employer_stats_query = "
        SELECT 
            (SELECT COUNT(*) FROM members WHERE employer_id = (SELECT employer_id FROM employers WHERE employer_id = ? LIMIT 1)) AS total_employees,
            (SELECT COUNT(*) FROM contributions WHERE contribution_type = 'EMPLOYER' AND MONTH(contribution_period) = MONTH(CURDATE()) AND YEAR(contribution_period) = YEAR(CURDATE())) AS monthly_contributions,
            (SELECT COALESCE(SUM(contribution_amount), 0) FROM contributions WHERE contribution_type = 'EMPLOYER' AND MONTH(contribution_period) = MONTH(CURDATE()) AND YEAR(contribution_period) = YEAR(CURDATE())) AS monthly_amount
    ";
    // Note: This query needs employer_id which should be linked to user
    $quick_stats = ['total_employees' => 0, 'monthly_contributions' => 0, 'monthly_amount' => 0];
} elseif ($role_id == 4) { // Member
    // Get member_id for this user
    $member_query = "SELECT member_id FROM members WHERE user_id = ? LIMIT 1";
    $stmt_member = $conn->prepare($member_query);
    $stmt_member->bind_param("i", $user_id);
    $stmt_member->execute();
    $member_result = $stmt_member->get_result()->fetch_assoc();
    $member_id = $member_result['member_id'] ?? null;
    
    if ($member_id) {
        $member_stats_query = "
            SELECT 
                ma.accrued_benefits,
                ma.available_balance,
                ma.total_withdrawn,
                (SELECT COUNT(*) FROM withdrawal_requests WHERE member_id = ?) AS withdrawal_count,
                (SELECT COUNT(*) FROM contributions WHERE member_id = ? AND YEAR(contribution_period) = YEAR(CURDATE())) AS yearly_contributions
            FROM member_accounts ma
            WHERE ma.member_id = ?
        ";
        $stmt_stats = $conn->prepare($member_stats_query);
        $stmt_stats->bind_param("iii", $member_id, $member_id, $member_id);
        $stmt_stats->execute();
        $quick_stats = $stmt_stats->get_result()->fetch_assoc();
    }
} elseif ($role_id == 5) { // Insurance Officer
    $insurance_stats_query = "
        SELECT 
            (SELECT COUNT(*) FROM life_policies WHERE policy_status = 'ACTIVE') AS active_policies,
            (SELECT COUNT(*) FROM life_claims WHERE claim_status = 'PENDING') AS pending_claims,
            (SELECT COUNT(*) FROM surrender_requests WHERE status = 'PENDING') AS pending_surrenders,
            (SELECT COUNT(*) FROM premiums WHERE payment_status = 'OVERDUE') AS overdue_premiums
    ";
    $insurance_result = $conn->query($insurance_stats_query);
    $quick_stats = $insurance_result->fetch_assoc();
} elseif ($role_id == 6) { // Finance Officer
    $finance_stats_query = "
        SELECT 
            (SELECT COUNT(*) FROM withdrawal_requests WHERE status = 'APPROVED') AS approved_withdrawals,
            (SELECT COUNT(*) FROM payouts WHERE payout_status = 'PENDING') AS pending_payouts,
            (SELECT COALESCE(SUM(payout_amount), 0) FROM payouts WHERE payout_status = 'PENDING') AS pending_amount,
            (SELECT COUNT(*) FROM premiums WHERE payment_status = 'OVERDUE') AS overdue_premiums
    ";
    $finance_result = $conn->query($finance_stats_query);
    $quick_stats = $finance_result->fetch_assoc();
}

// Helper functions - with guards to prevent redeclaration
if (!function_exists('getActivityColor')) {
    function getActivityColor($event_type) {
        return match($event_type) {
            'ACCRUED_BENEFITS_CALCULATION', 'CONTRIBUTION' => 'success',
            'WITHDRAWAL_ELIGIBILITY_CHECK', 'WITHDRAWAL' => 'warning',
            'SURRENDER_VALUE_CALCULATION', 'CLAIM' => 'info',
            'API_TOKEN_CREATED', 'API_TOKEN_REVOKED' => 'primary',
            default => 'secondary'
        };
    }
}

if (!function_exists('getActivityIcon')) {
    function getActivityIcon($event_type) {
        return match($event_type) {
            'ACCRUED_BENEFITS_CALCULATION' => 'bx-calculator',
            'CONTRIBUTION' => 'bx-plus-circle',
            'WITHDRAWAL_ELIGIBILITY_CHECK' => 'bx-minus-circle',
            'WITHDRAWAL' => 'bx-wallet',
            'SURRENDER_VALUE_CALCULATION' => 'bx-file',
            'CLAIM' => 'bx-receipt',
            'API_TOKEN_CREATED' => 'bx-key',
            'API_TOKEN_REVOKED' => 'bx-lock',
            default => 'bx-bell'
        };
    }
}

if (!function_exists('formatActivityMessage')) {
    function formatActivityMessage($notification) {
        $event = $notification['event_type'];
        $user = $notification['performed_by'] ?: 'SYSTEM';
        $desc = $notification['event_description'];
        
        // Truncate long descriptions
        if (strlen($desc) > 80) {
            $desc = substr($desc, 0, 80) . '...';
        }
        
        return $desc;
    }
}

if (!function_exists('getTimeAgo')) {
    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">
                <!-- PENSION SYSTEM 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/logo-sm.png" alt="Pension 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 Pension System -->
                <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 members, schemes, policies..." 
                               autocomplete="off" id="search-options">
                        <span class="search-widget-icon">
                            <i class="bx bx-search-alt"></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="bx bx-bolt 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">
                                    <?php if ($role_id == 1 || $role_id == 2): ?>
                                    <a href="add_member.php" class="btn btn-soft-primary btn-sm">
                                        <i class="bx bx-user-plus me-1"></i>Add Member
                                    </a>
                                    <a href="create_scheme.php" class="btn btn-soft-success btn-sm">
                                        <i class="bx bx-briefcase me-1"></i>Create Scheme
                                    </a>
                                    <a href="post_contribution.php" class="btn btn-soft-info btn-sm">
                                        <i class="bx bx-money me-1"></i>Post Contribution
                                    </a>
                                    <?php endif; ?>
                                    <?php if ($role_id == 5): ?>
                                    <a href="create_policy.php" class="btn btn-soft-warning btn-sm">
                                        <i class="bx bx-file-blank me-1"></i>Create Policy
                                    </a>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- System Modules -->
                            <div class="dropdown-header bg-light">
                                <h6 class="text-overflow text-muted mb-1 text-uppercase">
                                    <i class="bx bx-grid-alt me-1"></i>System Modules
                                </h6>
                            </div>

                            <?php if ($role_id == 1 || $role_id == 2 || $role_id == 3): ?>
                            <a href="list_members.php" class="dropdown-item notify-item">
                                <i class="bx bx-user align-middle fs-18 text-primary me-2"></i>
                                <span>Members</span>
                            </a>

                            <a href="list_schemes.php" class="dropdown-item notify-item">
                                <i class="bx bx-briefcase align-middle fs-18 text-success me-2"></i>
                                <span>Pension Schemes</span>
                            </a>
                            <?php endif; ?>

                            <a href="contributions.php" class="dropdown-item notify-item">
                                <i class="bx bx-money align-middle fs-18 text-info me-2"></i>
                                <span>Contributions</span>
                            </a>

                            <?php if ($role_id == 1 || $role_id == 2 || $role_id == 6): ?>
                            <a href="withdrawal_requests.php" class="dropdown-item notify-item">
                                <i class="bx bx-wallet align-middle fs-18 text-warning me-2"></i>
                                <span>Withdrawals</span>
                            </a>
                            <?php endif; ?>

                            <?php if ($role_id == 1 || $role_id == 5): ?>
                            <a href="life_policies.php" class="dropdown-item notify-item">
                                <i class="bx bx-file-blank align-middle fs-18 text-danger me-2"></i>
                                <span>Life Policies</span>
                            </a>

                            <a href="life_claims.php" class="dropdown-item notify-item">
                                <i class="bx bx-receipt align-middle fs-18 text-primary me-2"></i>
                                <span>Life Claims</span>
                            </a>
                            <?php endif; ?>

                            <!-- 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="bx bx-search me-1"></i>Search Results
                                    </h6>
                                </div>
                                <div id="search-results"></div>
                            </div>
                        </div>

                        <div class="text-center p-3 border-top">
                            <a href="advanced_search.php" class="btn btn-primary btn-sm w-100">
                                <i class="bx bx-search 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/kenya.svg" alt="Kenya Flag" class="me-2 rounded" height="20">
                    <span class="align-middle text-white fw-medium">Kenya</span>
                </div>

                <!-- Activity/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='bx bx-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">unread notifications</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="bx bx-bell me-1"></i>System Activity
                                        </h6>
                                    </div>
                                    <div class="col-auto dropdown-tabs">
                                        <span class="badge bg-light-subtle text-body fs-13">
                                            <?php echo $unread_count; ?> New
                                        </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="bx bx-bell-off fs-1 text-muted mb-3 d-block"></i>
                                            <h6 class="mb-1">No recent activity</h6>
                                            <p class="mb-0 fs-12">When system activities occur, 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['event_type']); ?>-subtle text-<?php echo getActivityColor($notification['event_type']); ?> rounded-circle fs-16">
                                                            <i class="<?php echo getActivityIcon($notification['event_type']); ?>"></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="bx bx-time"></i> 
                                                                <?php echo getTimeAgo($notification['created_at']); ?>
                                                            </span>
                                                        </p>
                                                    </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="audit_logs.php">
                                            View All Activities <i class="bx bx-right-arrow-alt 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">
                                <div class="avatar-xs">
                                    <span class="avatar-title bg-white text-primary rounded-circle">
                                        <?php echo strtoupper(substr($full_name, 0, 1)); ?>
                                    </span>
                                </div>
                            </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">
                                    <div class="avatar-sm">
                                        <span class="avatar-title bg-primary text-white rounded-circle">
                                            <?php echo strtoupper(substr($full_name, 0, 1)); ?>
                                        </span>
                                    </div>
                                </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>
                        
                        <!-- Role-based Menu Items -->
                        <a class="dropdown-item" href="profile.php">
                            <i class="bx bx-user-circle text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">My Profile</span>
                        </a>
                        
                        <?php if($role_id == 1): // System Administrator ?>
                        <a class="dropdown-item" href="system_settings.php">
                            <i class="bx bx-cog text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">System Settings</span>
                        </a>
                        
                        <a class="dropdown-item" href="list_users.php">
                            <i class="bx bx-group text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">User Management</span>
                        </a>
                        
                        <a class="dropdown-item" href="role_permissions.php">
                            <i class="bx bx-shield text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Role Permissions</span>
                        </a>
                        
                        <?php elseif($role_id == 2): // Trustee ?>
                        <a class="dropdown-item" href="my_schemes.php">
                            <i class="bx bx-briefcase text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">My Schemes</span>
                        </a>
                        
                        <a class="dropdown-item" href="pending_approvals.php">
                            <i class="bx bx-check-circle text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Pending Approvals</span>
                            <?php if(isset($quick_stats['pending_withdrawals']) && $quick_stats['pending_withdrawals'] > 0): ?>
                                <span class="badge bg-warning ms-2 fs-11"><?php echo $quick_stats['pending_withdrawals']; ?></span>
                            <?php endif; ?>
                        </a>
                        
                        <a class="dropdown-item" href="reports_dashboard.php">
                            <i class="bx bx-line-chart text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Reports</span>
                        </a>
                        
                        <?php elseif($role_id == 4): // Member ?>
                        <a class="dropdown-item" href="my_account.php">
                            <i class="bx bx-wallet text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">My Account</span>
                        </a>
                        
                        <a class="dropdown-item" href="my_contributions.php">
                            <i class="bx bx-money text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">My Contributions</span>
                        </a>
                        
                        <a class="dropdown-item" href="my_withdrawals.php">
                            <i class="bx bx-transfer text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Withdrawal Requests</span>
                        </a>
                        
                        <a class="dropdown-item" href="member_statement.php">
                            <i class="bx bx-file text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Statement</span>
                        </a>
                        
                        <?php elseif($role_id == 5): // Insurance Officer ?>
                        <a class="dropdown-item" href="life_policies.php">
                            <i class="bx bx-file-blank text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Life Policies</span>
                        </a>
                        
                        <a class="dropdown-item" href="pending_claims.php">
                            <i class="bx bx-receipt text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Pending Claims</span>
                            <?php if(isset($quick_stats['pending_claims']) && $quick_stats['pending_claims'] > 0): ?>
                                <span class="badge bg-danger ms-2 fs-11"><?php echo $quick_stats['pending_claims']; ?></span>
                            <?php endif; ?>
                        </a>
                        
                        <a class="dropdown-item" href="surrender_requests.php">
                            <i class="bx bx-transfer text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Surrender Requests</span>
                        </a>
                        
                        <?php elseif($role_id == 6): // Finance Officer ?>
                        <a class="dropdown-item" href="pending_payouts.php">
                            <i class="bx bx-wallet text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Pending Payouts</span>
                            <?php if(isset($quick_stats['pending_payouts']) && $quick_stats['pending_payouts'] > 0): ?>
                                <span class="badge bg-warning ms-2 fs-11"><?php echo $quick_stats['pending_payouts']; ?></span>
                            <?php endif; ?>
                        </a>
                        
                        <a class="dropdown-item" href="payment_processing.php">
                            <i class="bx bx-check-circle text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Process Payments</span>
                        </a>
                        
                        <a class="dropdown-item" href="financial_reports.php">
                            <i class="bx bx-line-chart 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="bx bx-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="bx bx-time 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="bx bx-lock text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Change Password</span>
                        </a>
                        
                        <div class="dropdown-divider"></div>
                        
                        <a class="dropdown-item text-danger" href="logout.php">
                            <i class="bx bx-log-out text-danger fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Logout</span>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</header>

<style>
/* Pension System Topbar Styles */
#page-topbar {
    background: linear-gradient(135deg, #2563eb 0%, #3b82f6 100%);
    box-shadow: 0 2px 20px rgba(0,0,0,0.1);
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1030;
    height: 70px;
}

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

/* Search styles */
.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;
}

/* Notification styles */
.notification-item {
    transition: all 0.2s ease;
    border-radius: 8px;
    margin: 2px;
}

.notification-item:hover {
    background: linear-gradient(135deg, rgba(37, 99, 235, 0.05) 0%, rgba(59, 130, 246, 0.05) 100%);
    transform: translateX(3px);
}

/* User profile styles */
.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); }
}

/* Button styles */
.btn-icon {
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: all 0.3s ease;
}

.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);
}

/* Responsive adjustments */
@media (max-width: 991.98px) {
    .app-search {
        display: none !important;
    }
    
    .user-name-text,
    .user-name-sub-text {
        display: none !important;
    }
    
    #page-topbar { height: 60px; }
}

@media (max-width: 767.98px) {
    .header-item.d-none.d-sm-flex {
        display: none !important;
    }
    
    #page-topbar { height: 55px; }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Enhanced search functionality
    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) {
        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);
            }
        });
        
        searchInput.addEventListener('focus', function() {
            searchDropdown.classList.add('show');
        });
        
        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('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 => {
            return `
                <a href="${result.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 bg-soft-primary text-primary rounded-circle fs-16">
                                <i class="bx ${result.icon}"></i>
                            </span>
                        </div>
                        <div class="flex-grow-1">
                            <h6 class="mt-0 mb-1 fs-13">${result.title}</h6>
                            <p class="mb-0 fs-11 text-muted">${result.subtitle}</p>
                        </div>
                        <div class="flex-shrink-0">
                            <span class="badge bg-soft-primary text-primary fs-11">${result.type}</span>
                        </div>
                    </div>
                </a>
            `;
        }).join('');
    }
    
    function displayNoResults(query) {
        resultsDiv.innerHTML = `
            <div class="text-center p-3">
                <i class="bx bx-search-alt 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>
        `;
    }
    
    // Auto-refresh activity feed every 2 minutes
    setInterval(refreshActivityFeed, 120000);
    
    function refreshActivityFeed() {
        fetch('get_activity_feed.php')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    updateActivityCount(data.count);
                }
            })
            .catch(error => console.error('Activity refresh error:', error));
    }
    
    function updateActivityCount(count) {
        const countBadge = document.querySelector('.topbar-badge');
        if (count > 0 && countBadge) {
            countBadge.textContent = Math.min(count, 99);
            countBadge.style.display = '';
        } else if (countBadge) {
            countBadge.style.display = 'none';
        }
    }
});
</script>