<?php 
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 Property Management System schema alignment
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, r.role_name
                     FROM users u 
                     INNER JOIN roles r ON u.role_id = r.id 
                     WHERE u.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['email'];
    $role_name = $user_data['role_name'];
    $full_name = trim($user_data['first_name'] . ' ' . ($user_data['middle_name'] ?? '') . ' ' . $user_data['last_name']);
    $email = $user_data['email'];
    $phone_number = $user_data['phone'];
    $profile_picture = $user_data['profile_photo_url'] ?? null;
}

// Fetch recent activity from activity_logs (using as notifications)
$notifications_query = "SELECT al.id, al.action_type, al.module, al.reference_id, al.timestamp, 
                       al.user_id, u.first_name, u.last_name
                       FROM activity_logs al 
                       LEFT JOIN users u ON al.user_id = u.id 
                       WHERE al.action_type IN ('CREATE', 'UPDATE', 'DELETE')
                       AND al.timestamp >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
                       ORDER BY al.timestamp DESC LIMIT 10";
$notifications_result = $conn->query($notifications_query);
$notifications = [];
if ($notifications_result) {
    $notifications = $notifications_result->fetch_all(MYSQLI_ASSOC);
}

// Count recent activities as unread notifications
$unread_count_query = "SELECT COUNT(*) as count FROM activity_logs 
                      WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 24 HOUR) 
                      AND action_type IN ('CREATE', 'UPDATE', 'DELETE')";
$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.id as user_id, CONCAT(u.first_name, ' ', u.last_name) as full_name, 
              r.role_name, u.profile_photo_url as profile_picture 
              FROM users u 
              LEFT JOIN roles r ON u.role_id = r.id 
              WHERE u.status = 'active' AND u.id != ? 
              ORDER BY u.first_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 ($role_name === 'Super Admin') {
    // Get admin's system stats
    $admin_stats_query = "SELECT 
        (SELECT COUNT(*) FROM properties) as total_properties,
        (SELECT COUNT(*) FROM units WHERE status = 'vacant') as vacant_units,
        (SELECT COUNT(*) FROM leases WHERE status = 'active') as active_leases,
        (SELECT COALESCE(SUM(amount), 0) FROM payments WHERE MONTH(payment_date) = MONTH(CURDATE())) as monthly_revenue";
    $admin_result = $conn->query($admin_stats_query);
    $quick_stats = $admin_result->fetch_assoc();
} elseif ($role_name === 'Landlord') {
    // Get landlord's property stats
    $landlord_stats_query = "SELECT 
        (SELECT COUNT(*) FROM properties WHERE owner_id = ?) as my_properties,
        (SELECT COUNT(*) FROM units u 
         JOIN properties p ON u.property_id = p.id 
         WHERE p.owner_id = ? AND u.status = 'occupied') as occupied_units,
        (SELECT COUNT(*) FROM invoices i 
         JOIN leases l ON i.lease_id = l.id 
         JOIN units u ON l.unit_id = u.id 
         JOIN properties p ON u.property_id = p.id 
         WHERE p.owner_id = ? AND i.status = 'unpaid') as unpaid_invoices,
        (SELECT COALESCE(SUM(pay.amount), 0) FROM payments pay
         JOIN invoices i ON pay.invoice_id = i.id
         JOIN leases l ON i.lease_id = l.id
         JOIN units u ON l.unit_id = u.id
         JOIN properties p ON u.property_id = p.id
         WHERE p.owner_id = ? AND MONTH(pay.payment_date) = MONTH(CURDATE())) as monthly_revenue";
    $stmt_landlord = $conn->prepare($landlord_stats_query);
    $stmt_landlord->bind_param("iiii", $user_id, $user_id, $user_id, $user_id);
    $stmt_landlord->execute();
    $quick_stats = $stmt_landlord->get_result()->fetch_assoc();
} elseif ($role_name === 'Property Manager') {
    // Get property manager's stats
    $manager_stats_query = "SELECT 
        (SELECT COUNT(*) FROM properties WHERE manager_id = ?) as managed_properties,
        (SELECT COUNT(*) FROM maintenance_requests mr
         JOIN properties p ON mr.property_id = p.id
         WHERE p.manager_id = ? AND mr.status IN ('Open', 'Assigned')) as pending_maintenance,
        (SELECT COUNT(*) FROM leases l
         JOIN units u ON l.unit_id = u.id
         JOIN properties p ON u.property_id = p.id
         WHERE p.manager_id = ? AND l.end_date <= DATE_ADD(CURDATE(), INTERVAL 30 DAY)
         AND l.status = 'active') as expiring_leases,
        (SELECT COUNT(*) FROM tenant_complaints tc
         JOIN properties p ON tc.property_id = p.id
         WHERE p.manager_id = ? AND tc.status NOT IN ('resolved', 'closed')) as open_complaints";
    $stmt_manager = $conn->prepare($manager_stats_query);
    $stmt_manager->bind_param("iiii", $user_id, $user_id, $user_id, $user_id);
    $stmt_manager->execute();
    $quick_stats = $stmt_manager->get_result()->fetch_assoc();
} elseif ($role_name === 'Tenant') {
    // Get tenant's stats
    $tenant_stats_query = "SELECT 
        (SELECT COUNT(*) FROM leases WHERE tenant_id = ? AND status = 'active') as active_leases,
        (SELECT COUNT(*) FROM invoices WHERE tenant_id = ? AND status IN ('unpaid', 'overdue')) as unpaid_invoices,
        (SELECT COUNT(*) FROM maintenance_requests WHERE requester_id = ? AND status != 'Completed') as open_requests,
        (SELECT COALESCE(SUM(balance), 0) FROM invoices WHERE tenant_id = ? AND status != 'paid') as outstanding_balance";
    $stmt_tenant = $conn->prepare($tenant_stats_query);
    $stmt_tenant->bind_param("iiii", $user_id, $user_id, $user_id, $user_id);
    $stmt_tenant->execute();
    $quick_stats = $stmt_tenant->get_result()->fetch_assoc();
} elseif ($role_name === 'Accountant') {
    // Get accountant's financial stats
    $accountant_stats_query = "SELECT 
        (SELECT COUNT(*) FROM invoices WHERE status = 'overdue') as overdue_invoices,
        (SELECT COUNT(*) FROM payments WHERE status = 'pending') as pending_payments,
        (SELECT COALESCE(SUM(amount), 0) FROM payments 
         WHERE DATE(payment_date) = CURDATE()) as daily_collections,
        (SELECT COALESCE(SUM(balance), 0) FROM invoices 
         WHERE status IN ('unpaid', 'partial', 'overdue')) as total_outstanding";
    $accountant_result = $conn->query($accountant_stats_query);
    $quick_stats = $accountant_result->fetch_assoc();
} elseif ($role_name === 'Vendor') {
    // Get vendor's maintenance stats
    $vendor_stats_query = "SELECT 
        (SELECT COUNT(*) FROM maintenance_requests 
         WHERE assigned_vendor_id = ? AND status = 'Assigned') as assigned_jobs,
        (SELECT COUNT(*) FROM maintenance_requests 
         WHERE assigned_vendor_id = ? AND status = 'In Progress') as in_progress_jobs,
        (SELECT COUNT(*) FROM maintenance_requests 
         WHERE assigned_vendor_id = ? AND status = 'Completed' 
         AND DATE(completed_date) = CURDATE()) as completed_today,
        (SELECT COALESCE(SUM(final_cost), 0) FROM maintenance_requests 
         WHERE assigned_vendor_id = ? AND status = 'Completed' 
         AND MONTH(completed_date) = MONTH(CURDATE())) as monthly_earnings";
    $stmt_vendor = $conn->prepare($vendor_stats_query);
    $stmt_vendor->bind_param("iiii", $user_id, $user_id, $user_id, $user_id);
    $stmt_vendor->execute();
    $quick_stats = $stmt_vendor->get_result()->fetch_assoc();
}

// Helper functions for activity formatting
function getActivityColor($action) {
    return match($action) {
        'CREATE' => 'success',
        'UPDATE' => 'primary',
        'DELETE' => 'danger',
        'LOGIN' => 'info',
        default => 'secondary'
    };
}

function getActivityIcon($action) {
    return match($action) {
        'CREATE' => 'ph-plus-circle',
        'UPDATE' => 'ph-pencil-circle',
        'DELETE' => 'ph-minus-circle',
        'LOGIN' => 'ph-sign-in',
        default => 'ph-bell'
    };
}

function formatActivityMessage($notification) {
    $action = $notification['action_type'];
    $module = $notification['module'];
    $user = trim(($notification['first_name'] ?? '') . ' ' . ($notification['last_name'] ?? '')) ?: 'System';
    
    return match($action) {
        'CREATE' => "New {$module} created by {$user}",
        'UPDATE' => "{$module} updated by {$user}",
        'DELETE' => "{$module} deleted by {$user}",
        'LOGIN' => "{$user} logged into the system",
        default => "System activity in {$module}"
    };
}

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

// System name and branding
$system_name = 'Property Management System';
$system_logo = 'assets/images/logo.png'; // Default logo path
?>

<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">
                            <img src="<?php echo htmlspecialchars($system_logo); ?>" alt="" height="22">
                        </span>
                        <span class="logo-lg">
                            <img src="<?php echo htmlspecialchars($system_logo); ?>" alt="" height="17">
                        </span>
                    </a>
                    <a href="index.php" class="logo logo-light">
                        <span class="logo-sm">
                            <img src="<?php echo htmlspecialchars($system_logo); ?>" alt="" height="22">
                        </span>
                        <span class="logo-lg">
                            <img src="<?php echo htmlspecialchars($system_logo); ?>" alt="" height="17">
                        </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 Property Management 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 properties, tenants, units..." 
                               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">
                                    <?php if (in_array($role_name, ['Super Admin', 'Property Manager'])): ?>
                                    <a href="add_property.php" class="btn btn-soft-primary btn-sm">
                                        <i class="ph-buildings me-1"></i>Add Property
                                    </a>
                                    <a href="add_tenant.php" class="btn btn-soft-success btn-sm">
                                        <i class="ph-user-plus me-1"></i>Add Tenant
                                    </a>
                                    <?php endif; ?>
                                    <?php if (in_array($role_name, ['Super Admin', 'Accountant'])): ?>
                                    <a href="create_invoice.php" class="btn btn-soft-warning btn-sm">
                                        <i class="ph-receipt me-1"></i>Create Invoice
                                    </a>
                                    <?php endif; ?>
                                    <?php if ($role_name === 'Tenant'): ?>
                                    <a href="create_maintenance_request.php" class="btn btn-soft-info btn-sm">
                                        <i class="ph-wrench me-1"></i>Request Maintenance
                                    </a>
                                    <?php endif; ?>
                                </div>
                            </div>

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

                            <a href="list_properties.php" class="dropdown-item notify-item">
                                <i class="ph-buildings align-middle fs-18 text-primary me-2"></i>
                                <span>Properties</span>
                            </a>

                            <a href="list_units.php" class="dropdown-item notify-item">
                                <i class="ph-house align-middle fs-18 text-success me-2"></i>
                                <span>Units</span>
                            </a>

                            <a href="list_tenants.php" class="dropdown-item notify-item">
                                <i class="ph-users align-middle fs-18 text-info me-2"></i>
                                <span>Tenants</span>
                            </a>

                            <a href="list_leases.php" class="dropdown-item notify-item">
                                <i class="ph-file-text align-middle fs-18 text-warning me-2"></i>
                                <span>Leases</span>
                            </a>

                            <?php if (in_array($role_name, ['Super Admin', 'Accountant'])): ?>
                            <a href="list_invoices.php" class="dropdown-item notify-item">
                                <i class="ph-receipt align-middle fs-18 text-danger me-2"></i>
                                <span>Invoices</span>
                            </a>

                            <a href="list_payments.php" class="dropdown-item notify-item">
                                <i class="ph-money align-middle fs-18 text-success me-2"></i>
                                <span>Payments</span>
                            </a>
                            <?php endif; ?>

                            <a href="list_maintenance.php" class="dropdown-item notify-item">
                                <i class="ph-wrench align-middle fs-18 text-secondary me-2"></i>
                                <span>Maintenance</span>
                            </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['profile_picture']): ?>
                                                <img src="<?php echo $member['profile_picture']; ?>" 
                                                     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>
                                </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 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='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">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="ph-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="ph-bell-slash 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['action_type']); ?>-subtle text-<?php echo getActivityColor($notification['action_type']); ?> rounded-circle fs-16">
                                                            <i class="<?php echo getActivityIcon($notification['action_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="ph-clock"></i> 
                                                                <?php echo getTimeAgo($notification['timestamp']); ?>
                                                            </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="activity_log.php">
                                            View All Activities <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="<?php echo $profile_picture; ?>" 
                                         alt="Header Avatar">
                                <?php else: ?>
                                    <div class="avatar-xs">
                                        <span class="avatar-title bg-primary text-white 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">
                                    <?php echo htmlspecialchars($full_name); ?>
                                </span>
                                <span class="d-none d-xl-block ms-1 fs-13 user-name-sub-text">
                                    <?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="<?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>
                        
                        <!-- Role-based Menu Items -->
                        <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 === 'Super Admin'): ?>
                        <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="list_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="role_permissions.php">
                            <i class="ph-key text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Role Permissions</span>
                        </a>
                        
                        <?php elseif($role_name === 'Landlord'): ?>
                        <a class="dropdown-item" href="my_properties.php">
                            <i class="ph-buildings text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">My Properties</span>
                        </a>
                        
                        <a class="dropdown-item" href="my_tenants.php">
                            <i class="ph-users text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">My Tenants</span>
                        </a>
                        
                        <a class="dropdown-item" href="financial_reports.php">
                            <i class="ph-chart-line text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Financial Reports</span>
                        </a>
                        
                        <?php elseif($role_name === 'Property Manager'): ?>
                        <a class="dropdown-item" href="managed_properties.php">
                            <i class="ph-buildings text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Managed Properties</span>
                        </a>
                        
                        <a class="dropdown-item" href="maintenance_requests.php">
                            <i class="ph-wrench text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Maintenance Requests</span>
                            <?php if(isset($quick_stats['pending_maintenance']) && $quick_stats['pending_maintenance'] > 0): ?>
                                <span class="badge bg-danger ms-2 fs-11"><?php echo $quick_stats['pending_maintenance']; ?></span>
                            <?php endif; ?>
                        </a>
                        
                        <a class="dropdown-item" href="tenant_complaints.php">
                            <i class="ph-chat-circle text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Tenant Complaints</span>
                            <?php if(isset($quick_stats['open_complaints']) && $quick_stats['open_complaints'] > 0): ?>
                                <span class="badge bg-warning ms-2 fs-11"><?php echo $quick_stats['open_complaints']; ?></span>
                            <?php endif; ?>
                        </a>
                        
                        <?php elseif($role_name === 'Tenant'): ?>
                        <a class="dropdown-item" href="my_lease.php">
                            <i class="ph-file-text text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">My Lease</span>
                        </a>
                        
                        <a class="dropdown-item" href="my_invoices.php">
                            <i class="ph-receipt text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">My Invoices</span>
                            <?php if(isset($quick_stats['unpaid_invoices']) && $quick_stats['unpaid_invoices'] > 0): ?>
                                <span class="badge bg-danger ms-2 fs-11"><?php echo $quick_stats['unpaid_invoices']; ?></span>
                            <?php endif; ?>
                        </a>
                        
                        <a class="dropdown-item" href="my_payments.php">
                            <i class="ph-money text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Payment History</span>
                        </a>
                        
                        <a class="dropdown-item" href="my_maintenance.php">
                            <i class="ph-wrench text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Maintenance Requests</span>
                            <?php if(isset($quick_stats['open_requests']) && $quick_stats['open_requests'] > 0): ?>
                                <span class="badge bg-primary ms-2 fs-11"><?php echo $quick_stats['open_requests']; ?></span>
                            <?php endif; ?>
                        </a>
                        
                        <?php elseif($role_name === 'Accountant'): ?>
                        <a class="dropdown-item" href="all_invoices.php">
                            <i class="ph-receipt text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">All Invoices</span>
                        </a>
                        
                        <a class="dropdown-item" href="all_payments.php">
                            <i class="ph-money text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">All Payments</span>
                        </a>
                        
                        <a class="dropdown-item" href="overdue_invoices.php">
                            <i class="ph-warning text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Overdue Invoices</span>
                            <?php if(isset($quick_stats['overdue_invoices']) && $quick_stats['overdue_invoices'] > 0): ?>
                                <span class="badge bg-danger ms-2 fs-11"><?php echo $quick_stats['overdue_invoices']; ?></span>
                            <?php endif; ?>
                        </a>
                        
                        <a class="dropdown-item" href="financial_reports.php">
                            <i class="ph-chart-line text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Financial Reports</span>
                        </a>
                        
                        <?php elseif($role_name === 'Vendor'): ?>
                        <a class="dropdown-item" href="my_jobs.php">
                            <i class="ph-wrench text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">My Jobs</span>
                            <?php if(isset($quick_stats['assigned_jobs']) && $quick_stats['assigned_jobs'] > 0): ?>
                                <span class="badge bg-warning ms-2 fs-11"><?php echo $quick_stats['assigned_jobs']; ?></span>
                            <?php endif; ?>
                        </a>
                        
                        <a class="dropdown-item" href="job_history.php">
                            <i class="ph-clock-counter-clockwise text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">Job History</span>
                        </a>
                        
                        <a class="dropdown-item" href="my_earnings.php">
                            <i class="ph-chart-bar text-muted fs-16 align-middle me-1"></i> 
                            <span class="align-middle">My Earnings</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>
                        </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>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Enhanced search functionality for Property Management System
    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('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 = {
            'PROPERTY': 'ph-buildings',
            'UNIT': 'ph-house',
            'TENANT': 'ph-user',
            'LEASE': 'ph-file-text',
            'INVOICE': 'ph-receipt',
            'PAYMENT': 'ph-money',
            'MAINTENANCE': 'ph-wrench'
        };
        return icons[type] || 'ph-magnifying-glass';
    }
    
    function getResultBadge(type) {
        const badges = {
            'PROPERTY': 'bg-soft-primary text-primary',
            'UNIT': 'bg-soft-success text-success',
            'TENANT': 'bg-soft-info text-info',
            'LEASE': 'bg-soft-warning text-warning',
            'INVOICE': 'bg-soft-danger text-danger',
            'PAYMENT': 'bg-soft-success text-success',
            'MAINTENANCE': 'bg-soft-secondary text-secondary'
        };
        return badges[type] || 'bg-soft-light text-muted';
    }
    
    function getBadgeClass(type) {
        const classes = {
            'PROPERTY': 'bg-soft-primary text-primary',
            'UNIT': 'bg-soft-success text-success',
            'TENANT': 'bg-soft-info text-info',
            'LEASE': 'bg-soft-warning text-warning',
            'INVOICE': 'bg-soft-danger text-danger',
            'PAYMENT': 'bg-soft-success text-success',
            'MAINTENANCE': 'bg-soft-secondary text-secondary'
        };
        return classes[type] || 'bg-soft-light text-muted';
    }
    
    function getResultUrl(result) {
        const baseUrls = {
            'PROPERTY': 'view_property.php?id=',
            'UNIT': 'view_unit.php?id=',
            'TENANT': 'view_tenant.php?id=',
            'LEASE': 'view_lease.php?id=',
            'INVOICE': 'view_invoice.php?id=',
            'PAYMENT': 'view_payment.php?id=',
            'MAINTENANCE': 'view_maintenance.php?id='
        };
        
        return baseUrls[result.type] + encodeURIComponent(result.id);
    }
    
    function getResultTitle(result) {
        return result.title || result.name || 'Unknown';
    }
    
    function getResultSubtitle(result) {
        return result.subtitle || result.description || '';
    }
});

// Lock screen functionality
function lockScreen() {
    if (confirm('Are you sure you want to lock your screen?')) {
        window.location.href = 'lock_screen.php';
    }
}

// Keyboard shortcuts
document.addEventListener('keydown', function(e) {
    if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') {
        return;
    }
    
    // Ctrl/Cmd + K for search
    if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
        e.preventDefault();
        document.getElementById('search-options')?.focus();
    }
});
</script>

<style>
/* Enhanced topbar styles */
#page-topbar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1030;
    height: 70px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    box-shadow: 0 2px 20px rgba(0,0,0,0.1);
}

body {
    padding-top: 70px;
}

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

/* Search styles */
.app-search {
    margin-left: 1.5rem;
    min-width: 320px;
}

.search-input {
    background: rgba(255, 255, 255, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.3);
    color: white;
    padding-left: 45px;
    padding-right: 45px;
    border-radius: 25px;
}

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

.search-input:focus {
    background: rgba(255, 255, 255, 0.3);
    border-color: rgba(255, 255, 255, 0.5);
    color: white;
}

.search-widget-icon {
    position: absolute;
    top: 50%;
    left: 15px;
    transform: translateY(-50%);
    color: white;
}

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

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

.notification-item:hover {
    background: rgba(102, 126, 234, 0.1);
    transform: translateX(3px);
}

/* User profile styles */
.header-profile-user {
    width: 36px;
    height: 36px;
    object-fit: cover;
    border: 2px solid rgba(255, 255, 255, 0.3);
}

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

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

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

.dropdown-item {
    padding: 8px 15px;
    border-radius: 6px;
    margin: 1px 5px;
    transition: all 0.2s ease;
}

.dropdown-item:hover {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    transform: translateX(3px);
}

/* Responsive */
@media (max-width: 991.98px) {
    .app-search {
        display: none !important;
    }
    #page-topbar { height: 60px; }
    body { padding-top: 60px; }
}

@media (max-width: 767.98px) {
    #page-topbar { height: 55px; }
    body { padding-top: 55px; }
}
</style>