<?php
require_once __DIR__ . '/config/session.php';
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/config/helpers.php';

// Check if user is logged in and is staff
if (!isLoggedIn()) {
    header("Location: staff-login.php");
    exit();
}

$currentUser = getCurrentUser();
if (!isset($currentUser['user_type']) || $currentUser['user_type'] !== 'staff') {
    header("Location: staff-login.php");
    exit();
}

$userId = getCurrentUserId();
$dbHelper = new DBHelper($conn);

// Get dashboard statistics
$dashboardStats = [
    'total_guests' => 0,
    'total_reservations' => 0,
    'total_service_reservations' => 0,
    'active_reservations' => 0,
    'active_service_reservations' => 0,
    'total_active_bookings' => 0,
    'checked_in_guests' => 0,
    'pending_reservations' => 0,
    'pending_service_reservations' => 0,
    'total_pending_reservations' => 0,
    'total_cost' => 0
];

try {
    // Total guests
    $result = $conn->query("SELECT COUNT(*) as count FROM users WHERE user_type = 'guest' AND is_active = 1");
    if ($result) {
        $row = $result->fetch_assoc();
        $dashboardStats['total_guests'] = $row['count'] ?? 0;
    }

    // Total reservations
    $result = $conn->query("SELECT COUNT(*) as count FROM reservations");
    if ($result) {
        $row = $result->fetch_assoc();
        $dashboardStats['total_reservations'] = $row['count'] ?? 0;
    }

    // Active reservations
    $result = $conn->query("SELECT COUNT(*) as count FROM reservations WHERE status IN ('pending', 'confirmed', 'checked_in')");
    if ($result) {
        $row = $result->fetch_assoc();
        $dashboardStats['active_reservations'] = $row['count'] ?? 0;
    }

    // Total service reservations
    $result = $conn->query("SELECT COUNT(*) as count FROM service_reservations");
    if ($result) {
        $row = $result->fetch_assoc();
        $dashboardStats['total_service_reservations'] = $row['count'] ?? 0;
    }

    // Active service reservations
    $result = $conn->query("SELECT COUNT(*) as count FROM service_reservations WHERE status IN ('pending', 'confirmed')");
    if ($result) {
        $row = $result->fetch_assoc();
        $dashboardStats['active_service_reservations'] = $row['count'] ?? 0;
    }

    // Checked-in guests
    $result = $conn->query("SELECT COUNT(*) as count FROM reservations WHERE status = 'checked_in'");
    if ($result) {
        $row = $result->fetch_assoc();
        $dashboardStats['checked_in_guests'] = $row['count'] ?? 0;
    }

    // Pending reservations
    $result = $conn->query("SELECT COUNT(*) as count FROM reservations WHERE status = 'pending'");
    if ($result) {
        $row = $result->fetch_assoc();
        $dashboardStats['pending_reservations'] = $row['count'] ?? 0;
    }

    // Pending service reservations
    $result = $conn->query("SELECT COUNT(*) as count FROM service_reservations WHERE status = 'pending'");
    if ($result) {
        $row = $result->fetch_assoc();
        $dashboardStats['pending_service_reservations'] = $row['count'] ?? 0;
    }

    // Total cost (sum of all reservation costs)
    $result = $conn->query("SELECT COALESCE(SUM(total_cost), 0) as total FROM reservations WHERE status IN ('confirmed', 'checked_in', 'checked_out')");
    if ($result) {
        $row = $result->fetch_assoc();
        $dashboardStats['total_cost'] = $row['total'] ?? 0;
    }

    $dashboardStats['total_active_bookings'] = (int)$dashboardStats['active_reservations'] + (int)$dashboardStats['active_service_reservations'];
    $dashboardStats['total_pending_reservations'] = (int)$dashboardStats['pending_reservations'] + (int)$dashboardStats['pending_service_reservations'];
} catch (Exception $e) {
    error_log("Error fetching dashboard stats: " . $e->getMessage());
}

// Get recent reservations
$recentReservations = [];
try {
    $sql = "SELECT r.*, u.first_name, u.last_name, u.email, u.phone, rm.room_number, rm.room_type
            FROM reservations r
            LEFT JOIN users u ON r.user_id = u.id
            LEFT JOIN rooms rm ON r.room_id = rm.id
            ORDER BY r.created_at DESC
            LIMIT 8";
    $result = $conn->query($sql);
    if ($result) {
        $recentReservations = $result->fetch_all(MYSQLI_ASSOC) ?? [];
    }
} catch (Exception $e) {
    error_log("Error fetching recent reservations: " . $e->getMessage());
}

// Get today's check-ins
$todaysCheckIns = [];
try {
    $today = date('Y-m-d');
    $sql = "SELECT r.*, u.first_name, u.last_name, u.email, u.phone, rm.room_number, rm.room_type
            FROM reservations r
            LEFT JOIN users u ON r.user_id = u.id
            LEFT JOIN rooms rm ON r.room_id = rm.id
            WHERE DATE(r.check_in_date) = '$today'
            ORDER BY r.created_at DESC
            LIMIT 5";
    $result = $conn->query($sql);
    if ($result) {
        $todaysCheckIns = $result->fetch_all(MYSQLI_ASSOC) ?? [];
    }
} catch (Exception $e) {
    error_log("Error fetching today's check-ins: " . $e->getMessage());
}

// Guest details for Total Guests section
$guestDetails = [];
try {
    $sql = "SELECT u.id, u.first_name, u.last_name, u.email, u.phone, u.created_at,
                   COUNT(DISTINCT r.id) AS room_bookings,
                   COUNT(DISTINCT sr.id) AS service_bookings
            FROM users u
            LEFT JOIN reservations r ON r.user_id = u.id
            LEFT JOIN service_reservations sr ON sr.user_id = u.id
            WHERE u.user_type = 'guest' AND u.is_active = 1
            GROUP BY u.id, u.first_name, u.last_name, u.email, u.phone, u.created_at
            ORDER BY u.created_at DESC
            LIMIT 8";
    $result = $conn->query($sql);
    if ($result) {
        $guestDetails = $result->fetch_all(MYSQLI_ASSOC) ?? [];
    }
} catch (Exception $e) {
    error_log("Error fetching guest details: " . $e->getMessage());
}

// Active room bookings details
$activeRoomBookings = [];
try {
    $sql = "SELECT r.id, r.status, r.check_in_date, r.check_out_date,
                   u.first_name, u.last_name, rm.room_number
            FROM reservations r
            LEFT JOIN users u ON r.user_id = u.id
            LEFT JOIN rooms rm ON r.room_id = rm.id
            WHERE r.status IN ('pending', 'confirmed', 'checked_in')
            ORDER BY r.created_at DESC
            LIMIT 6";
    $result = $conn->query($sql);
    if ($result) {
        $activeRoomBookings = $result->fetch_all(MYSQLI_ASSOC) ?? [];
    }
} catch (Exception $e) {
    error_log("Error fetching active room bookings: " . $e->getMessage());
}

// Active service bookings details
$activeServiceBookings = [];
try {
    $hasReservationDate = false;
    $hasReservationTime = false;
    $hasServiceStartDate = false;
    $hasServiceEndDate = false;

    $col = $conn->query("SHOW COLUMNS FROM service_reservations LIKE 'reservation_date'");
    $hasReservationDate = $col && $col->num_rows > 0;
    $col = $conn->query("SHOW COLUMNS FROM service_reservations LIKE 'reservation_time'");
    $hasReservationTime = $col && $col->num_rows > 0;
    $col = $conn->query("SHOW COLUMNS FROM service_reservations LIKE 'service_start_date'");
    $hasServiceStartDate = $col && $col->num_rows > 0;
    $col = $conn->query("SHOW COLUMNS FROM service_reservations LIKE 'service_end_date'");
    $hasServiceEndDate = $col && $col->num_rows > 0;

    $reservationDateExpr = $hasReservationDate
        ? "sr.reservation_date"
        : ($hasServiceStartDate ? "sr.service_start_date" : "NULL");
    $reservationTimeExpr = $hasReservationTime ? "sr.reservation_time" : "NULL";
    $serviceStartExpr = $hasServiceStartDate ? "sr.service_start_date" : "NULL";
    $serviceEndExpr = $hasServiceEndDate ? "sr.service_end_date" : "NULL";

    $sql = "SELECT sr.id, sr.status,
                   $reservationDateExpr AS reservation_date,
                   $reservationTimeExpr AS reservation_time,
                   $serviceStartExpr AS service_start_date,
                   $serviceEndExpr AS service_end_date,
                   u.first_name, u.last_name, f.name AS service_name
            FROM service_reservations sr
            LEFT JOIN users u ON sr.user_id = u.id
            LEFT JOIN facilities f ON sr.facility_id = f.id
            WHERE sr.status IN ('pending', 'confirmed')
            ORDER BY sr.created_at DESC
            LIMIT 6";
    $result = $conn->query($sql);
    if ($result) {
        $activeServiceBookings = $result->fetch_all(MYSQLI_ASSOC) ?? [];
    }
} catch (Exception $e) {
    error_log("Error fetching active service bookings: " . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Staff Dashboard | zemaraim Hotel Management</title>
    <link rel="icon" href="images/icon.webp" type="image/gif" sizes="16x16">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Staff dashboard for zemaraim hotel management system.">
    <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <link href="css/plugins.css" rel="stylesheet" type="text/css">
    <link href="css/style.css" rel="stylesheet" type="text/css">
    <link href="css/coloring.css" rel="stylesheet" type="text/css">
    <link href="css/staff-dashboard.css" rel="stylesheet" type="text/css">
    <link id="colors" href="css/colors/scheme-01.css" rel="stylesheet" type="text/css">
</head>

<body class="light">
    <!-- Header/Navbar -->
    <nav class="staff-navbar navbar navbar-expand-lg navbar-dark">
        <div class="container-fluid px-3 px-md-4">
            <a class="navbar-brand d-flex align-items-center" href="index.php">
                <img src="images/zt_history_logo.png" alt="zemaraim" class="navbar-logo me-2">
                <span class="navbar-title">zemaraim Staff</span>
            </a>

            <button class="navbar-toggler" type="button" id="mobileSidebarToggle" aria-controls="staffSidebarNav" aria-expanded="false" aria-label="Toggle sidebar navigation">
                <span class="navbar-toggler-icon"></span>
            </button>

            <div class="collapse navbar-collapse" id="staffNavbar">
                <ul class="navbar-nav ms-auto align-items-lg-center gap-2">
                    
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="staffDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="icofont-user"></i> <span id="navbarStaffName"><?php echo htmlspecialchars($currentUser['first_name'] ?? 'Staff'); ?></span>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="staffDropdown">
                            <li><a class="dropdown-item" href="dashboard.php?tab=profile"><i class="icofont-edit"></i> My Profile</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item text-danger" href="logout.php"><i class="icofont-logout"></i> Logout</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- Main Content with Sidebar -->
    <div class="staff-dashboard-container">
        <div class="staff-dashboard-wrapper">
            <!-- Left Sidebar -->
            <aside class="staff-sidebar" id="staffSidebarNav">
                <div class="sidebar-header">
                    <h3 class="sidebar-title">
                        <i class="icofont-navigation-menu"></i> Menu
                    </h3>
                    <button class="btn-close-sidebar" id="closeSidebar" aria-label="Close sidebar">
                        <i class="icofont-close"></i>
                    </button>
                </div>

                <!-- Sidebar Navigation -->
                <nav class="sidebar-nav">
                    <!-- Main Sections Navigation -->
                    <div class="nav-section">
                        <h4 class="nav-section-title">Dashboard</h4>
                        <ul class="nav-list">
                            <li>
                                <a href="#" class="nav-link sidebar-section-link active" data-section="overview">
                                    <i class="icofont-dashboard-web"></i>
                                    <span>Overview</span>
                                </a>
                            </li>
                            <li>
                                <a href="#" class="nav-link sidebar-section-link" data-section="rooms">
                                    <i class="icofont-door"></i>
                                    <span>Room Reservations</span>
                                    <span class="badge bg-success ms-auto" id="roomResBadge">0</span>
                                </a>
                            </li>
                            <li>
                                <a href="#" class="nav-link sidebar-section-link" data-section="services">
                                    <i class="icofont-tasks"></i>
                                    <span>Service Reservations</span>
                                    <span class="badge bg-info ms-auto" id="serviceResBadge">0</span>
                                </a>
                            </li>
                            <li>
                                <a href="#" class="nav-link sidebar-section-link" data-section="guests">
                                    <i class="icofont-users-alt-5"></i>
                                    <span>Guest List</span>
                                    <span class="nav-count ms-auto" id="sidebarGuests">0</span>
                                </a>
                            </li>
                            <li>
                                <a href="#" class="nav-link sidebar-section-link" data-section="profile">
                                    <i class="icofont-user-alt-3"></i>
                                    <span>Profile</span>
                                </a>
                            </li>
                            <li>
                                <a href="#" class="nav-link sidebar-section-link" data-section="active">
                                    <i class="icofont-check-alt"></i>
                                    <span>Active Bookings</span>
                                    <span class="nav-count ms-auto" id="sidebarActive">0</span>
                                </a>
                            </li>
                            <li>
                                <a href="#" class="nav-link sidebar-section-link" data-section="pending">
                                    <i class="icofont-exclamation"></i>
                                    <span>Pending</span>
                                    <span class="badge bg-warning ms-auto" id="sidebarPending">0</span>
                                </a>
                            </li>
                            <li>
                                <a href="logout.php" class="nav-link text-danger">
                                    <i class="icofont-exit"></i>
                                    <span>Logout</span>
                                </a>
                            </li>
                        </ul>
                    </div>
                </nav>
            </aside>

            <!-- Toggle Sidebar Button (Mobile) -->
            <button class="btn-toggle-sidebar" id="toggleSidebar" aria-label="Toggle sidebar">
                <i class="icofont-navigation-menu"></i>
            </button>
            <div class="sidebar-backdrop" id="sidebarBackdrop"></div>

            <!-- Main Content Area -->
            <main class="staff-main-content">
                <div class="container-fluid px-0">
                    <!-- SECTION 1: OVERVIEW -->
                    <section class="dashboard-section section-active" id="overview" data-section="overview">
                        <div class="section-header">
                            <div class="container-fluid px-3 px-md-4 py-4">
                                <h3 class="section-title">
                                    <i class="icofont-dashboard-web"></i> Dashboard Overview
                                </h3>
                                <p class="section-subtitle">Daily performance summary and latest bookings</p>
                            </div>
                        </div>

                        <div class="section-content">
                            <div class="container-fluid px-3 px-md-4 py-4">

                        <!-- Welcome Section -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <div class="staff-welcome-card">
                                    <div class="welcome-content">
                                        <h2 class="welcome-title">
                                            <i class="icofont-hand-hold-tab"></i> Welcome, <span id="welcomeStaffName"><?php echo htmlspecialchars($currentUser['first_name'] ?? 'Staff'); ?></span>!
                                        </h2>
                                        <p class="welcome-subtitle">Here's what's happening at zemaraim today</p>
                                    </div>
                                    <div class="welcome-date">
                                        <span class="current-date" id="currentDate"></span>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Statistics Cards -->
                        <div class="row mb-4 g-3 g-md-4">
                            <div class="col-12 col-sm-6 col-lg-4 col-xl">
                                <div class="stat-card stat-card-guests">
                                    <div class="stat-icon">
                                        <i class="icofont-users-alt-5"></i>
                                    </div>
                                    <div class="stat-content">
                                        <h3 class="stat-number" id="overviewTotalGuests"><?php echo $dashboardStats['total_guests']; ?></h3>
                                        <p class="stat-label">Total Guests</p>
                                    </div>
                                </div>
                            </div>

                            <div class="col-12 col-sm-6 col-lg-4 col-xl">
                                <div class="stat-card stat-card-reservations">
                                    <div class="stat-icon">
                                        <i class="icofont-calendar"></i>
                                    </div>
                                    <div class="stat-content">
                                        <h3 class="stat-number" id="overviewRoomReservations"><?php echo $dashboardStats['total_reservations']; ?></h3>
                                        <p class="stat-label">Room Reservations</p>
                                    </div>
                                </div>
                            </div>

                            <div class="col-12 col-sm-6 col-lg-4 col-xl">
                                <div class="stat-card stat-card-service">
                                    <div class="stat-icon">
                                        <i class="icofont-ui-calendar"></i>
                                    </div>
                                    <div class="stat-content">
                                        <h3 class="stat-number" id="overviewServiceReservations"><?php echo $dashboardStats['total_service_reservations']; ?></h3>
                                        <p class="stat-label">Service Reservations</p>
                                    </div>
                                </div>
                            </div>

                            <div class="col-12 col-sm-6 col-lg-4 col-xl">
                                <div class="stat-card stat-card-active">
                                    <div class="stat-icon">
                                        <i class="icofont-check-alt"></i>
                                    </div>
                                    <div class="stat-content">
                                        <h3 class="stat-number" id="overviewActiveBookings"><?php echo $dashboardStats['total_active_bookings']; ?></h3>
                                        <p class="stat-label">Active Bookings</p>
                                    </div>
                                </div>
                            </div>

                            <div class="col-12 col-sm-6 col-lg-4 col-xl">
                                <div class="stat-card stat-card-checkin">
                                    <div class="stat-icon">
                                        <i class="icofont-sign-in"></i>
                                    </div>
                                    <div class="stat-content">
                                        <h3 class="stat-number" id="overviewCheckedInGuests"><?php echo $dashboardStats['checked_in_guests']; ?></h3>
                                        <p class="stat-label">Checked In</p>
                                    </div>
                                </div>
                            </div>

                            <div class="col-12 col-sm-6 col-lg-4 col-xl">
                                <div class="stat-card stat-card-reservations">
                                    <div class="stat-icon">
                                        <i class="icofont-money"></i>
                                    </div>
                                    <div class="stat-content">
                                        <h3 class="stat-number" id="overviewTotalCost">$<?php echo number_format($dashboardStats['total_cost'], 2); ?></h3>
                                        <p class="stat-label">Total Revenue</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </section>

                    <!-- SECTION 2: ROOM RESERVATIONS -->
                    <section class="dashboard-section" id="rooms" data-section="rooms">
                        <div class="section-header">
                            <div class="container-fluid px-3 px-md-4 py-4">
                                <h3 class="section-title">
                                    <i class="icofont-door"></i> Room Reservations
                                </h3>
                                <p class="section-subtitle">Manage all room bookings and check-in status</p>
                            </div>
                        </div>

                        <div class="section-content">
                            <div class="container-fluid px-3 px-md-4 py-4">
                                <div class="row g-3 g-md-4">
                                    <div class="col-12">
                                        <div class="dashboard-card">
                                            <div class="card-header">
                                                <h4 class="card-title">
                                                    <i class="icofont-bed"></i> All Room Reservations
                                                </h4>
                                                <span class="badge bg-success" id="roomResCount">0</span>
                                            </div>
                                            <div class="card-body">
                                                <div id="roomResContainer" class="reservations-list">
                                                    <div class="loading-state">
                                                        <i class="icofont-refresh"></i>
                                                        <p>Loading room reservations...</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </section>

                    <!-- SECTION 3: SERVICE RESERVATIONS -->
                    <section class="dashboard-section" id="services" data-section="services">
                        <div class="section-header">
                            <div class="container-fluid px-3 px-md-4 py-4">
                                <h3 class="section-title">
                                    <i class="icofont-tasks"></i> Service Reservations
                                </h3>
                                <p class="section-subtitle">Manage hotel services and bookings</p>
                            </div>
                        </div>

                        <div class="section-content">
                            <div class="container-fluid px-3 px-md-4 py-4">
                                <div class="row g-3 g-md-4">
                                    <div class="col-12">
                                        <div class="dashboard-card">
                                            <div class="card-header">
                                                <h4 class="card-title">
                                                    <i class="icofont-tasks"></i> All Service Reservations
                                                </h4>
                                                <span class="badge bg-info" id="serviceResCount">0</span>
                                            </div>
                                            <div class="card-body">
                                                <div id="serviceResContainer" class="reservations-list">
                                                    <div class="loading-state">
                                                        <i class="icofont-refresh"></i>
                                                        <p>Loading service reservations...</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </section>

                    <!-- SECTION 4: GUEST LIST -->
                    <section class="dashboard-section" id="guests" data-section="guests">
                        <div class="section-header">
                            <div class="container-fluid px-3 px-md-4 py-4">
                                <h3 class="section-title">
                                    <i class="icofont-users-alt-5"></i> Guest List
                                </h3>
                                <p class="section-subtitle">View all registered guests and their activity</p>
                            </div>
                        </div>

                        <div class="section-content">
                            <div class="container-fluid px-3 px-md-4 py-4">
                                <div class="row g-3 g-md-4">
                                    <div class="col-12">
                                        <div class="dashboard-card">
                                            <div class="card-header">
                                                <h4 class="card-title">
                                                    <i class="icofont-users-social"></i> Guest Details
                                                </h4>
                                                <span class="badge bg-primary"><?php echo count($guestDetails); ?></span>
                                            </div>
                                            <div class="card-body">
                                                <?php if (count($guestDetails) > 0): ?>
                                                <div class="guest-details-grid">
                                                    <?php foreach ($guestDetails as $guest): ?>
                                                    <div class="guest-detail-item">
                                                        <h5 class="guest-name"><?php echo htmlspecialchars($guest['first_name'] ?? 'N/A') . ' ' . htmlspecialchars($guest['last_name'] ?? 'N/A'); ?></h5>
                                                        <p><i class="icofont-email"></i> <?php echo htmlspecialchars($guest['email'] ?? 'N/A'); ?></p>
                                                        <p><i class="icofont-phone"></i> <?php echo htmlspecialchars($guest['phone'] ?? 'N/A'); ?></p>
                                                        <p><i class="icofont-bed"></i> Room Bookings: <?php echo (int)($guest['room_bookings'] ?? 0); ?></p>
                                                        <p><i class="icofont-ui-calendar"></i> Service Bookings: <?php echo (int)($guest['service_bookings'] ?? 0); ?></p>
                                                    </div>
                                                    <?php endforeach; ?>
                                                </div>
                                                <?php else: ?>
                                                <div class="empty-state">
                                                    <i class="icofont-users-alt-5"></i>
                                                    <p>No guest details available</p>
                                                </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </section>

                    <!-- SECTION 5: PROFILE -->
                    <section class="dashboard-section" id="profile" data-section="profile">
                        <div class="section-header">
                            <div class="container-fluid px-3 px-md-4 py-4">
                                <h3 class="section-title">
                                    <i class="icofont-user-alt-3"></i> My Profile
                                </h3>
                                <p class="section-subtitle">Update your personal details and password in real time</p>
                            </div>
                        </div>

                        <div class="section-content">
                            <div class="container-fluid px-3 px-md-4 py-4">
                                <div class="row g-3 g-md-4">
                                    <!-- Profile Image Section -->
                                    <div class="col-12 col-lg-5 col-xl-4">
                                        <div class="dashboard-card">
                                            <div class="card-header">
                                                <h4 class="card-title">
                                                    <i class="icofont-camera"></i> Profile Photo
                                                </h4>
                                            </div>
                                            <div class="card-body">
                                                <div class="profile-image-section">
                                                    <div class="profile-image-wrapper">
                                                        <img id="profileImagePreview" class="profile-image" src="images/default-avatar.png" alt="Profile Image">
                                                        <div class="profile-image-overlay">
                                                            <span class="upload-icon"><i class="icofont-camera"></i></span>
                                                        </div>
                                                    </div>
                                                    <input type="file" id="profileImageInput" name="profile_image" accept="image/*" style="display: none;">
                                                    <button type="button" class="btn btn-primary btn-sm w-100 mt-3" id="profileImageUploadBtn">
                                                        <i class="icofont-upload-alt"></i> Choose Photo
                                                    </button>
                                                    <p class="image-info">Recommended: 400x400px, Max 5MB</p>
                                                    <div id="imageUploadStatus" class="mt-3"></div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Profile Details Section -->
                                    <div class="col-12 col-lg-7 col-xl-5">
                                        <div class="dashboard-card">
                                            <div class="card-header">
                                                <h4 class="card-title">
                                                    <i class="icofont-edit"></i> Profile Details
                                                </h4>
                                            </div>
                                            <div class="card-body">
                                                <form id="staffProfileForm" class="profile-form">
                                                    <div class="profile-grid">
                                                        <div class="profile-field">
                                                            <label for="profileFirstName">First Name</label>
                                                            <input type="text" class="form-control" id="profileFirstName" name="first_name" required>
                                                        </div>
                                                        <div class="profile-field">
                                                            <label for="profileLastName">Last Name</label>
                                                            <input type="text" class="form-control" id="profileLastName" name="last_name" required>
                                                        </div>
                                                        <div class="profile-field">
                                                            <label for="profileEmail">Email</label>
                                                            <input type="email" class="form-control" id="profileEmail" name="email" required>
                                                        </div>
                                                        <div class="profile-field">
                                                            <label for="profilePhone">Phone</label>
                                                            <input type="text" class="form-control" id="profilePhone" name="phone">
                                                        </div>
                                                        <div class="profile-field profile-field-wide">
                                                            <label>Member Since</label>
                                                            <input type="text" class="form-control" id="profileMemberSince" readonly>
                                                        </div>
                                                    </div>
                                                    <div class="profile-actions">
                                                        <button type="submit" class="btn btn-success" id="profileSaveBtn">
                                                            <i class="icofont-check"></i> Save Profile
                                                        </button>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Change Password Section -->
                                    <div class="col-12 col-lg-12 col-xl-3">
                                        <div class="dashboard-card">
                                            <div class="card-header">
                                                <h4 class="card-title">
                                                    <i class="icofont-lock"></i> Change Password
                                                </h4>
                                            </div>
                                            <div class="card-body">
                                                <form id="staffPasswordForm" class="profile-form">
                                                    <div class="profile-grid profile-grid-single">
                                                        <div class="profile-field">
                                                            <label for="currentPassword">Current Password</label>
                                                            <input type="password" class="form-control" id="currentPassword" name="current_password" required>
                                                        </div>
                                                        <div class="profile-field">
                                                            <label for="newPassword">New Password</label>
                                                            <input type="password" class="form-control" id="newPassword" name="new_password" minlength="8" required>
                                                        </div>
                                                        <div class="profile-field">
                                                            <label for="confirmPassword">Confirm New Password</label>
                                                            <input type="password" class="form-control" id="confirmPassword" name="confirm_password" minlength="8" required>
                                                        </div>
                                                    </div>
                                                    <div class="profile-actions">
                                                        <button type="submit" class="btn btn-warning w-100" id="passwordSaveBtn">
                                                            <i class="icofont-refresh"></i> Update Password
                                                        </button>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </section>

                    <!-- SECTION 6: ACTIVE BOOKINGS -->
                    <section class="dashboard-section" id="active" data-section="active">
                        <div class="section-header">
                            <div class="container-fluid px-3 px-md-4 py-4">
                                <h3 class="section-title">
                                    <i class="icofont-check-alt"></i> Active Bookings
                                </h3>
                                <p class="section-subtitle">Current room and service reservations</p>
                            </div>
                        </div>

                        <div class="section-content">
                            <div class="container-fluid px-3 px-md-4 py-4">
                                <div class="row g-3 g-md-4">
                                    <div class="col-12 col-xl-6">
                                        <div class="dashboard-card">
                                            <div class="card-header">
                                                <h4 class="card-title">
                                                    <i class="icofont-bed"></i> Active Room Bookings
                                                </h4>
                                                <span class="badge bg-success"><?php echo (int)$dashboardStats['active_reservations']; ?></span>
                                            </div>
                                            <div class="card-body">
                                                <?php if (count($activeRoomBookings) > 0): ?>
                                                <div class="active-bookings-list">
                                                    <?php foreach ($activeRoomBookings as $booking): ?>
                                                    <div class="active-booking-item">
                                                        <h5><?php echo htmlspecialchars($booking['first_name'] ?? 'N/A') . ' ' . htmlspecialchars($booking['last_name'] ?? 'N/A'); ?></h5>
                                                        <p><i class="icofont-door"></i> Room <?php echo htmlspecialchars($booking['room_number'] ?? 'N/A'); ?></p>
                                                        <p><i class="icofont-calendar"></i> <?php echo date('M d', strtotime($booking['check_in_date'])) . ' - ' . date('M d', strtotime($booking['check_out_date'])); ?></p>
                                                        <span class="status-badge status-<?php echo strtolower($booking['status']); ?>"><?php echo ucfirst(str_replace('_', ' ', $booking['status'])); ?></span>
                                                    </div>
                                                    <?php endforeach; ?>
                                                </div>
                                                <?php else: ?>
                                                <div class="empty-state">
                                                    <i class="icofont-bed"></i>
                                                    <p>No active room bookings</p>
                                                </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="col-12 col-xl-6">
                                        <div class="dashboard-card">
                                            <div class="card-header">
                                                <h4 class="card-title">
                                                    <i class="icofont-tasks"></i> Active Service Bookings
                                                </h4>
                                                <span class="badge bg-info"><?php echo (int)$dashboardStats['active_service_reservations']; ?></span>
                                            </div>
                                            <div class="card-body">
                                                <?php if (count($activeServiceBookings) > 0): ?>
                                                <div class="active-bookings-list">
                                                    <?php foreach ($activeServiceBookings as $booking): ?>
                                                    <div class="active-booking-item service">
                                                        <h5><?php echo htmlspecialchars($booking['first_name'] ?? 'N/A') . ' ' . htmlspecialchars($booking['last_name'] ?? 'N/A'); ?></h5>
                                                        <p><i class="icofont-ui-calendar"></i> <?php echo htmlspecialchars($booking['service_name'] ?? 'Service'); ?></p>
                                                        <p><i class="icofont-calendar"></i>
                                                            <?php
                                                            $bookingDate = $booking['reservation_date'] ?? $booking['service_start_date'] ?? null;
                                                            $bookingEndDate = $booking['service_end_date'] ?? null;
                                                            $bookingTime = $booking['reservation_time'] ?? '';
                                                            if (!empty($bookingDate)) {
                                                                echo date('M d, Y', strtotime($bookingDate));
                                                                if (!empty($bookingEndDate) && $bookingEndDate !== $bookingDate) {
                                                                    echo ' - ' . date('M d, Y', strtotime($bookingEndDate));
                                                                }
                                                            } else {
                                                                echo 'Date not available';
                                                            }
                                                            if (!empty($bookingTime)) {
                                                                echo ' ' . htmlspecialchars($bookingTime);
                                                            }
                                                            ?>
                                                        </p>
                                                        <span class="status-badge status-<?php echo strtolower($booking['status']); ?>"><?php echo ucfirst(str_replace('_', ' ', $booking['status'])); ?></span>
                                                    </div>
                                                    <?php endforeach; ?>
                                                </div>
                                                <?php else: ?>
                                                <div class="empty-state">
                                                    <i class="icofont-tasks"></i>
                                                    <p>No active service bookings</p>
                                                </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </section>

                    <!-- SECTION 7: PENDING -->
                    <section class="dashboard-section" id="pending" data-section="pending">
                        <div class="section-header">
                            <div class="container-fluid px-3 px-md-4 py-4">
                                <h3 class="section-title">
                                    <i class="icofont-exclamation"></i> Pending Confirmations
                                </h3>
                                <p class="section-subtitle">Reservations awaiting approval</p>
                            </div>
                        </div>

                        <div class="section-content">
                            <div class="container-fluid px-3 px-md-4 py-4">
                                <div class="row g-3 g-md-4">
                                    <div class="col-12">
                                        <div class="dashboard-card">
                                            <div class="card-header">
                                                <h4 class="card-title">
                                                    <i class="icofont-exclamation"></i> Pending Reservations
                                                </h4>
                                                <span class="badge bg-warning" id="pendingCount"><?php echo $dashboardStats['total_pending_reservations']; ?></span>
                                            </div>
                                            <div class="card-body">
                                                <div id="pendingResContainer" class="reservations-list">
                                                    <div class="loading-state">
                                                        <i class="icofont-refresh"></i>
                                                        <p>Loading pending reservations...</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </section>
                </div>
            </main>
        </div>
    </div>

    <!-- Footer -->
    <footer class="staff-footer">
        <div class="container-fluid px-3 px-md-4">
            <p class="mb-0">&copy; 2026 zemaraim Hotel Management. All rights reserved.</p>
        </div>
    </footer>

    <!-- Service Reservation Details Modal -->
    <div class="modal fade" id="serviceReservationModal" tabindex="-1" aria-labelledby="serviceReservationModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg service-res-modal-dialog">
            <div class="modal-content service-res-modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="serviceReservationModalLabel">
                        <i class="icofont-tasks"></i> Service Reservation Details
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="service-details-grid">
                        <div class="service-detail-card">
                            <label>Reservation ID</label>
                            <p id="serviceDetailId">-</p>
                        </div>
                        <div class="service-detail-card">
                            <label>Status</label>
                            <p id="serviceDetailStatus">-</p>
                        </div>
                        <div class="service-detail-card">
                            <label>Service</label>
                            <p id="serviceDetailName">-</p>
                        </div>
                        <div class="service-detail-card">
                            <label>Schedule</label>
                            <p id="serviceDetailSchedule">-</p>
                        </div>
                        <div class="service-detail-card">
                            <label>Total Price</label>
                            <p id="serviceDetailTotalPrice">-</p>
                        </div>
                        <div class="service-detail-card">
                            <label>Payment Status</label>
                            <p id="serviceDetailPaymentStatus">-</p>
                        </div>
                        <div class="service-detail-card">
                            <label>Guest Name</label>
                            <p id="serviceDetailGuest">-</p>
                        </div>
                        <div class="service-detail-card">
                            <label>Email</label>
                            <p id="serviceDetailEmail">-</p>
                        </div>
                        <div class="service-detail-card service-detail-card-wide">
                            <label>Phone</label>
                            <p id="serviceDetailPhone">-</p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Room Reservation Details Modal -->
    <div class="modal fade" id="roomReservationModal" tabindex="-1" aria-labelledby="roomReservationModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg service-res-modal-dialog">
            <div class="modal-content service-res-modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="roomReservationModalLabel">
                        <i class="icofont-bed"></i> Room Reservation Details
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="service-details-grid">
                        <div class="service-detail-card">
                            <label>Reservation ID</label>
                            <p id="roomDetailId">-</p>
                        </div>
                        <div class="service-detail-card">
                            <label>Status</label>
                            <p id="roomDetailStatus">-</p>
                        </div>
                        <div class="service-detail-card">
                            <label>Room</label>
                            <p id="roomDetailRoom">-</p>
                        </div>
                        <div class="service-detail-card">
                            <label>Guests</label>
                            <p id="roomDetailGuests">-</p>
                        </div>
                        <div class="service-detail-card">
                            <label>Check-in</label>
                            <p id="roomDetailCheckIn">-</p>
                        </div>
                        <div class="service-detail-card">
                            <label>Check-out</label>
                            <p id="roomDetailCheckOut">-</p>
                        </div>
                        <div class="service-detail-card">
                            <label>Total Price</label>
                            <p id="roomDetailTotalPrice">-</p>
                        </div>
                        <div class="service-detail-card">
                            <label>Payment Status</label>
                            <p id="roomDetailPaymentStatus">-</p>
                        </div>
                        <div class="service-detail-card">
                            <label>Guest Name</label>
                            <p id="roomDetailGuest">-</p>
                        </div>
                        <div class="service-detail-card">
                            <label>Email</label>
                            <p id="roomDetailEmail">-</p>
                        </div>
                        <div class="service-detail-card service-detail-card-wide">
                            <label>Phone</label>
                            <p id="roomDetailPhone">-</p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="js/jquery-3.6.0.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/staff-utils.js"></script>
    <script>
        // Update current date
        function updateDate() {
            const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
            const today = new Date();
            document.getElementById('currentDate').textContent = today.toLocaleDateString('en-US', options);
        }
        updateDate();

        // ==========================================
        // SECTION SWITCHING
        // ==========================================
        const sectionLinks = document.querySelectorAll('.sidebar-section-link');
        const dashboardSections = document.querySelectorAll('.dashboard-section');

        sectionLinks.forEach(link => {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                const targetSection = this.dataset.section;
                
                // Remove active class from all links
                sectionLinks.forEach(l => l.classList.remove('active'));
                
                // Add active class to clicked link
                this.classList.add('active');
                
                // Hide all sections
                dashboardSections.forEach(section => {
                    section.classList.remove('section-active');
                    section.style.display = 'none';
                });
                
                // Show target section
                const target = document.getElementById(targetSection);
                if (target) {
                    target.style.display = 'block';
                    target.classList.add('section-active');
                    // Animate entrance
                    setTimeout(() => {
                        target.style.opacity = '1';
                    }, 10);
                }
                
                // Close sidebar on mobile
                if (window.innerWidth < 768) {
                    closeSidebar();
                }
                
                // Load data for specific sections
                if (targetSection === 'rooms') {
                    loadRoomReservations();
                } else if (targetSection === 'services') {
                    loadServiceReservations();
                } else if (targetSection === 'pending') {
                    loadPendingReservations();
                } else if (targetSection === 'profile') {
                    loadStaffProfile();
                }
            });
        });

        // ==========================================
        // SIDEBAR FUNCTIONALITY
        // ==========================================

        const staffSidebar = document.querySelector('.staff-sidebar');
        const sidebarBackdrop = document.getElementById('sidebarBackdrop');
        const toggleSidebarBtn = document.getElementById('toggleSidebar');
        const closeSidebarBtn = document.getElementById('closeSidebar');
        const mobileSidebarToggleBtn = document.getElementById('mobileSidebarToggle');
        const staffNavbar = document.querySelector('.staff-navbar');

        function syncNavbarHeightVar() {
            if (!staffNavbar) return;
            const navHeight = Math.ceil(staffNavbar.offsetHeight || 76);
            document.documentElement.style.setProperty('--staff-navbar-height', navHeight + 'px');
        }
        syncNavbarHeightVar();

        // Toggle sidebar on mobile
        function openSidebar() {
            if (!staffSidebar || !sidebarBackdrop) return;
            staffSidebar.classList.add('open');
            sidebarBackdrop.classList.add('show');
            document.body.classList.add('sidebar-open');
            if (mobileSidebarToggleBtn) {
                mobileSidebarToggleBtn.setAttribute('aria-expanded', 'true');
            }
        }

        function closeSidebar() {
            if (!staffSidebar || !sidebarBackdrop) return;
            staffSidebar.classList.remove('open');
            sidebarBackdrop.classList.remove('show');
            document.body.classList.remove('sidebar-open');
            if (mobileSidebarToggleBtn) {
                mobileSidebarToggleBtn.setAttribute('aria-expanded', 'false');
            }
        }

        function isMobileOrTablet() {
            return window.innerWidth <= 1024;
        }

        if (toggleSidebarBtn) {
            toggleSidebarBtn.addEventListener('click', openSidebar);
        }
        if (mobileSidebarToggleBtn) {
            mobileSidebarToggleBtn.addEventListener('click', function(e) {
                if (isMobileOrTablet()) {
                    e.preventDefault();
                    if (staffSidebar && staffSidebar.classList.contains('open')) {
                        closeSidebar();
                    } else {
                        openSidebar();
                    }
                }
            });
        }
        if (closeSidebarBtn) {
            closeSidebarBtn.addEventListener('click', closeSidebar);
        }
        if (sidebarBackdrop) {
            sidebarBackdrop.addEventListener('click', closeSidebar);
        }

        window.addEventListener('resize', function() {
            syncNavbarHeightVar();
            if (!isMobileOrTablet()) {
                closeSidebar();
            }
        });

        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && staffSidebar && staffSidebar.classList.contains('open')) {
                closeSidebar();
            }
        });

        // Close sidebar when clicking on a sidebar link
        document.querySelectorAll('.sidebar-nav .nav-link').forEach(link => {
            link.addEventListener('click', function(e) {
                if (window.innerWidth < 768) {
                    closeSidebar();
                }
            });
        });

        // Load room reservations
        function loadRoomReservations() {
            const container = document.getElementById('roomResContainer');
            StaffUtils.getStaffData('get_room_reservations', {status: 'all'}).then(response => {
                if(response.success) {
                    displayRoomReservations(response.data);
                } else {
                    console.error('Error loading room reservations');
                    if (container) {
                        container.innerHTML = '<div class="empty-state"><i class="icofont-warning"></i><p>Unable to load room reservations</p></div>';
                    }
                }
            });
        }

        // Load service reservations
        function loadServiceReservations() {
            const container = document.getElementById('serviceResContainer');
            StaffUtils.getStaffData('get_service_reservations', {status: 'all'}).then(response => {
                if(response.success) {
                    displayServiceReservations(response.data);
                } else {
                    console.error('Error loading service reservations');
                    if (container) {
                        container.innerHTML = '<div class="empty-state"><i class="icofont-warning"></i><p>Unable to load service reservations</p></div>';
                    }
                }
            });
        }

        // Load pending reservations
        function loadPendingReservations() {
            const container = document.getElementById('pendingResContainer');
            Promise.all([
                StaffUtils.getStaffData('get_room_reservations', {status: 'pending'}),
                StaffUtils.getStaffData('get_service_reservations', {status: 'pending'})
            ]).then(([roomResponse, serviceResponse]) => {
                const roomPending = roomResponse && roomResponse.success ? (roomResponse.data || []) : [];
                const servicePending = serviceResponse && serviceResponse.success ? (serviceResponse.data || []) : [];

                if (!(roomResponse && roomResponse.success) && !(serviceResponse && serviceResponse.success)) {
                    console.error('Error loading pending reservations');
                    if (container) {
                        container.innerHTML = '<div class="empty-state"><i class="icofont-warning"></i><p>Unable to load pending reservations</p></div>';
                    }
                    return;
                }

                const mergedPending = [
                    ...roomPending.map(item => ({...item, reservation_type: 'room'})),
                    ...servicePending.map(item => ({...item, reservation_type: 'service'}))
                ];

                displayPendingReservations(mergedPending);
            });
        }

        function loadStaffProfile() {
            StaffUtils.getStaffData('get_staff_profile').then(response => {
                if (!response || !response.success || !response.data) {
                    return;
                }

                const profile = response.data;
                const firstName = profile.first_name || '';
                const lastName = profile.last_name || '';
                const firstNameEl = document.getElementById('profileFirstName');
                const lastNameEl = document.getElementById('profileLastName');
                const emailEl = document.getElementById('profileEmail');
                const phoneEl = document.getElementById('profilePhone');
                const memberSinceEl = document.getElementById('profileMemberSince');
                const profileImageEl = document.getElementById('profileImagePreview');
                const navbarNameEl = document.getElementById('navbarStaffName');
                const welcomeNameEl = document.getElementById('welcomeStaffName');

                if (firstNameEl) firstNameEl.value = firstName;
                if (lastNameEl) lastNameEl.value = lastName;
                if (emailEl) emailEl.value = profile.email || '';
                if (phoneEl) phoneEl.value = profile.phone || '';
                if (memberSinceEl) memberSinceEl.value = profile.created_at ? formatDate(profile.created_at) : '-';
                if (profileImageEl) {
                    const profilePicture = (profile.profile_picture || '').toString().trim();
                    const hasCustomImage = profilePicture !== '';
                    const cacheBuster = 't=' + Date.now();
                    profileImageEl.src = hasCustomImage
                        ? `${profilePicture}${profilePicture.includes('?') ? '&' : '?'}${cacheBuster}`
                        : `images/default-avatar.png?${cacheBuster}`;
                }
                if (navbarNameEl) navbarNameEl.textContent = firstName || 'Staff';
                if (welcomeNameEl) welcomeNameEl.textContent = firstName || 'Staff';
            });
        }

        // Display room reservations
        function displayRoomReservations(data) {
            const container = document.getElementById('roomResContainer');
            const count = document.getElementById('roomResCount');
            const badge = document.getElementById('roomResBadge');
            
            count.textContent = data.length;
            badge.textContent = data.length;

            if(data.length === 0) {
                container.innerHTML = '<div class="empty-state"><i class="icofont-calendar"></i><p>No room reservations</p></div>';
                return;
            }

            container.innerHTML = data.map(res => `
                ${(() => {
                    const statusValue = (res.status || '').toLowerCase();
                    const isLocked = statusValue === 'checked_out' || statusValue === 'cancelled';
                    const paymentStatusValue = (res.payment_status || 'unpaid').toLowerCase();
                    const isPaymentLocked = paymentStatusValue === 'paid';
                    return `
                <div class="reservation-item pending-mixed-item">
                    <div class="reservation-header">
                        <h5 class="reservation-title">${res.guest_name}</h5>
                        <span class="status-badge status-${statusValue}">${capitalize(statusValue.replace('_', ' '))}</span>
                    </div>
                    <div class="reservation-details">
                        <p><i class="icofont-door"></i> <strong>Room:</strong> ${res.room_number}</p>
                        <p><i class="icofont-calendar"></i> <strong>Check-in:</strong> ${formatDate(res.check_in_date)}</p>
                        <p><i class="icofont-calendar"></i> <strong>Check-out:</strong> ${formatDate(res.check_out_date)}</p>
                        <p><i class="icofont-users-alt-5"></i> <strong>Guests:</strong> ${res.number_of_guests}</p>
                        <p><i class="icofont-money"></i> <strong>Total Price:</strong> ${formatCurrency(res.total_price)}</p>
                        <p><i class="icofont-credit-card"></i> <strong>Payment:</strong> <span class="payment-badge payment-${paymentStatusValue}">${capitalize(paymentStatusValue.replace('_', ' '))}</span></p>
                    </div>
                    <div class="reservation-actions reservation-actions-wrap">
                        <select class="form-select form-select-sm status-select" data-type="room" data-id="${res.id}" ${isLocked ? 'disabled' : ''}>
                            ${renderStatusOptions(['pending', 'confirmed', 'checked_in', 'checked_out', 'cancelled'], statusValue)}
                        </select>
                        <button type="button" class="btn btn-sm btn-success status-update-btn" data-type="room" data-id="${res.id}" ${isLocked ? 'disabled' : ''}>
                            <i class="icofont-refresh"></i> ${isLocked ? 'Locked' : 'Update Status'}
                        </button>
                        <select class="form-select form-select-sm payment-select" data-type="room" data-id="${res.id}" ${isPaymentLocked ? 'disabled' : ''}>
                            ${renderStatusOptions(['unpaid', 'partial', 'paid'], paymentStatusValue)}
                        </select>
                        <button type="button" class="btn btn-sm btn-warning payment-update-btn" data-type="room" data-id="${res.id}" ${isPaymentLocked ? 'disabled' : ''}>
                            <i class="icofont-credit-card"></i> ${isPaymentLocked ? 'Paid Locked' : 'Update Payment'}
                        </button>
                        <button type="button" class="btn btn-sm btn-primary room-view-btn"
                            data-id="${res.id}"
                            data-status="${statusValue}"
                            data-room-number="${res.room_number || 'N/A'}"
                            data-room-type="${res.room_type || ''}"
                            data-guests="${res.number_of_guests || '0'}"
                            data-check-in="${res.check_in_date || ''}"
                            data-check-out="${res.check_out_date || ''}"
                            data-total-price="${res.total_price || 0}"
                            data-payment-status="${(res.payment_status || 'unpaid').toLowerCase()}"
                            data-guest="${res.guest_name || 'N/A'}"
                            data-email="${res.email || 'N/A'}"
                            data-phone="${res.phone || 'N/A'}">
                            <i class="icofont-eye"></i> View Details
                        </button>
                    </div>
                </div>
            `;
                })()}
            `).join('');
        }

        // Display service reservations
        function displayServiceReservations(data) {
            const container = document.getElementById('serviceResContainer');
            const count = document.getElementById('serviceResCount');
            const badge = document.getElementById('serviceResBadge');
            
            count.textContent = data.length;
            badge.textContent = data.length;

            if(data.length === 0) {
                container.innerHTML = '<div class="empty-state"><i class="icofont-tasks"></i><p>No service reservations</p></div>';
                return;
            }

            container.innerHTML = data.map(res => `
                ${(() => {
                    const statusValue = (res.status || '').toLowerCase();
                    const isLocked = statusValue === 'completed' || statusValue === 'cancelled';
                    const paymentStatusValue = (res.payment_status || 'unpaid').toLowerCase();
                    const isPaymentLocked = paymentStatusValue === 'paid';
                    return `
                <div class="reservation-item service-item">
                    <div class="reservation-header">
                        <h5 class="reservation-title">${res.guest_name}</h5>
                        <span class="status-badge status-${statusValue}">${capitalize(statusValue.replace('_', ' '))}</span>
                    </div>
                    <div class="reservation-details">
                        <p><i class="icofont-tasks"></i> <strong>Service:</strong> ${res.service_name}</p>
                        <p><i class="icofont-phone"></i> <strong>Guest:</strong> ${res.guest_name}</p>
                        <p><i class="icofont-calendar"></i> <strong>Schedule:</strong> ${formatServiceSchedule(res)}</p>
                        <p><i class="icofont-money"></i> <strong>Total Price:</strong> ${formatCurrency(res.total_price)}</p>
                        <p><i class="icofont-credit-card"></i> <strong>Payment:</strong> <span class="payment-badge payment-${paymentStatusValue}">${capitalize(paymentStatusValue.replace('_', ' '))}</span></p>
                    </div>
                    <div class="reservation-actions reservation-actions-wrap">
                        <select class="form-select form-select-sm status-select" data-type="service" data-id="${res.id}" ${isLocked ? 'disabled' : ''}>
                            ${renderStatusOptions(['pending', 'confirmed', 'completed', 'cancelled'], statusValue)}
                        </select>
                        <button type="button" class="btn btn-sm btn-info status-update-btn" data-type="service" data-id="${res.id}" ${isLocked ? 'disabled' : ''}>
                            <i class="icofont-refresh"></i> ${isLocked ? 'Locked' : 'Update Status'}
                        </button>
                        <select class="form-select form-select-sm payment-select" data-type="service" data-id="${res.id}" ${isPaymentLocked ? 'disabled' : ''}>
                            ${renderStatusOptions(['unpaid', 'partial', 'paid'], paymentStatusValue)}
                        </select>
                        <button type="button" class="btn btn-sm btn-warning payment-update-btn" data-type="service" data-id="${res.id}" ${isPaymentLocked ? 'disabled' : ''}>
                            <i class="icofont-credit-card"></i> ${isPaymentLocked ? 'Paid Locked' : 'Update Payment'}
                        </button>
                        <button type="button" class="btn btn-sm btn-primary service-view-btn"
                            data-id="${res.id}"
                            data-status="${statusValue}"
                            data-service="${res.service_name || 'Service'}"
                            data-schedule="${formatServiceSchedule(res)}"
                            data-total-price="${res.total_price || 0}"
                            data-payment-status="${(res.payment_status || 'unpaid').toLowerCase()}"
                            data-guest="${res.guest_name || 'N/A'}"
                            data-email="${res.email || 'N/A'}"
                            data-phone="${res.phone || 'N/A'}">
                            <i class="icofont-eye"></i> View Details
                        </button>
                    </div>
                </div>
            `;
                })()}
            `).join('');
        }

        // Display pending reservations
        function displayPendingReservations(data) {
            const container = document.getElementById('pendingResContainer');
            const count = document.getElementById('pendingCount');
            const sidebarPending = document.getElementById('sidebarPending');
            if (!container || !count) {
                return;
            }

            count.textContent = data.length;
            if (sidebarPending) {
                sidebarPending.textContent = data.length;
            }

            if(data.length === 0) {
                container.innerHTML = '<div class="empty-state"><i class="icofont-check-alt"></i><p>All reservations confirmed!</p></div>';
                return;
            }

            container.innerHTML = data.map(res => `
                <div class="reservation-item">
                    <div class="reservation-header">
                        <h5 class="reservation-title">${res.guest_name}</h5>
                        <span class="badge ${res.reservation_type === 'service' ? 'bg-info' : 'bg-success'}">
                            ${res.reservation_type === 'service' ? 'Service' : 'Room'}
                        </span>
                        <span class="status-badge status-${res.status.toLowerCase()}">${capitalize(res.status.replace('_', ' '))}</span>
                    </div>
                    <div class="reservation-details">
                        <p><i class="icofont-email"></i> <strong>Email:</strong> ${res.email}</p>
                        <p><i class="icofont-phone"></i> <strong>Phone:</strong> ${res.phone}</p>
                        ${res.reservation_type === 'service'
                            ? `
                                <p><i class="icofont-tasks"></i> <strong>Service:</strong> ${res.service_name || 'Service'}</p>
                                <p><i class="icofont-calendar"></i> <strong>Schedule:</strong> ${formatServiceSchedule(res)}</p>
                              `
                            : `
                                <p><i class="icofont-door"></i> <strong>Room:</strong> ${res.room_number}</p>
                                <p><i class="icofont-calendar"></i> <strong>Check-in:</strong> ${formatDate(res.check_in_date)}</p>
                                <p><i class="icofont-calendar"></i> <strong>Check-out:</strong> ${formatDate(res.check_out_date)}</p>
                                <p><i class="icofont-users-alt-5"></i> <strong>Guests:</strong> ${res.number_of_guests}</p>
                              `
                        }
                    </div>
                    <div class="reservation-actions reservation-actions-wrap">
                        <select class="form-select form-select-sm status-select" data-type="${res.reservation_type}" data-id="${res.id}">
                            ${res.reservation_type === 'service'
                                ? renderStatusOptions(['pending', 'confirmed', 'completed', 'cancelled'], res.status)
                                : renderStatusOptions(['pending', 'confirmed', 'checked_in', 'checked_out', 'cancelled'], res.status)
                            }
                        </select>
                        <button type="button" class="btn btn-sm ${res.reservation_type === 'service' ? 'btn-info' : 'btn-success'} status-update-btn" data-type="${res.reservation_type}" data-id="${res.id}">
                            <i class="icofont-check"></i> Update Status
                        </button>
                        <a href="${res.reservation_type === 'service' ? '#' : `reservation.php?id=${res.id}`}" class="btn btn-sm btn-primary ${res.reservation_type === 'service' ? 'disabled' : ''}">
                            <i class="icofont-eye"></i> ${res.reservation_type === 'service' ? 'Service Info' : 'View Details'}
                        </a>
                    </div>
                </div>
            `).join('');
        }

        // Real-time refresh setup
        // Refresh every 30 seconds
        const refreshInterval = 30000;

        function refreshSidebarData() {
            loadRoomReservations();
            loadServiceReservations();
            loadPendingReservations();
            updateSidebarStats();
            const activeSection = document.querySelector('.dashboard-section.section-active');
            if (activeSection && activeSection.id === 'profile') {
                loadStaffProfile();
            }
        }

        // Setup real-time updates
        setInterval(refreshSidebarData, refreshInterval);

        // Status update actions (room + service)
        document.addEventListener('click', function(event) {
            const roomViewBtn = event.target.closest('.room-view-btn');
            if (roomViewBtn) {
                openRoomDetails(roomViewBtn);
                return;
            }

            const serviceViewBtn = event.target.closest('.service-view-btn');
            if (serviceViewBtn) {
                openServiceDetails(serviceViewBtn);
                return;
            }

            const paymentBtn = event.target.closest('.payment-update-btn');
            if (paymentBtn) {
                const type = paymentBtn.dataset.type;
                const id = paymentBtn.dataset.id;
                const actionContainer = paymentBtn.closest('.reservation-actions');
                const paymentSelect = actionContainer
                    ? actionContainer.querySelector(`.payment-select[data-type="${type}"][data-id="${id}"]`)
                    : null;

                if (!paymentSelect) {
                    StaffUtils.showNotification('error', 'Unable to find payment selector');
                    return;
                }

                const newPaymentStatus = paymentSelect.value;
                paymentBtn.disabled = true;

                const request = type === 'room'
                    ? StaffUtils.updateReservationPaymentStatus(id, newPaymentStatus)
                    : StaffUtils.updateServiceReservationPaymentStatus(id, newPaymentStatus);

                request
                    .then(response => {
                        if (response.success) {
                            StaffUtils.showNotification('success', 'Payment status updated successfully');
                            loadRoomReservations();
                            loadServiceReservations();
                            loadPendingReservations();
                        } else {
                            StaffUtils.showNotification('error', response.message || 'Failed to update payment status');
                        }
                    }).catch(() => {
                        StaffUtils.showNotification('error', 'Failed to update payment status');
                    }).finally(() => {
                        paymentBtn.disabled = false;
                    });
                return;
            }

            const actionBtn = event.target.closest('.status-update-btn');
            if (!actionBtn) {
                return;
            }

            const type = actionBtn.dataset.type;
            const id = actionBtn.dataset.id;
            const actionContainer = actionBtn.closest('.reservation-actions');
            const statusSelect = actionContainer
                ? actionContainer.querySelector(`.status-select[data-type="${type}"][data-id="${id}"]`)
                : null;

            if (!statusSelect) {
                StaffUtils.showNotification('error', 'Unable to find status selector');
                return;
            }

            const newStatus = statusSelect.value;
            actionBtn.disabled = true;

            const request = type === 'service'
                ? StaffUtils.updateServiceReservationStatus(id, newStatus)
                : StaffUtils.updateReservationStatus(id, newStatus);

            request.then(response => {
                if (response.success) {
                    StaffUtils.showNotification('success', 'Status updated successfully');
                    loadRoomReservations();
                    loadServiceReservations();
                    loadPendingReservations();
                    updateSidebarStats();
                } else {
                    StaffUtils.showNotification('error', response.message || 'Failed to update status');
                }
            }).catch(() => {
                StaffUtils.showNotification('error', 'Failed to update status');
            }).finally(() => {
                actionBtn.disabled = false;
            });
        });

        const profileForm = document.getElementById('staffProfileForm');
        if (profileForm) {
            profileForm.addEventListener('submit', function(event) {
                event.preventDefault();
                const saveBtn = document.getElementById('profileSaveBtn');
                if (saveBtn) saveBtn.disabled = true;

                const formData = new FormData(profileForm);
                formData.append('action', 'update_staff_profile');

                fetch('api/get-staff-data.php', {
                    method: 'POST',
                    body: formData
                }).then(response => response.json())
                  .then(response => {
                    if (response.success) {
                        StaffUtils.showNotification('success', response.message || 'Profile updated successfully');
                        loadStaffProfile();
                    } else {
                        StaffUtils.showNotification('error', response.message || 'Failed to update profile');
                    }
                  }).catch(() => {
                    StaffUtils.showNotification('error', 'Failed to update profile');
                  }).finally(() => {
                    if (saveBtn) saveBtn.disabled = false;
                  });
            });
        }

        // Profile Image Upload Handler
        const profileImageInput = document.getElementById('profileImageInput');
        const profileImageUploadBtn = document.getElementById('profileImageUploadBtn');
        const profileImagePreview = document.getElementById('profileImagePreview');
        const imageUploadStatus = document.getElementById('imageUploadStatus');

        if (profileImageUploadBtn && profileImageInput) {
            profileImageUploadBtn.addEventListener('click', function() {
                profileImageInput.click();
            });

            profileImageInput.addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (!file) return;

                // Validate file type
                if (!file.type.startsWith('image/')) {
                    imageUploadStatus.innerHTML = '<span class="error"><i class="icofont-close-line"></i>Please select a valid image file</span>';
                    imageUploadStatus.className = 'error';
                    return;
                }

                // Validate file size (5MB max)
                if (file.size > 5 * 1024 * 1024) {
                    imageUploadStatus.innerHTML = '<span class="error"><i class="icofont-close-line"></i>File size must be less than 5MB</span>';
                    imageUploadStatus.className = 'error';
                    return;
                }

                // Show loading state
                imageUploadStatus.innerHTML = '<i class="icofont-refresh"></i> Uploading...';
                imageUploadStatus.className = 'loading';

                // Create FormData
                const formData = new FormData();
                formData.append('action', 'upload_profile_image');
                formData.append('profile_image', file);

                // Upload image
                fetch('api/get-staff-data.php', {
                    method: 'POST',
                    body: formData
                }).then(response => response.json())
                  .then(response => {
                    if (response.success) {
                        imageUploadStatus.innerHTML = '<i class="icofont-check"></i> Image uploaded successfully';
                        imageUploadStatus.className = 'success';
                        
                        // Update preview with timestamp to bypass cache
                        const timestamp = new Date().getTime();
                        profileImagePreview.src = (response.data && response.data.image_url) ? response.data.image_url + '?t=' + timestamp : 'images/default-avatar.png?t=' + timestamp;
                        
                        // Clear file input
                        profileImageInput.value = '';
                        
                        // Clear status message after 3 seconds
                        setTimeout(() => {
                            imageUploadStatus.innerHTML = '';
                            imageUploadStatus.className = '';
                        }, 3000);
                    } else {
                        imageUploadStatus.innerHTML = '<i class="icofont-close-line"></i> ' + (response.message || 'Failed to upload image');
                        imageUploadStatus.className = 'error';
                    }
                  }).catch(error => {
                    imageUploadStatus.innerHTML = '<i class="icofont-close-line"></i> Error uploading image';
                    imageUploadStatus.className = 'error';
                    console.error('Upload error:', error);
                  });
            });

            // Trigger upload on image click
            if (profileImagePreview) {
                profileImagePreview.style.cursor = 'pointer';
                profileImagePreview.addEventListener('click', function() {
                    profileImageInput.click();
                });
            }
        }

        const passwordForm = document.getElementById('staffPasswordForm');
        if (passwordForm) {
            passwordForm.addEventListener('submit', function(event) {
                event.preventDefault();
                const saveBtn = document.getElementById('passwordSaveBtn');
                if (saveBtn) saveBtn.disabled = true;

                const formData = new FormData(passwordForm);
                formData.append('action', 'change_staff_password');

                fetch('api/get-staff-data.php', {
                    method: 'POST',
                    body: formData
                }).then(response => response.json())
                  .then(response => {
                    if (response.success) {
                        StaffUtils.showNotification('success', response.message || 'Password changed successfully');
                        passwordForm.reset();
                    } else {
                        StaffUtils.showNotification('error', response.message || 'Failed to change password');
                    }
                  }).catch(() => {
                    StaffUtils.showNotification('error', 'Failed to change password');
                  }).finally(() => {
                    if (saveBtn) saveBtn.disabled = false;
                  });
            });
        }

        // Initial load
        loadRoomReservations();
        loadServiceReservations();
        loadPendingReservations();
        loadStaffProfile();
        updateSidebarStats();

        function updateSidebarStats() {
            StaffUtils.getStaffData('get_dashboard_stats').then(response => {
                if(response.success) {
                    document.getElementById('sidebarGuests').textContent = response.data.total_guests;
                    document.getElementById('sidebarActive').textContent = response.data.total_active_bookings;
                    if (response.data.total_pending_reservations !== undefined) {
                        const sidebarPending = document.getElementById('sidebarPending');
                        if (sidebarPending) {
                            sidebarPending.textContent = response.data.total_pending_reservations;
                        }
                    }

                    const overviewTotalGuests = document.getElementById('overviewTotalGuests');
                    const overviewRoomReservations = document.getElementById('overviewRoomReservations');
                    const overviewServiceReservations = document.getElementById('overviewServiceReservations');
                    const overviewActiveBookings = document.getElementById('overviewActiveBookings');
                    const overviewCheckedInGuests = document.getElementById('overviewCheckedInGuests');

                    if (overviewTotalGuests) overviewTotalGuests.textContent = response.data.total_guests;
                    if (overviewRoomReservations) overviewRoomReservations.textContent = response.data.total_reservations;
                    if (overviewServiceReservations) overviewServiceReservations.textContent = response.data.total_service_reservations;
                    if (overviewActiveBookings) overviewActiveBookings.textContent = response.data.total_active_bookings;
                    if (overviewCheckedInGuests) overviewCheckedInGuests.textContent = response.data.checked_in_guests;
                }
            });
        }

        // Update sidebar stats every minute
        setInterval(updateSidebarStats, 60000);

        // Capitalize helper
        function capitalize(str) {
            return str.charAt(0).toUpperCase() + str.slice(1);
        }

        function renderStatusOptions(statuses, currentStatus) {
            return statuses.map(status => {
                const isSelected = status === currentStatus ? 'selected' : '';
                return `<option value="${status}" ${isSelected}>${capitalize(status.replace('_', ' '))}</option>`;
            }).join('');
        }

        function formatServiceSchedule(service) {
            const reservationDate = service.reservation_date;
            const reservationTime = service.reservation_time;
            const startDate = service.service_start_date;
            const endDate = service.service_end_date;

            if (reservationDate) {
                const dateText = formatDate(reservationDate);
                return reservationTime ? `${dateText} ${reservationTime}` : dateText;
            }

            if (startDate && endDate) {
                return `${formatDate(startDate)} - ${formatDate(endDate)}`;
            }

            if (startDate) {
                return formatDate(startDate);
            }

            return 'Schedule not available';
        }

        function formatCurrency(value) {
            const numericValue = Number(value || 0);
            return numericValue.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
        }

        function openRoomDetails(button) {
            const setText = (id, value) => {
                const el = document.getElementById(id);
                if (el) {
                    el.textContent = value || '-';
                }
            };

            const roomText = `${button.dataset.roomNumber || 'N/A'}${button.dataset.roomType ? ` (${button.dataset.roomType})` : ''}`;

            setText('roomDetailId', button.dataset.id);
            setText('roomDetailStatus', capitalize((button.dataset.status || '-').replace('_', ' ')));
            setText('roomDetailRoom', roomText);
            setText('roomDetailGuests', button.dataset.guests);
            setText('roomDetailCheckIn', button.dataset.checkIn ? formatDate(button.dataset.checkIn) : '-');
            setText('roomDetailCheckOut', button.dataset.checkOut ? formatDate(button.dataset.checkOut) : '-');
            setText('roomDetailTotalPrice', formatCurrency(button.dataset.totalPrice));
            setText('roomDetailPaymentStatus', capitalize((button.dataset.paymentStatus || '-').replace('_', ' ')));
            setText('roomDetailGuest', button.dataset.guest);
            setText('roomDetailEmail', button.dataset.email);
            setText('roomDetailPhone', button.dataset.phone);

            const modalElement = document.getElementById('roomReservationModal');
            if (!modalElement) {
                return;
            }

            if (typeof bootstrap !== 'undefined' && bootstrap.Modal) {
                const modal = bootstrap.Modal.getOrCreateInstance(modalElement);
                modal.show();
                return;
            }

            if (typeof $ !== 'undefined' && typeof $.fn.modal === 'function') {
                $('#roomReservationModal').modal('show');
                return;
            }

            modalElement.style.display = 'block';
            modalElement.classList.add('show');
            modalElement.setAttribute('aria-modal', 'true');
            modalElement.removeAttribute('aria-hidden');
            document.body.classList.add('modal-open');

            let backdrop = document.getElementById('roomModalBackdropFallback');
            if (!backdrop) {
                backdrop = document.createElement('div');
                backdrop.id = 'roomModalBackdropFallback';
                backdrop.className = 'modal-backdrop fade show';
                backdrop.addEventListener('click', closeRoomDetailsModal);
                document.body.appendChild(backdrop);
            }
        }

        function closeRoomDetailsModal() {
            const modalElement = document.getElementById('roomReservationModal');
            if (!modalElement) {
                return;
            }

            if (typeof bootstrap !== 'undefined' && bootstrap.Modal) {
                const instance = bootstrap.Modal.getInstance(modalElement);
                if (instance) {
                    instance.hide();
                    return;
                }
            }

            if (typeof $ !== 'undefined' && typeof $.fn.modal === 'function') {
                $('#roomReservationModal').modal('hide');
                return;
            }

            modalElement.classList.remove('show');
            modalElement.style.display = 'none';
            modalElement.setAttribute('aria-hidden', 'true');
            modalElement.removeAttribute('aria-modal');
            document.body.classList.remove('modal-open');

            const backdrop = document.getElementById('roomModalBackdropFallback');
            if (backdrop) {
                backdrop.remove();
            }
        }

        (function initRoomModalCloseHandlers() {
            const modalElement = document.getElementById('roomReservationModal');
            if (!modalElement) {
                return;
            }

            modalElement.addEventListener('click', function(event) {
                if (event.target === modalElement) {
                    closeRoomDetailsModal();
                }
            });

            modalElement.querySelectorAll('[data-bs-dismiss="modal"]').forEach(btn => {
                btn.addEventListener('click', function() {
                    closeRoomDetailsModal();
                });
            });

            document.addEventListener('keydown', function(event) {
                if (event.key === 'Escape' && modalElement.classList.contains('show')) {
                    closeRoomDetailsModal();
                }
            });
        })();

        function openServiceDetails(button) {
            const setText = (id, value) => {
                const el = document.getElementById(id);
                if (el) {
                    el.textContent = value || '-';
                }
            };

            setText('serviceDetailId', button.dataset.id);
            setText('serviceDetailStatus', capitalize((button.dataset.status || '-').replace('_', ' ')));
            setText('serviceDetailName', button.dataset.service);
            setText('serviceDetailSchedule', button.dataset.schedule);
            setText('serviceDetailTotalPrice', formatCurrency(button.dataset.totalPrice));
            setText('serviceDetailPaymentStatus', capitalize((button.dataset.paymentStatus || '-').replace('_', ' ')));
            setText('serviceDetailGuest', button.dataset.guest);
            setText('serviceDetailEmail', button.dataset.email);
            setText('serviceDetailPhone', button.dataset.phone);

            const modalElement = document.getElementById('serviceReservationModal');
            if (!modalElement) {
                return;
            }

            // Bootstrap 5 API
            if (typeof bootstrap !== 'undefined' && bootstrap.Modal) {
                const modal = bootstrap.Modal.getOrCreateInstance(modalElement);
                modal.show();
                return;
            }

            // Bootstrap 4/jQuery fallback
            if (typeof $ !== 'undefined' && typeof $.fn.modal === 'function') {
                $('#serviceReservationModal').modal('show');
                return;
            }

            // Final fallback if modal plugin is not available
            modalElement.style.display = 'block';
            modalElement.classList.add('show');
            modalElement.setAttribute('aria-modal', 'true');
            modalElement.removeAttribute('aria-hidden');
            document.body.classList.add('modal-open');

            // Create fallback backdrop if missing
            let backdrop = document.getElementById('serviceModalBackdropFallback');
            if (!backdrop) {
                backdrop = document.createElement('div');
                backdrop.id = 'serviceModalBackdropFallback';
                backdrop.className = 'modal-backdrop fade show';
                backdrop.addEventListener('click', closeServiceDetailsModal);
                document.body.appendChild(backdrop);
            }
        }

        function closeServiceDetailsModal() {
            const modalElement = document.getElementById('serviceReservationModal');
            if (!modalElement) {
                return;
            }

            // Bootstrap 5 API
            if (typeof bootstrap !== 'undefined' && bootstrap.Modal) {
                const instance = bootstrap.Modal.getInstance(modalElement);
                if (instance) {
                    instance.hide();
                    return;
                }
            }

            // Bootstrap 4/jQuery fallback
            if (typeof $ !== 'undefined' && typeof $.fn.modal === 'function') {
                $('#serviceReservationModal').modal('hide');
                return;
            }

            // Manual fallback close
            modalElement.classList.remove('show');
            modalElement.style.display = 'none';
            modalElement.setAttribute('aria-hidden', 'true');
            modalElement.removeAttribute('aria-modal');
            document.body.classList.remove('modal-open');

            const backdrop = document.getElementById('serviceModalBackdropFallback');
            if (backdrop) {
                backdrop.remove();
            }
        }

        // Ensure close actions always work (x button, footer close, outside click, ESC)
        (function initServiceModalCloseHandlers() {
            const modalElement = document.getElementById('serviceReservationModal');
            if (!modalElement) {
                return;
            }

            modalElement.addEventListener('click', function(event) {
                if (event.target === modalElement) {
                    closeServiceDetailsModal();
                }
            });

            modalElement.querySelectorAll('[data-bs-dismiss="modal"]').forEach(btn => {
                btn.addEventListener('click', function() {
                    closeServiceDetailsModal();
                });
            });

            document.addEventListener('keydown', function(event) {
                if (event.key === 'Escape' && modalElement.classList.contains('show')) {
                    closeServiceDetailsModal();
                }
            });
        })();

        // Auto-refresh dashboard every 5 minutes (300000 milliseconds)
        // Uncomment the line below to enable auto-refresh
        // StaffUtils.startAutoRefresh(300000);

        // Manual refresh example - uncomment to test
        // StaffUtils.refreshDashboard();
    </script>
</body>

</html>
