<?php
require_once 'config.php';
session_start();

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

$staff_id = $_SESSION['user_id'];
$staff_name = $_SESSION['admin_name'] ?? 'Staff Member';
?><!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Staff Dashboard | Cleaning Service</title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/fontawesome.min.css">
    <style>
        :root {
            --primary-color: #109c3d;
            --primary-dark: #0f8c3d;
            --light-bg: #f8fbff;
            --border-color: rgba(16, 156, 61, 0.2);
            --danger: #ef4444;
            --warning: #fbbf24;
            --info: #3b82f6;
            --success: #10b981;
        }

        * {
            transition: all 0.3s ease;
        }

        body {
            background: linear-gradient(135deg, #f8fbff, #f1f5f4);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .dashboard-wrapper {
            display: grid;
            grid-template-columns: 280px 1fr;
            gap: 0;
            min-height: 100vh;
        }

        .sidebar {
            background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
            color: white;
            padding: 30px 20px;
            position: sticky;
            top: 0;
            height: 100vh;
            overflow-y: auto;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }

        .sidebar-brand {
            font-weight: 700;
            font-size: 18px;
            margin-bottom: 30px;
            display: flex;
            align-items: center;
            gap: 10px;
            padding-bottom: 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
        }

        .sidebar-menu {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .sidebar-menu li {
            margin-bottom: 10px;
        }

        .sidebar-menu a {
            color: rgba(255, 255, 255, 0.8);
            text-decoration: none;
            padding: 12px 15px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 14px;
            cursor: pointer;
        }

        .sidebar-menu a:hover,
        .sidebar-menu a.active {
            background: rgba(255, 255, 255, 0.2);
            color: white;
        }

        .sidebar-menu i {
            width: 20px;
            text-align: center;
        }

        .sidebar-divider {
            height: 1px;
            background: rgba(255, 255, 255, 0.2);
            margin: 20px 0;
        }

        .logout-btn {
            margin-top: 30px;
            padding-top: 30px;
            border-top: 1px solid rgba(255, 255, 255, 0.2);
        }

        .main-content {
            padding: 30px;
            overflow-y: auto;
        }

        .header-section {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 40px;
            flex-wrap: wrap;
            gap: 20px;
        }

        .header-section h1 {
            font-size: 32px;
            font-weight: 700;
            color: #0f172a;
        }

        .staff-profile {
            display: flex;
            align-items: center;
            gap: 15px;
            background: white;
            padding: 15px 20px;
            border-radius: 12px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
        }

        .avatar {
            width: 45px;
            height: 45px;
            border-radius: 50%;
            background: var(--primary-color);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 700;
            font-size: 18px;
        }

        .content-section {
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            margin-bottom: 30px;
        }

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            flex-wrap: wrap;
            gap: 15px;
        }

        .section-header h2 {
            font-size: 22px;
            font-weight: 700;
            color: #0f172a;
        }

        .btn-primary-custom {
            background: var(--primary-color);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .btn-primary-custom:hover {
            background: var(--primary-dark);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(16, 156, 61, 0.3);
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 12px;
            border-left: 4px solid var(--primary-color);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
        }

        .stat-card h3 {
            font-size: 14px;
            font-weight: 600;
            color: #64748b;
            margin: 0 0 10px 0;
        }

        .stat-card .stat-value {
            font-size: 28px;
            font-weight: 700;
            color: var(--primary-color);
        }

        .data-table {
            overflow-x: auto;
        }

        .data-table table {
            width: 100%;
            border-collapse: collapse;
        }

        .data-table thead {
            background: var(--light-bg);
        }

        .data-table th {
            padding: 15px;
            text-align: left;
            font-weight: 600;
            color: #0f172a;
            border-bottom: 2px solid var(--border-color);
        }

        .data-table td {
            padding: 15px;
            border-bottom: 1px solid var(--border-color);
            color: #64748b;
        }

        .status-badge {
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }

        .status-pending {
            background: rgba(251, 191, 36, 0.1);
            color: #d97706;
        }

        .status-in_progress {
            background: rgba(59, 130, 246, 0.1);
            color: #2563eb;
        }

        .status-completed {
            background: rgba(16, 156, 61, 0.1);
            color: var(--primary-color);
        }

        .status-rejected {
            background: rgba(239, 68, 68, 0.1);
            color: var(--danger);
        }

        .status-confirmed {
            background: rgba(59, 130, 246, 0.1);
            color: #2563eb;
        }

        .btn-action {
            padding: 6px 12px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            font-weight: 600;
            margin-right: 5px;
        }

        .btn-action-primary {
            background: var(--primary-color);
            color: white;
        }

        .btn-action-primary:hover {
            background: var(--primary-dark);
        }

        .btn-action-success {
            background: var(--success);
            color: white;
        }

        .btn-action-success:hover {
            background: #059669;
        }

        .nav-tabs {
            display: flex;
            gap: 10px;
            border-bottom: 2px solid var(--border-color);
            margin-bottom: 25px;
            flex-wrap: wrap;
        }

        .nav-tab {
            background: none;
            border: none;
            color: #64748b;
            padding: 12px 20px;
            cursor: pointer;
            font-weight: 600;
            border-bottom: 3px solid transparent;
            transition: all 0.3s ease;
        }

        .nav-tab.active {
            color: var(--primary-color);
            border-bottom-color: var(--primary-color);
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .loading {
            text-align: center;
            padding: 40px 20px;
            color: #64748b;
        }

        .spinner {
            border: 4px solid var(--light-bg);
            border-top: 4px solid var(--primary-color);
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
        }

        .modal-overlay.active {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background: white;
            border-radius: 15px;
            padding: 30px;
            max-width: 600px;
            width: 90%;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            border-bottom: 1px solid var(--border-color);
            padding-bottom: 15px;
        }

        .modal-close {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #64748b;
            padding: 0;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #0f172a;
        }

        .form-group textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            font-family: inherit;
            min-height: 100px;
        }

        .form-actions {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 30px;
        }

        .btn-modal-cancel,
        .btn-modal-submit {
            padding: 10px 20px;
            border-radius: 8px;
            border: none;
            cursor: pointer;
            font-weight: 600;
        }

        .btn-modal-cancel {
            background: #e2e8f0;
            color: #0f172a;
        }

        .btn-modal-submit {
            background: var(--primary-color);
            color: white;
        }

        .assignment-card {
            background: #f8fbff;
            border-left: 4px solid var(--primary-color);
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 15px;
        }

        .assignment-card.high {
            border-left-color: var(--danger);
        }

        .assignment-card.medium {
            border-left-color: var(--warning);
        }

        .assignment-card.low {
            border-left-color: var(--info);
        }

        .assignment-title {
            font-weight: 700;
            color: #0f172a;
            margin-bottom: 8px;
            font-size: 16px;
        }

        .assignment-meta {
            display: flex;
            gap: 15px;
            margin-bottom: 12px;
            flex-wrap: wrap;
            font-size: 13px;
        }

        .assignment-actions {
            display: flex;
            gap: 10px;
            margin-top: 15px;
            flex-wrap: wrap;
        }

        @media (max-width: 768px) {
            .dashboard-wrapper {
                grid-template-columns: 1fr;
            }

            .stats-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="dashboard-wrapper">
        <!-- Sidebar Navigation -->
        <div class="sidebar">
            <div class="sidebar-brand">
                <i class="fa-solid fa-users-gear"></i>
                Staff Panel
            </div>
            <ul class="sidebar-menu">
                <li><a href="#" class="menu-link active" data-tab="dashboard"><i class="fa-solid fa-gauge"></i> Dashboard</a></li>
                <li><a href="#" class="menu-link" data-tab="my-tasks"><i class="fa-solid fa-tasks"></i> My Tasks</a></li>
                <li><a href="#" class="menu-link" data-tab="my-assignments"><i class="fa-solid fa-briefcase"></i> My Assignments</a></li>
                <li><a href="#" class="menu-link" data-tab="profile"><i class="fa-solid fa-user"></i> My Profile</a></li>
                
                <div class="sidebar-divider"></div>
                
                <li class="logout-btn"><a href="logout.php"><i class="fa-solid fa-sign-out-alt"></i> Logout</a></li>
            </ul>
        </div>

        <!-- Main Content -->
        <div class="main-content">
            <div class="header-section">
                <div>
                    <h1 id="pageTitle">Dashboard</h1>
                </div>
                <div class="staff-profile">
                    <div class="avatar"><?php echo strtoupper(substr($staff_name, 0, 1)); ?></div>
                    <div>
                        <strong style="color: #0f172a;"><?php echo htmlspecialchars($staff_name); ?></strong><br>
                        <small style="color: #64748b;">Staff Member</small>
                    </div>
                </div>
            </div>

            <!-- TAB 1: Dashboard -->
            <div id="dashboard" class="tab-content active">
                <div class="content-section">
                    <div class="stats-grid" id="statsGrid">
                        <div class="loading">
                            <div class="spinner"></div>
                            Loading statistics...
                        </div>
                    </div>
                </div>

                <div class="content-section">
                    <div class="section-header">
                        <h2>Upcoming Assignments</h2>
                    </div>
                    <div id="upcomingContainer" class="data-table">
                        <div class="loading">
                            <div class="spinner"></div>
                            Loading assignments...
                        </div>
                    </div>
                </div>
            </div>

            <!-- TAB 2: My Tasks (from Admin) -->
            <div id="my-tasks" class="tab-content">
                <div class="content-section">
                    <div class="section-header">
                        <h2>Tasks Assigned to Me</h2>
                    </div>

                    <div class="nav-tabs">
                        <button class="nav-tab active" onclick="filterTasks('all')" style="padding: 8px 16px; background: var(--light-bg); border: 1px solid var(--border-color); border-radius: 6px; cursor: pointer; font-weight: 600; color: var(--primary-color);">All</button>
                        <button class="nav-tab" onclick="filterTasks('pending')" style="padding: 8px 16px; background: transparent; border: 1px solid var(--border-color); border-radius: 6px; cursor: pointer; font-weight: 600;">Pending</button>
                        <button class="nav-tab" onclick="filterTasks('in_progress')" style="padding: 8px 16px; background: transparent; border: 1px solid var(--border-color); border-radius: 6px; cursor: pointer; font-weight: 600;">In Progress</button>
                        <button class="nav-tab" onclick="filterTasks('completed')" style="padding: 8px 16px; background: transparent; border: 1px solid var(--border-color); border-radius: 6px; cursor: pointer; font-weight: 600;">Completed</button>
                    </div>

                    <div id="tasksContainer">
                        <div class="loading">
                            <div class="spinner"></div>
                            Loading tasks...
                        </div>
                    </div>
                </div>
            </div>

            <!-- TAB 3: My Assignments -->
            <div id="my-assignments" class="tab-content">
                <div class="content-section">
                    <div class="section-header">
                        <h2>All Service Assignments</h2>
                    </div>

                    <div class="nav-tabs">
                        <button class="nav-tab active" onclick="filterAssignments('all')" style="padding: 8px 16px; background: var(--light-bg); border: 1px solid var(--border-color); border-radius: 6px; cursor: pointer; font-weight: 600; color: var(--primary-color);">All</button>
                        <button class="nav-tab" onclick="filterAssignments('pending')" style="padding: 8px 16px; background: transparent; border: 1px solid var(--border-color); border-radius: 6px; cursor: pointer; font-weight: 600;">Pending</button>
                        <button class="nav-tab" onclick="filterAssignments('confirmed')" style="padding: 8px 16px; background: transparent; border: 1px solid var(--border-color); border-radius: 6px; cursor: pointer; font-weight: 600;">Confirmed</button>
                        <button class="nav-tab" onclick="filterAssignments('completed')" style="padding: 8px 16px; background: transparent; border: 1px solid var(--border-color); border-radius: 6px; cursor: pointer; font-weight: 600;">Completed</button>
                    </div>

                    <div id="assignmentsContainer" class="data-table">
                        <div class="loading">
                            <div class="spinner"></div>
                            Loading assignments...
                        </div>
                    </div>
                </div>
            </div>

            <!-- TAB 4: My Profile -->
            <div id="profile" class="tab-content">
                <div class="content-section">
                    <div class="section-header">
                        <h2>My Profile</h2>
                        <button class="btn-primary-custom" onclick="openEditProfileModal()">Edit Profile</button>
                    </div>
                    <div id="profileContainer" class="loading">
                        <div class="spinner"></div>
                        Loading profile...
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Profile Modal -->
    <div class="modal-overlay" id="editProfileModal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Edit Profile</h2>
                <button class="modal-close" onclick="closeEditProfileModal()">
                    <i class="fa-solid fa-times"></i>
                </button>
            </div>
            <div id="editProfileAlert"></div>
            <form id="editProfileForm">
                <div class="form-group">
                    <label for="editEmail">Email Address</label>
                    <input type="email" id="editEmail" required>
                </div>
                <div class="form-group">
                    <label for="editPhone">Phone Number</label>
                    <input type="tel" id="editPhone">
                </div>
                <div class="form-group">
                    <label for="editPassword">New Password (leave blank to keep current)</label>
                    <input type="password" id="editPassword">
                </div>
                <div class="form-group">
                    <label for="editPasswordConfirm">Confirm Password</label>
                    <input type="password" id="editPasswordConfirm">
                </div>
                <div class="form-actions">
                    <button type="button" class="btn-modal-cancel" onclick="closeEditProfileModal()">Cancel</button>
                    <button type="submit" class="btn-modal-submit">Save Changes</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Task Status Update Modal -->
    <div class="modal-overlay" id="updateTaskModal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Update Task Status</h2>
                <button class="modal-close" onclick="closeUpdateTaskModal()">
                    <i class="fa-solid fa-times"></i>
                </button>
            </div>
            <form id="updateTaskForm">
                <div class="form-group">
                    <label for="taskStatus">Status</label>
                    <select id="taskStatus" required style="width: 100%; padding: 10px; border: 1px solid var(--border-color); border-radius: 6px;">
                        <option value="pending">Pending</option>
                        <option value="in_progress">In Progress</option>
                        <option value="completed">Completed</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="taskNotes">Notes/Comments</label>
                    <textarea id="taskNotes" placeholder="Add notes about this task..."></textarea>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn-modal-cancel" onclick="closeUpdateTaskModal()">Cancel</button>
                    <button type="submit" class="btn-modal-submit">Update Status</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        const API_URL = 'api_handler.php';
        let currentTaskId = null;
        let currentAssignmentFilter = 'all';
        let currentTaskFilter = 'all';

        // Menu link click handler
        document.querySelectorAll('.menu-link').forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                const tabName = link.getAttribute('data-tab');
                
                // Update active menu item
                document.querySelectorAll('.menu-link').forEach(l => l.classList.remove('active'));
                link.classList.add('active');
                
                // Update active tab
                document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active'));
                document.getElementById(tabName).classList.add('active');
                
                // Update page title
                const titles = {
                    'dashboard': 'Dashboard',
                    'my-tasks': 'Tasks Assigned to Me',
                    'my-assignments': 'My Service Assignments',
                    'profile': 'My Profile'
                };
                document.getElementById('pageTitle').textContent = titles[tabName] || 'Dashboard';
                
                // Load data based on tab
                if (tabName === 'dashboard') {
                    loadDashboardStats();
                    loadUpcomingAssignments();
                } else if (tabName === 'my-tasks') {
                    loadStaffTasks('all');
                } else if (tabName === 'my-assignments') {
                    loadStaffAssignments('all');
                } else if (tabName === 'profile') {
                    loadStaffProfile();
                }
            });
        });

        // Load Dashboard Statistics
        function loadDashboardStats() {
            fetch(`${API_URL}?action=get_staff_stats`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const stats = data.data;
                        const statsGrid = document.getElementById('statsGrid');
                        statsGrid.innerHTML = `
                            <div class="stat-card">
                                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                                    <h3 style="margin: 0;">Total Tasks</h3>
                                    <i class="fa-solid fa-tasks" style="font-size: 24px; color: var(--primary-color);"></i>
                                </div>
                                <div class="stat-value" style="font-size: 36px; font-weight: 700; color: var(--primary-color);">${stats.total_tasks || 0}</div>
                                <p style="margin: 8px 0 0 0; color: #64748b; font-size: 12px;">Tasks assigned to you</p>
                            </div>
                            <div class="stat-card">
                                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                                    <h3 style="margin: 0;">Pending Tasks</h3>
                                    <i class="fa-solid fa-hourglass-end" style="font-size: 24px; color: #f59e0b;"></i>
                                </div>
                                <div class="stat-value" style="font-size: 36px; font-weight: 700; color: #f59e0b;">${stats.pending_tasks || 0}</div>
                                <p style="margin: 8px 0 0 0; color: #64748b; font-size: 12px;">In progress or pending</p>
                            </div>
                            <div class="stat-card">
                                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                                    <h3 style="margin: 0;">Completed Tasks</h3>
                                    <i class="fa-solid fa-check-circle" style="font-size: 24px; color: #10b981;"></i>
                                </div>
                                <div class="stat-value" style="font-size: 36px; font-weight: 700; color: #10b981;">${stats.completed_tasks || 0}</div>
                                <p style="margin: 8px 0 0 0; color: #64748b; font-size: 12px;">Successfully completed</p>
                            </div>
                            <div class="stat-card">
                                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                                    <h3 style="margin: 0;">Assignments</h3>
                                    <i class="fa-solid fa-calendar-check" style="font-size: 24px; color: #8b5cf6;"></i>
                                </div>
                                <div class="stat-value" style="font-size: 36px; font-weight: 700; color: #8b5cf6;">${stats.total_assignments || 0}</div>
                                <p style="margin: 8px 0 0 0; color: #64748b; font-size: 12px;">Service assignments</p>
                            </div>
                        `;
                    }
                })
                .catch(error => console.error('Error:', error));
        }

        // Load Upcoming Assignments
        function loadUpcomingAssignments() {
            fetch(`${API_URL}?action=get_staff_upcoming_assignments`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const assignments = data.data || [];
                        const container = document.getElementById('upcomingContainer');
                        
                        if (assignments.length === 0) {
                            container.innerHTML = '<p style="text-align: center; color: #64748b;">No upcoming assignments</p>';
                            return;
                        }
                        
                        let html = '<table><thead><tr><th>Date</th><th>Time</th><th>Service</th><th>Customer</th><th>Status</th></tr></thead><tbody>';
                        assignments.forEach(assignment => {
                            const statusClass = `status-${assignment.status}`;
                            html += `
                                <tr>
                                    <td>${assignment.booking_date}</td>
                                    <td>${assignment.booking_time}</td>
                                    <td>${assignment.service_name}</td>
                                    <td>${assignment.customer_name}</td>
                                    <td><span class="status-badge ${statusClass}">${assignment.status.toUpperCase()}</span></td>
                                </tr>
                            `;
                        });
                        html += '</tbody></table>';
                        container.innerHTML = html;
                    }
                })
                .catch(error => console.error('Error:', error));
        }

        // Load Staff Tasks (assigned by admin)
        function loadStaffTasks(filter) {
            fetch(`${API_URL}?action=get_staff_task_assignments&status=${filter}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const tasks = data.data || [];
                        const container = document.getElementById('tasksContainer');
                        
                        if (tasks.length === 0) {
                            container.innerHTML = '<p style="text-align: center; color: #64748b;">No tasks assigned</p>';
                            return;
                        }
                        
                        let html = '';
                        tasks.forEach(task => {
                            const dueDate = new Date(task.due_date);
                            const today = new Date();
                            const isOverdue = dueDate < today && task.status !== 'completed';
                            const priorityClass = task.priority || 'medium';
                            const statusClass = `status-${task.status}`;
                            
                            html += `
                                <div class="assignment-card ${priorityClass}">
                                    <div class="assignment-title">${task.task_description}</div>
                                    <div class="assignment-meta">
                                        <span><i class="fa-solid fa-calendar"></i> Due: ${task.due_date}${isOverdue && task.status !== 'completed' ? ' <strong style="color: var(--danger);">(OVERDUE)</strong>' : ''}</span>
                                        <span><i class="fa-solid fa-flag"></i> Priority: <strong>${task.priority.toUpperCase()}</strong></span>
                                        <span><i class="fa-solid fa-user"></i> By: ${task.admin_name}</span>
                                    </div>
                                    <div class="assignment-meta">
                                        <span>Status: <strong class="status-badge ${statusClass}">${task.status.toUpperCase()}</strong></span>
                                        <span>Your: <strong class="status-badge status-${task.staff_status}">${task.staff_status.toUpperCase()}</strong></span>
                                    </div>
                                    ${task.staff_notes ? `<div style="margin-top: 10px; padding: 10px; background: white; border-radius: 6px; font-size: 13px;"><strong>Notes:</strong> ${task.staff_notes}</div>` : ''}
                                    <div class="assignment-actions">
                                        <button class="btn-action btn-action-primary" onclick="openUpdateTaskModal(${task.id})">Update Status</button>
                                    </div>
                                </div>
                            `;
                        });
                        container.innerHTML = html;
                    }
                })
                .catch(error => console.error('Error:', error));
        }

        // Filter Tasks
        function filterTasks(filter) {
            currentTaskFilter = filter;
            loadStaffTasks(filter);
            
            // Update active button
            if (event && event.target) {
                event.target.parentElement.querySelectorAll('.nav-tab').forEach(btn => btn.classList.remove('active'));
                event.target.classList.add('active');
            }
        }

        // Open Update Task Modal
        function openUpdateTaskModal(taskId) {
            currentTaskId = taskId;
            document.getElementById('taskStatus').value = 'in_progress';
            document.getElementById('taskNotes').value = '';
            document.getElementById('updateTaskModal').classList.add('active');
        }

        // Close Update Task Modal
        function closeUpdateTaskModal() {
            document.getElementById('updateTaskModal').classList.remove('active');
            currentTaskId = null;
        }

        // Update Task Status
        document.getElementById('updateTaskForm')?.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const status = document.getElementById('taskStatus').value;
            const notes = document.getElementById('taskNotes').value;
            
            const formData = new FormData();
            formData.append('action', 'update_task_status');
            formData.append('assignment_id', currentTaskId);
            formData.append('status', status);
            formData.append('notes', notes);
            
            fetch(API_URL, { method: 'POST', body: formData })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        closeUpdateTaskModal();
                        loadStaffTasks(currentTaskFilter);
                        showAlert('success', 'Task status updated successfully');
                    } else {
                        showAlert('danger', data.message || 'Error updating task status');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showAlert('danger', 'Error updating task status');
                });
        });

        // Load Staff Assignments
        function loadStaffAssignments(filter) {
            fetch(`${API_URL}?action=get_staff_assignments&status=${filter}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const assignments = data.data || [];
                        const container = document.getElementById('assignmentsContainer');
                        
                        if (assignments.length === 0) {
                            container.innerHTML = '<p style="text-align: center; color: #64748b;">No assignments found</p>';
                            return;
                        }
                        
                        let html = '<table><thead><tr><th>Date</th><th>Time</th><th>Service</th><th>Customer</th><th>Status</th></tr></thead><tbody>';
                        assignments.forEach(assignment => {
                            const statusClass = `status-${assignment.status}`;
                            html += `
                                <tr>
                                    <td>${assignment.booking_date}</td>
                                    <td>${assignment.booking_time}</td>
                                    <td>${assignment.service_name}</td>
                                    <td>${assignment.customer_name}</td>
                                    <td><span class="status-badge ${statusClass}">${assignment.status.toUpperCase()}</span></td>
                                </tr>
                            `;
                        });
                        html += '</tbody></table>';
                        container.innerHTML = html;
                    }
                })
                .catch(error => console.error('Error:', error));
        }

        // Filter Assignments
        function filterAssignments(filter) {
            currentAssignmentFilter = filter;
            loadStaffAssignments(filter);
            
            // Update active button
            if (event && event.target) {
                event.target.parentElement.querySelectorAll('.nav-tab').forEach(btn => btn.classList.remove('active'));
                event.target.classList.add('active');
            }
        }

        // Load Staff Profile
        function loadStaffProfile() {
            fetch(`${API_URL}?action=get_staff_profile`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const profile = data.data;
                        const html = `
                            <div style="max-width: 600px;">
                                <div style="margin-bottom: 20px;">
                                    <label style="color: #64748b; font-size: 13px;">Name</label>
                                    <p style="font-size: 16px; font-weight: 600; color: #0f172a;">${profile.name}</p>
                                </div>
                                <div style="margin-bottom: 20px;">
                                    <label style="color: #64748b; font-size: 13px;">Email</label>
                                    <p style="font-size: 16px; font-weight: 600; color: #0f172a;">${profile.email}</p>
                                </div>
                                <div style="margin-bottom: 20px;">
                                    <label style="color: #64748b; font-size: 13px;">Phone</label>
                                    <p style="font-size: 16px; font-weight: 600; color: #0f172a;">${profile.phone || 'Not provided'}</p>
                                </div>
                                <div style="margin-bottom: 20px;">
                                    <label style="color: #64748b; font-size: 13px;">Position</label>
                                    <p style="font-size: 16px; font-weight: 600; color: #0f172a;">${profile.position || 'Staff'}</p>
                                </div>
                            </div>
                        `;
                        document.getElementById('profileContainer').innerHTML = html;
                    }
                })
                .catch(error => console.error('Error:', error));
        }

        // Edit Profile Modal Functions
        function openEditProfileModal() {
            fetch(`${API_URL}?action=get_staff_profile`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const profile = data.data;
                        document.getElementById('editEmail').value = profile.email;
                        document.getElementById('editPhone').value = profile.phone || '';
                        document.getElementById('editPassword').value = '';
                        document.getElementById('editPasswordConfirm').value = '';
                        document.getElementById('editProfileModal').classList.add('active');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showAlert('danger', 'Error loading profile');
                });
        }

        function closeEditProfileModal() {
            document.getElementById('editProfileModal').classList.remove('active');
            document.getElementById('editProfileForm').reset();
        }

        document.getElementById('editProfileForm')?.addEventListener('submit', function(e) {
            e.preventDefault();

            const phone = document.getElementById('editPhone').value;
            const email = document.getElementById('editEmail').value;
            const password = document.getElementById('editPassword').value;
            const passwordConfirm = document.getElementById('editPasswordConfirm').value;

            if (!email) {
                showAlert('danger', 'Email is required');
                return;
            }

            if (password && password.length < 8) {
                showAlert('danger', 'Password must be at least 8 characters long');
                return;
            }

            if (password && password !== passwordConfirm) {
                showAlert('danger', 'Passwords do not match');
                return;
            }

            let updates = 0;
            const totalUpdates = (email ? 1 : 0) + (phone ? 1 : 0) + (password ? 1 : 0);

            if (email) {
                updateProfileField('email', email, () => {
                    updates++;
                    if (updates === totalUpdates) finishProfileUpdate();
                });
            }

            if (phone) {
                updateProfileField('phone', phone, () => {
                    updates++;
                    if (updates === totalUpdates) finishProfileUpdate();
                });
            }

            if (password) {
                updateProfileField('password', password, () => {
                    updates++;
                    if (updates === totalUpdates) finishProfileUpdate();
                });
            }

            if (totalUpdates === 0) {
                showAlert('danger', 'No changes to save');
            }
        });

        function updateProfileField(field, value, callback) {
            const formData = new FormData();
            formData.append('action', 'update_staff_profile');
            formData.append('field', field);
            formData.append('value', value);

            fetch(API_URL, { method: 'POST', body: formData })
                .then(response => response.json())
                .then(data => {
                    if (callback) callback();
                })
                .catch(error => console.error('Error:', error));
        }

        function finishProfileUpdate() {
            closeEditProfileModal();
            loadStaffProfile();
            showAlert('success', 'Profile updated successfully');
        }

        // Show Alert
        function showAlert(type, message) {
            const alertDiv = document.createElement('div');
            alertDiv.className = type === 'success' ? 'alert alert-success' : 'alert alert-danger';
            alertDiv.textContent = message;
            alertDiv.style.position = 'fixed';
            alertDiv.style.top = '20px';
            alertDiv.style.right = '20px';
            alertDiv.style.zIndex = '10000';
            alertDiv.style.minWidth = '300px';
            alertDiv.style.maxWidth = '500px';
            alertDiv.style.padding = '15px';
            alertDiv.style.borderRadius = '8px';
            alertDiv.style.boxShadow = '0 5px 15px rgba(0,0,0,0.2)';
            
            if (type === 'success') {
                alertDiv.style.background = 'rgba(16, 156, 61, 0.1)';
                alertDiv.style.color = '#109c3d';
                alertDiv.style.borderLeft = '4px solid #109c3d';
            } else {
                alertDiv.style.background = 'rgba(239, 68, 68, 0.1)';
                alertDiv.style.color = '#ef4444';
                alertDiv.style.borderLeft = '4px solid #ef4444';
            }
            
            document.body.appendChild(alertDiv);
            
            setTimeout(() => {
                alertDiv.remove();
            }, 4000);
        }

        // Load initial data
        loadDashboardStats();
        loadUpcomingAssignments();
    </script>
</body>
</html>
