<?php
/**
 * Staff Dashboard - Real-Time Implementation
 * Handles inquiries and appointments with real-time approve/decline functionality
 */

require_once '../config.php';

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

$staff_id = $_SESSION['user_id'];
$staff_name = $_SESSION['user_name'] ?? 'Staff Member';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Staff Dashboard - Zemaraim</title>
    <link rel="stylesheet" href="../assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="../assets/css/fontawesome.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Poppins', sans-serif; background: #f5f7fa; color: #333; }
        
        /* Layout */
        .dashboard-wrapper {
            display: flex;
            min-height: 100vh;
        }
        
        /* Sidebar */
        .sidebar {
            width: 280px;
            background: #2c3e50;
            color: white;
            position: fixed;
            height: 100vh;
            overflow-y: auto;
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
            z-index: 1000;
            transition: transform 0.3s ease;
        }
        
        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid rgba(255,255,255,0.1);
            text-align: center;
        }
        
        .sidebar-header h2 {
            font-size: 18px;
            margin: 0;
            color: #667eea;
        }
        
        .sidebar-nav {
            padding: 0;
            list-style: none;
            margin-top: 20px;
        }
        
        .sidebar-nav li {
            margin: 0;
        }
        
        .sidebar-nav a {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 15px 20px;
            color: rgba(255,255,255,0.7);
            text-decoration: none;
            transition: all 0.3s ease;
            border-left: 4px solid transparent;
        }
        
        .sidebar-nav a:hover,
        .sidebar-nav a.active {
            background: rgba(102,126,234,0.15);
            color: white;
            border-left-color: #667eea;
        }
        
        .sidebar-nav span {
            font-size: 14px;
        }
        
        .sidebar-badge {
            margin-left: auto;
            background: #667eea;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
        }
        
        .toggle-sidebar {
            display: none;
            position: fixed;
            top: 20px;
            left: 20px;
            z-index: 1001;
            background: #667eea;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 6px;
            cursor: pointer;
        }
        
        /* Main Content */
        .main-content {
            flex: 1;
            margin-left: 280px;
            transition: margin-left 0.3s ease;
        }
        
        /* Header */
        .nav-header { 
            background: white; 
            padding: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 100;
        }
        
        .nav-header h1 { font-size: 22px; color: #667eea; margin: 0; font-weight: 700; }
        
        .user-menu {
            display: flex;
            align-items: center;
            gap: 20px;
        }
        
        .user-menu .avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #667eea;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
        }
        
        .logout-btn {
            background: #dc3545;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 5px;
            cursor: pointer;
            text-decoration: none;
            transition: background 0.3s;
        }
        
        .logout-btn:hover { background: #c82333; }
        
        /* Container */
        .container { max-width: 1200px; margin: 0 auto; padding: 30px 20px; }
        
        h2 {
            font-size: 20px;
            color: #333;
            margin-bottom: 20px;
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        /* Section */
        .section {
            display: none;
        }
        
        .section.active {
            display: block;
            animation: fadeIn 0.3s ease;
        }
        
        /* Stats Grid */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.06);
            border-left: 4px solid #667eea;
            text-align: center;
        }
        
        .stat-card h3 { font-size: 11px; color: #999; text-transform: uppercase; margin-bottom: 10px; }
        .stat-card .number { font-size: 28px; font-weight: 700; color: #667eea; }
        
        /* Panel */
        .panel {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.06);
            padding: 25px;
            margin-bottom: 30px;
        }

        .assign-card {
            padding: 16px;
            border: 1px solid #e5e7eb;
            border-radius: 10px;
            background: #f8fafc;
            margin-top: 10px;
        }

        .assign-grid {
            display: grid;
            grid-template-columns: minmax(220px, 2fr) minmax(220px, 2fr) auto;
            gap: 12px;
            align-items: end;
        }

        .assign-toolbar {
            margin-top: 12px;
            display: flex;
            gap: 12px;
            align-items: center;
            flex-wrap: wrap;
        }

        .assign-toolbar .form-group {
            margin: 0;
            min-width: 220px;
            flex: 1 1 260px;
        }

        .assign-current {
            margin-top: 8px;
            font-size: 13px;
            color: #4b5563;
        }

        .assign-hint {
            font-size: 12px;
            color: #6b7280;
            margin-top: 8px;
        }

        .assign-table {
            margin-top: 10px;
            max-height: 420px;
            overflow: auto;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            background: #fff;
        }

        .assign-status {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 999px;
            font-size: 11px;
            background: #e2e8f0;
            color: #334155;
            text-transform: capitalize;
        }

        .assign-status.unassigned { background: #e5e7eb; color: #374151; }
        .assign-status.assigned { background: #dbeafe; color: #1e40af; }
        .assign-status.working { background: #fef3c7; color: #92400e; }
        .assign-status.finished_pending_admin { background: #fed7aa; color: #9a3412; }
        .assign-status.finished_approved { background: #dcfce7; color: #166534; }

        .assign-thumb {
            width: 64px;
            height: 48px;
            object-fit: cover;
            border-radius: 8px;
            border: 1px solid #dbe1ec;
            background: #f1f5f9;
        }

        .assign-thumb-fallback {
            width: 64px;
            height: 48px;
            border-radius: 8px;
            border: 1px solid #dbe1ec;
            background: linear-gradient(135deg, #c7d2fe 0%, #e2e8f0 100%);
            color: #475569;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
        }
        
        /* Cards Grid */
        .cards-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
            gap: 20px;
        }
        
        .card {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            border-left: 4px solid #667eea;
            transition: all 0.3s ease;
        }
        
        .card:hover {
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }
        
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: start;
            margin-bottom: 15px;
        }
        
        .card-title { font-weight: 600; color: #333; font-size: 16px; }
        
        .card-meta { color: #999; font-size: 12px; margin-top: 5px; }
        
        .badge {
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            white-space: nowrap;
        }
        
        .badge-pending { background: #fff3cd; color: #856404; }
        .badge-responded { background: #d1ecf1; color: #0c5460; }
        .badge-approved { background: #d4edda; color: #155724; }
        .badge-declined { background: #f8d7da; color: #721c24; }
        .badge-scheduled { background: #d4edda; color: #155724; }
        
        .card-content {
            font-size: 14px;
            color: #666;
            line-height: 1.6;
            margin-bottom: 15px;
        }
        
        .card-content strong { color: #333; }
        
        .customer-info {
            margin: 15px 0;
            padding: 12px;
            background: white;
            border-radius: 6px;
            font-size: 13px;
        }
        
        .customer-info-row { margin: 5px 0; }
        
        /* Buttons */
        .btn {
            padding: 10px 16px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            font-size: 13px;
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .btn:hover { background: #764ba2; }
        
        .btn-small {
            padding: 6px 12px;
            font-size: 12px;
        }
        
        .btn-secondary { background: #999; }
        .btn-secondary:hover { background: #777; }
        
        .btn-success { background: #28a745; }
        .btn-success:hover { background: #218838; }
        
        .btn-danger { background: #dc3545; }
        .btn-danger:hover { background: #c82333; }
        
        .card-actions {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        
        /* Table */
        .table-responsive { overflow-x: auto; }
        
        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }
        
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #e0e0e0;
        }
        
        th {
            background: #f8f9fa;
            font-weight: 600;
            color: #333;
        }
        
        tr:hover { background: #f8f9fa; }
        
        /* Empty & Loading */
        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #999;
        }
        
        .empty-state-icon { font-size: 48px; margin-bottom: 15px; }
        
        .loading {
            text-align: center;
            color: #999;
            padding: 40px 20px;
        }
        
        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        /* Alert */
        .alert {
            padding: 12px 16px;
            border-radius: 6px;
            margin-bottom: 15px;
            font-size: 13px;
        }
        
        .alert-success { background: #d4edda; color: #155724; }
        .alert-error { background: #f8d7da; color: #721c24; }
        
        /* Responsive */
        @media (max-width: 1024px) {
            .sidebar { width: 250px; }
            .main-content { margin-left: 250px; }
            .cards-grid { grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); }
        }
        
        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                height: auto;
                position: static;
                box-shadow: none;
                transform: none !important;
            }
            
            .main-content {
                margin-left: 0;
            }
            
            .toggle-sidebar { display: block; }
            
            .sidebar.hidden { display: none; }
            
            .nav-header {
                flex-direction: column;
                gap: 15px;
                text-align: center;
            }
            
            .nav-header h1 { font-size: 18px; }
            
            .user-menu {
                width: 100%;
                justify-content: space-between;
            }
            
            .container { padding: 15px 10px; }
            
            h2 { font-size: 18px; }
            
            .cards-grid {
                grid-template-columns: 1fr;
            }
            
            .stat-card {
                padding: 15px;
            }
            
            .stat-card .number { font-size: 20px; }
            
            .card { padding: 15px; }
            
            .card-title { font-size: 14px; }
            
            .card-content { font-size: 12px; }
            
            .card-actions {
                flex-direction: column;
            }
            
            .btn {
                width: 100%;
                text-align: center;
            }
            
            table { font-size: 12px; }
            
            th, td { padding: 8px; }
            
            .sidebar-nav a { padding: 12px 15px; }

            .assign-grid { grid-template-columns: 1fr; }
            .assign-toolbar { flex-direction: column; align-items: stretch; }
            .assign-table table { min-width: 820px; }
        }
        
        @media (max-width: 640px) {
            .nav-header h1 { font-size: 16px; }
            
            .user-menu {
                gap: 10px;
                font-size: 13px;
            }
            
            .user-menu .avatar { width: 35px; height: 35px; }
            
            .logout-btn {
                padding: 6px 12px;
                font-size: 12px;
            }
            
            .stat-card h3 { font-size: 10px; }
            .stat-card .number { font-size: 18px; }
            
            .card-title { font-size: 13px; }
            
            .btn-small { padding: 5px 10px; font-size: 11px; }
            
            table { font-size: 11px; }
        }
        
        @media (max-width: 480px) {
            .sidebar-header h2 { font-size: 16px; }
            
            .nav-header h1 { font-size: 14px; }
            
            h2 { font-size: 14px; }
            
            .stat-card .number { font-size: 16px; }
            
            .card-title { font-size: 12px; }
            
            .btn { font-size: 10px; padding: 6px 10px; }
        }
    </style>
</head>
<body>

    <div class="dashboard-wrapper">
        <!-- Sidebar -->
        <div class="sidebar" id="sidebar">
            <div class="sidebar-header">
                <h2>Staff</h2>
            </div>
            <ul class="sidebar-nav">
                <li>
                    <a href="#" data-section="overview" class="nav-link active">
                         Overview
                        <span class="sidebar-badge" id="badge-overview">4</span>
                    </a>
                </li>
                <li>
                    <a href="#" data-section="inquiries" class="nav-link">
                        💬 Inquiries
                        <span class="sidebar-badge" id="badge-inquiries">0</span>
                    </a>
                </li>
                <li>
                    <a href="#" data-section="appointments" class="nav-link">
                        📅 Appointments
                        <span class="sidebar-badge" id="badge-appointments">0</span>
                    </a>
                </li>
                <li>
                    <a href="#" data-section="properties" class="nav-link">
                        🏠 Properties
                    </a>
                </li>
                <li>
                    <a href="#" data-section="assignments" class="nav-link">
                        Assignments
                    </a>
                </li>
            </ul>
        </div>

        <!-- Main Content -->
        <div class="main-content">
            <!-- Toggle Button -->
            <button class="toggle-sidebar" id="toggleBtn">☰</button>

            <!-- Header -->
            <div class="nav-header">
                <h1> Staff Dashboard</h1>
                <div class="user-menu">
                    <span><?php echo htmlspecialchars($staff_name); ?></span>
                    <div class="avatar"><?php echo strtoupper(substr($staff_name, 0, 1)); ?></div>
                    <a href="../logout.php" class="logout-btn">Logout</a>
                </div>
            </div>

            <!-- Container -->
            <div class="container">

                <!-- Overview Section -->
                <section class="section active" id="overview">
                    <h2>📊 Real-Time Statistics</h2>
                    <div class="stats-grid">
                        <div class="stat-card">
                            <h3>💬 Pending Inquiries</h3>
                            <div class="number" id="stat-inquiries">0</div>
                        </div>
                        <div class="stat-card">
                            <h3>📅 Pending Visits</h3>
                            <div class="number" id="stat-visits">0</div>
                        </div>
                        <div class="stat-card">
                            <h3>🏠 Properties</h3>
                            <div class="number" id="stat-properties">0</div>
                        </div>
                        <div class="stat-card">
                            <h3>👥 Customers</h3>
                            <div class="number" id="stat-customers">0</div>
                        </div>
                    </div>
                </section>

                <!-- Inquiries Section -->
                <section class="section" id="inquiries">
                    <h2>💬 Customer Inquiries - Pending Approval</h2>
                    <div class="panel">
                        <div id="inquiries-container" class="cards-grid">
                            <div class="loading">
                                <div class="spinner"></div>
                                <p>Loading inquiries...</p>
                            </div>
                        </div>
                    </div>
                </section>

                <!-- Appointments Section -->
                <section class="section" id="appointments">
                    <h2>📅 Scheduled Visits - Pending Approval</h2>
                    <div class="panel">
                        <div id="visits-container" class="cards-grid">
                            <div class="loading">
                                <div class="spinner"></div>
                                <p>Loading appointments...</p>
                            </div>
                        </div>
                    </div>
                </section>

                <section class="section" id="properties">
                    <h2>🏠 Property Listings</h2>
                    <div class="panel">
                        <div class="table-responsive">
                            <table id="properties-table">
                                <thead>
                                    <tr>
                                        <th>Title</th>
                                        <th>Location</th>
                                        <th>Price</th>
                                        <th>Beds</th>
                                        <th>Baths</th>
                                        <th>Inquiries</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody id="properties-body">
                                    <tr>
                                        <td colspan="7" class="loading">
                                            <div class="spinner"></div>
                                            Loading properties...
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </section>

                <section class="section" id="assignments">
                    <h2>Assign Property To Broker</h2>
                    <div class="panel">
                        <div class="assign-card">
                            <div class="assign-grid">
                                <div class="form-group">
                                    <label for="assignPropertySelect">Property</label>
                                    <select id="assignPropertySelect" class="btn" style="width:100%; background:#fff; color:#333; border:1px solid #d1d5db;" onchange="handleAssignmentPropertySelection()">
                                        <option value="">Select a property</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="assignBrokerSelect">Broker</label>
                                    <select id="assignBrokerSelect" class="btn" style="width:100%; background:#fff; color:#333; border:1px solid #d1d5db;">
                                        <option value="0">Unassigned</option>
                                    </select>
                                </div>
                                <button class="btn btn-success" type="button" onclick="assignPropertyToBroker()">Assign Now</button>
                            </div>
                            <div class="assign-toolbar">
                                <div class="form-group">
                                    <label for="assignStatusFilter">Filter By Work Status</label>
                                    <select id="assignStatusFilter" class="btn" style="width:100%; background:#fff; color:#333; border:1px solid #d1d5db;" onchange="handleAssignmentFilterChange()">
                                        <option value="all">All</option>
                                        <option value="assigned">Assigned (Not Confirmed)</option>
                                        <option value="working">Working</option>
                                        <option value="finished">Finished (Pending/Approved)</option>
                                        <option value="unassigned">Unassigned</option>
                                    </select>
                                </div>
                            </div>
                            <div id="assignmentCurrentInfo" class="assign-current">Current assignment: -</div>
                            <div class="assign-hint">Auto-refresh every 10 seconds keeps this list current.</div>
                            <div id="assignmentTableWrap" class="assign-table">
                                <div style="padding: 14px; color:#6b7280;">Loading assignment data...</div>
                            </div>
                        </div>
                    </div>
                </section>

            </div>
        </div>
    </div>

    <script>
        const POLLING_INTERVAL = 10000; // 10 seconds
        let intervals = {};
        let currentSection = 'overview';
        let propertyAssignmentCache = [];
        let brokerAssignmentCache = [];
        let assignmentStatusFilter = 'all';
        
        // Initialize
        document.addEventListener('DOMContentLoaded', function() {
            console.log('Staff Dashboard Initialized');
            
            // Sidebar navigation
            document.querySelectorAll('.nav-link').forEach(link => {
                link.addEventListener('click', function(e) {
                    e.preventDefault();
                    const section = this.getAttribute('data-section');
                    showSection(section);
                    
                    // Close sidebar on mobile after click
                    if (window.innerWidth <= 768) {
                        document.getElementById('sidebar').classList.add('hidden');
                    }
                });
            });
            
            // Toggle sidebar button
            document.getElementById('toggleBtn').addEventListener('click', function() {
                document.getElementById('sidebar').classList.toggle('hidden');
            });
            
            // Load data
            loadData();
            
            // Start polling
            intervals.all = setInterval(loadData, POLLING_INTERVAL);
        });
        
        function showSection(sectionId) {
            currentSection = sectionId;
            // Hide all sections
            document.querySelectorAll('.section').forEach(s => s.classList.remove('active'));
            
            // Show selected section
            document.getElementById(sectionId).classList.add('active');
            
            // Update nav links
            document.querySelectorAll('.nav-link').forEach(link => {
                link.classList.remove('active');
            });
            document.querySelector(`[data-section="${sectionId}"]`).classList.add('active');
            
            // Load section data
            if (sectionId === 'overview') {
                loadStats();
            } else if (sectionId === 'inquiries') {
                loadInquiries();
            } else if (sectionId === 'appointments') {
                loadVisits();
            } else if (sectionId === 'properties') {
                loadProperties();
            } else if (sectionId === 'assignments') {
                loadPropertyAssignments();
            }
        }
        
        function loadData() {
            loadStats();
            loadInquiries();
            loadVisits();
            if (currentSection === 'assignments') {
                loadPropertyAssignments();
            }
        }
        
        // Load Statistics
        function loadStats() {
            fetch('../api/staff/get-stats.php')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const pending_inquiries = Math.max(0, data.stats.pending_inquiries);
                        const upcoming_visits = Math.max(0, data.stats.upcoming_visits);
                        document.getElementById('stat-inquiries').textContent = pending_inquiries;
                        document.getElementById('stat-visits').textContent = upcoming_visits;
                        document.getElementById('stat-properties').textContent = data.stats.total_properties;
                        document.getElementById('stat-customers').textContent = data.stats.total_customers;
                        document.getElementById('badge-inquiries').textContent = pending_inquiries;
                        document.getElementById('badge-appointments').textContent = upcoming_visits;
                        console.log('Stats loaded');
                    }
                })
                .catch(e => console.error('Stats error:', e));
        }
        
        // Load Inquiries
        function loadInquiries() {
            fetch('../api/staff/get-pending-inquiries.php')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayInquiries(data.inquiries);
                        console.log('Inquiries loaded:', data.count);
                    } else {
                        showError('inquiries-container', data.message || 'Failed to load inquiries');
                    }
                })
                .catch(e => {
                    console.error('Inquiries error:', e);
                    showError('inquiries-container', 'Error loading inquiries');
                });
        }
        
        function displayInquiries(inquiries) {
            const container = document.getElementById('inquiries-container');
            const pending = inquiries.filter(i => i.status === 'pending');
            const responses = inquiries.filter(i => i.status === 'responded');
            const approved = inquiries.filter(i => i.status === 'approved');
            const declined = inquiries.filter(i => i.status === 'declined');
            
            if (inquiries.length === 0) {
                container.innerHTML = '<div class="empty-state"><div class="empty-state-icon">ðŸŽ‰</div><p>No inquiries.</p></div>';
                return;
            }
            
            let html = '';
            
            // Pending
            pending.forEach(inq => {
                html += `
                    <div class="card" style="border-left-color: #ffc107;">
                        <div class="card-header">
                            <div class="card-title">${inq.property_title || 'Inquiry'}</div>
                            <span class="badge badge-pending">Pending</span>
                        </div>
                        <div class="card-content">${inq.message}</div>
                        <div class="customer-info">
                            <div><strong>👤 ${inq.customer_name}</strong> | ☎️ ${inq.phone}</div>
                            <div class="card-meta">✉️ ${inq.email}</div>
                        </div>
                        <div class="card-actions">
                            <button class="btn btn-success btn-small" onclick="approveInquiry(${inq.id})"> Approve</button>
                            <button class="btn btn-danger btn-small" onclick="declineInquiry(${inq.id})"> Decline</button>
                            <a href="mailto:${inq.email}" class="btn btn-secondary btn-small">✉️ Email</a>
                        </div>
                    </div>
                `;
            });
            
            // Responded
            responses.forEach(inq => {
                html += `
                    <div class="card" style="border-left-color: #17a2b8;">
                        <div class="card-header">
                            <div class="card-title">${inq.property_title || 'Inquiry'}</div>
                            <span class="badge badge-responded">Responded</span>
                        </div>
                        <div class="card-content"><strong>Message:</strong> ${inq.message}</div>
                        <div class="customer-info" style="background: #d1ecf1;">
                            <strong>Your Response:</strong><br>${inq.response}
                        </div>
                        <div class="card-actions">
                            <button class="btn btn-success btn-small" onclick="approveInquiry(${inq.id})"> Approve</button>
                            <button class="btn btn-danger btn-small" onclick="declineInquiry(${inq.id})"> Decline</button>
                        </div>
                    </div>
                `;
            });
            
            // Approved
            approved.forEach(inq => {
                html += `
                    <div class="card" style="border-left-color: #28a745; opacity: 0.8;">
                        <div class="card-header">
                            <div class="card-title">${inq.property_title || 'Inquiry'}</div>
                            <span class="badge badge-approved"> Approved</span>
                        </div>
                        <div class="card-content">${inq.message}</div>
                        <div class="customer-info">
                            <div><strong>👤 ${inq.customer_name}</strong></div>
                        </div>
                    </div>
                `;
            });
            
            // Declined
            declined.forEach(inq => {
                html += `
                    <div class="card" style="border-left-color: #dc3545; opacity: 0.8;">
                        <div class="card-header">
                            <div class="card-title">${inq.property_title || 'Inquiry'}</div>
                            <span class="badge badge-declined"> Declined</span>
                        </div>
                        <div class="card-content">${inq.message}</div>
                        <div class="customer-info">
                            <div><strong>👤 ${inq.customer_name}</strong></div>
                        </div>
                    </div>
                `;
            });
            
            container.innerHTML = html;
        }
        
        // Approve/Decline Inquiry
        function approveInquiry(inquiryId) {
            if (!confirm('Approve this inquiry?')) return;
            
            fetch('../api/staff/approve-inquiry.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({inquiry_id: inquiryId, action: 'approve'})
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    showAlert('Inquiry approved!', 'success');
                    loadInquiries();
                    loadStats();
                } else {
                    showAlert('Error', 'error');
                }
            })
            .catch(e => console.error(e));
        }
        
        function declineInquiry(inquiryId) {
            if (!confirm('Decline this inquiry?')) return;
            
            fetch('../api/staff/approve-inquiry.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({inquiry_id: inquiryId, action: 'decline'})
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    showAlert('Inquiry declined!', 'success');
                    loadInquiries();
                    loadStats();
                } else {
                    showAlert('Error', 'error');
                }
            })
            .catch(e => console.error(e));
        }
        
        // Load Visits
        function loadVisits() {
            fetch('../api/staff/get-scheduled-visits.php')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayVisits(data.appointments);
                        console.log('Visits loaded:', data.count);
                    } else {
                        showError('visits-container', data.message || 'Failed to load visits');
                    }
                })
                .catch(e => {
                    console.error('Visits error:', e);
                    showError('visits-container', 'Error loading visits');
                });
        }
        
        function displayVisits(appointments) {
            const container = document.getElementById('visits-container');
            const pending = appointments.filter(a => a.status === 'pending');
            const approved = appointments.filter(a => a.status === 'approved');
            const declined = appointments.filter(a => a.status === 'declined');
            const scheduled = appointments.filter(a => a.status === 'scheduled');
            const completed = appointments.filter(a => a.status === 'completed');
            
            if (appointments.length === 0) {
                container.innerHTML = '<div class="empty-state"><div class="empty-state-icon">ðŸ“­</div><p>No appointments.</p></div>';
                return;
            }
            
            let html = '';
            
            // Pending
            pending.forEach(apt => {
                html += `
                    <div class="card" style="border-left-color: #ffc107;">
                        <div class="card-header">
                            <div class="card-title">${apt.property_title || 'Visit'}</div>
                            <span class="badge badge-pending">Pending</span>
                        </div>
                        <div class="card-content">
                             📍 ${apt.city} | 🗓️ ${formatDate(apt.appointment_date)} | ⏰ ${apt.appointment_time}
                        </div>
                        <div class="customer-info">
                            <div><strong>👤 ${apt.customer_name}</strong> | ☎️ ${apt.phone}</div>
                            <div class="card-meta">✉️ ${apt.email}</div>
                        </div>
                        <div class="card-actions">
                            <button class="btn btn-success btn-small" onclick="approveAppointment(${apt.id})"> Approve</button>
                            <button class="btn btn-danger btn-small" onclick="declineAppointment(${apt.id})"> Decline</button>
                        </div>
                    </div>
                `;
            });
            
            // Approved
            approved.forEach(apt => {
                html += `
                    <div class="card" style="border-left-color: #28a745; opacity: 0.85;">
                        <div class="card-header">
                            <div class="card-title">${apt.property_title || 'Visit'}</div>
                            <span class="badge badge-approved"> Approved</span>
                        </div>
                        <div class="card-content">
                             📍 ${apt.city} | 🗓️ ${formatDate(apt.appointment_date)} | ⏰ ${apt.appointment_time}
                        </div>
                        <div class="customer-info"><strong>👤 ${apt.customer_name}</strong></div>
                    </div>
                `;
            });
            
            // Declined
            declined.forEach(apt => {
                html += `
                    <div class="card" style="border-left-color: #dc3545; opacity: 0.85;">
                        <div class="card-header">
                            <div class="card-title">${apt.property_title || 'Visit'}</div>
                            <span class="badge badge-declined"> Declined</span>
                        </div>
                        <div class="card-content">
                            📍 ${apt.city} | 🗓️ ${formatDate(apt.appointment_date)} | ⏰ ${apt.appointment_time}
                        </div>
                        <div class="customer-info"><strong>👤 ${apt.customer_name}</strong></div>
                    </div>
                `;
            });
            
            container.innerHTML = html;
        }
        
        function approveAppointment(appointmentId) {
            if (!confirm('Approve this visit?')) return;
            
            fetch('../api/staff/approve-appointment.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({appointment_id: appointmentId, action: 'approve'})
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    showAlert('Visit approved!', 'success');
                    loadVisits();
                    loadStats();
                } else {
                    showAlert('Error', 'error');
                }
            })
            .catch(e => console.error(e));
        }
        
        function declineAppointment(appointmentId) {
            if (!confirm('Decline this visit?')) return;
            
            fetch('../api/staff/approve-appointment.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({appointment_id: appointmentId, action: 'decline'})
            })
            .then(r => r.json())
            .then(data => {
                if (data.success) {
                    showAlert('Visit declined!', 'success');
                    loadVisits();
                    loadStats();
                } else {
                    showAlert('Error', 'error');
                }
            })
            .catch(e => console.error(e));
        }
        
        // Load Properties
        function loadProperties() {
            fetch('../api/staff/get-properties.php')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayProperties(data.properties);
                    }
                })
                .catch(e => {
                    console.error('Properties error:', e);
                    document.getElementById('properties-body').innerHTML = '<tr><td colspan="7" class="loading">Error loading</td></tr>';
                });
        }
        
        function displayProperties(properties) {
            const tbody = document.getElementById('properties-body');
            if (properties.length === 0) {
                tbody.innerHTML = '<tr><td colspan="7" class="empty-state">No properties</td></tr>';
                return;
            }
            
            let html = '';
            properties.forEach(prop => {
                html += `
                    <tr>
                        <td><strong>${prop.title}</strong></td>
                        <td>${prop.city}</td>
                        <td>$${parseInt(prop.price).toLocaleString()}</td>
                        <td>${prop.bedrooms}</td>
                        <td>${prop.bathrooms}</td>
                        <td><span class="badge badge-info">${prop.inquiry_count}</span></td>
                        <td><button class="btn btn-small" onclick="alert('Edit property')">âœï¸</button></td>
                    </tr>
                `;
            });
            tbody.innerHTML = html;
        }

        function escapeStaffHtml(value) {
            return String(value ?? '')
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#39;');
        }

        function normalizeAssignmentStatus(status) {
            return String(status || 'unassigned').trim().toLowerCase();
        }

        function getAssignmentStatusLabel(statusValue) {
            const normalized = normalizeAssignmentStatus(statusValue);
            const map = {
                unassigned: 'Unassigned',
                assigned: 'Assigned',
                working: 'Working',
                finished_pending_admin: 'Finished - Pending Admin',
                finished_approved: 'Finished - Approved'
            };
            return map[normalized] || normalized.replace(/_/g, ' ');
        }

        function normalizeDashboardImagePath(path) {
            const imagePath = String(path || '').trim();
            if (!imagePath) return '';
            if (/^(https?:)?\/\//i.test(imagePath)) return imagePath;
            if (imagePath.startsWith('/')) return imagePath;
            return '../' + imagePath.replace(/^\.?\//, '');
        }

        function getFilteredAssignments() {
            if (assignmentStatusFilter === 'all') return propertyAssignmentCache;
            return propertyAssignmentCache.filter((propertyItem) => {
                const currentStatus = normalizeAssignmentStatus(propertyItem.assignment_status);
                if (assignmentStatusFilter === 'working') return currentStatus === 'working';
                if (assignmentStatusFilter === 'finished') {
                    return currentStatus === 'finished_pending_admin' || currentStatus === 'finished_approved';
                }
                return currentStatus === assignmentStatusFilter;
            });
        }

        function handleAssignmentFilterChange() {
            const filterSelect = document.getElementById('assignStatusFilter');
            assignmentStatusFilter = String(filterSelect?.value || 'all');
            renderAssignmentTable(getFilteredAssignments());
        }

        async function loadPropertyAssignments() {
            const propertySelect = document.getElementById('assignPropertySelect');
            const brokerSelect = document.getElementById('assignBrokerSelect');
            const tableWrap = document.getElementById('assignmentTableWrap');
            const filterSelect = document.getElementById('assignStatusFilter');
            if (!propertySelect || !brokerSelect || !tableWrap) return;

            try {
                const prevPropertyId = propertySelect.value || '';
                const prevBrokerId = brokerSelect.value || '0';
                const response = await fetch('../api/staff/get-property-assignment-data.php');
                const data = await response.json();

                if (!data.success) {
                    tableWrap.innerHTML = `<div style="padding: 14px; color:#b91c1c;">Error: ${escapeStaffHtml(data.message || 'Failed to load assignment data')}</div>`;
                    return;
                }

                propertyAssignmentCache = Array.isArray(data.properties) ? data.properties : [];
                brokerAssignmentCache = Array.isArray(data.brokers) ? data.brokers : [];
                if (filterSelect) {
                    assignmentStatusFilter = String(filterSelect.value || assignmentStatusFilter || 'all');
                }

                renderAssignmentSelectors(prevPropertyId, prevBrokerId);
                renderAssignmentTable(getFilteredAssignments());
                handleAssignmentPropertySelection();
            } catch (error) {
                tableWrap.innerHTML = `<div style="padding: 14px; color:#b91c1c;">Error: ${escapeStaffHtml(error.message)}</div>`;
            }
        }

        function renderAssignmentSelectors(selectedPropertyId, selectedBrokerId) {
            const propertySelect = document.getElementById('assignPropertySelect');
            const brokerSelect = document.getElementById('assignBrokerSelect');
            if (!propertySelect || !brokerSelect) return;

            const propertyOptions = ['<option value="">Select a property</option>'];
            propertyAssignmentCache.forEach((prop) => {
                const brokerText = prop.broker_name || 'Unassigned';
                propertyOptions.push(
                    `<option value="${Number(prop.id)}">${escapeStaffHtml(prop.title || ('Property #' + prop.id))} (${escapeStaffHtml(brokerText)})</option>`
                );
            });
            propertySelect.innerHTML = propertyOptions.join('');
            propertySelect.value = propertyAssignmentCache.some((p) => String(p.id) === String(selectedPropertyId))
                ? String(selectedPropertyId)
                : '';

            const brokerOptions = ['<option value="0">Unassigned</option>'];
            brokerAssignmentCache.forEach((broker) => {
                brokerOptions.push(`<option value="${escapeStaffHtml(String(broker.id || '0'))}">${escapeStaffHtml(broker.full_name)}</option>`);
            });
            brokerSelect.innerHTML = brokerOptions.join('');
            brokerSelect.value = brokerAssignmentCache.some((b) => String(b.id) === String(selectedBrokerId || ''))
                ? String(selectedBrokerId)
                : '0';
        }

        function renderAssignmentTable(properties) {
            const tableWrap = document.getElementById('assignmentTableWrap');
            if (!tableWrap) return;

            if (!Array.isArray(properties) || properties.length === 0) {
                tableWrap.innerHTML = '<div style="padding: 14px; color:#6b7280;">No properties found.</div>';
                return;
            }

            let html = '<table><thead><tr><th>ID</th><th>Image</th><th>Property</th><th>Location</th><th>Listing Status</th><th>Work Status</th><th>Current Broker</th></tr></thead><tbody>';
            properties.forEach((prop) => {
                const workflowStatus = normalizeAssignmentStatus(prop.assignment_status);
                const reviewStatus = normalizeAssignmentStatus(prop.assignment_review_status);
                const reviewText = `Review: ${getAssignmentStatusLabel(reviewStatus)}`;
                const imageUrl = normalizeDashboardImagePath(prop.image_url || '');
                const imageCell = imageUrl
                    ? `<img src="${escapeStaffHtml(imageUrl)}" alt="Property image" class="assign-thumb" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';"><div class="assign-thumb-fallback" style="display:none;"><i class="fas fa-home"></i></div>`
                    : '<div class="assign-thumb-fallback"><i class="fas fa-home"></i></div>';
                html += `
                    <tr>
                        <td>#${Number(prop.id)}</td>
                        <td>${imageCell}</td>
                        <td>${escapeStaffHtml(prop.title || ('Property #' + prop.id))}</td>
                        <td>${escapeStaffHtml(prop.address || '')}${prop.city ? ', ' + escapeStaffHtml(prop.city) : ''}</td>
                        <td><span class="assign-status">${escapeStaffHtml(prop.status || 'unknown')}</span></td>
                        <td>
                            <span class="assign-status ${escapeStaffHtml(workflowStatus)}">${escapeStaffHtml(getAssignmentStatusLabel(workflowStatus))}</span>
                            <div style="font-size:11px; color:#6b7280; margin-top:6px;">${escapeStaffHtml(reviewText)}</div>
                        </td>
                        <td>${escapeStaffHtml(prop.broker_name || 'Unassigned')}</td>
                    </tr>
                `;
            });
            html += '</tbody></table>';
            tableWrap.innerHTML = html;
        }

        function handleAssignmentPropertySelection() {
            const propertySelect = document.getElementById('assignPropertySelect');
            const brokerSelect = document.getElementById('assignBrokerSelect');
            const currentInfo = document.getElementById('assignmentCurrentInfo');
            if (!propertySelect || !brokerSelect || !currentInfo) return;

            const selectedPropertyId = Number(propertySelect.value || 0);
            if (!selectedPropertyId) {
                currentInfo.textContent = 'Current assignment: -';
                brokerSelect.value = '0';
                return;
            }

            const selectedProperty = propertyAssignmentCache.find((item) => Number(item.id) === selectedPropertyId);
            const currentBrokerToken = String(selectedProperty?.broker_token || '0');
            brokerSelect.value = brokerAssignmentCache.some((b) => String(b.id) === currentBrokerToken)
                ? currentBrokerToken
                : '0';
            currentInfo.textContent = `Current assignment: ${selectedProperty?.broker_name || 'Unassigned'}`;
        }

        async function assignPropertyToBroker() {
            const propertySelect = document.getElementById('assignPropertySelect');
            const brokerSelect = document.getElementById('assignBrokerSelect');
            if (!propertySelect || !brokerSelect) return;

            const propertyId = Number(propertySelect.value || 0);
            const brokerRef = String(brokerSelect.value || '0');
            if (propertyId <= 0) {
                showAlert('Please select a property first.', 'error');
                return;
            }

            try {
                const response = await fetch('../api/staff/assign-property-broker.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ property_id: propertyId, broker_ref: brokerRef })
                });
                const data = await response.json();
                if (!data.success) {
                    showAlert(data.message || 'Could not assign property', 'error');
                    return;
                }

                showAlert(data.message || 'Assignment updated', 'success');
                await Promise.all([loadPropertyAssignments(), loadProperties()]);
            } catch (error) {
                showAlert('Error assigning property: ' + error.message, 'error');
            }
        }
        
        // Utilities
        function formatDate(dateString) {
            if (!dateString) return 'N/A';
            const date = new Date(dateString);
            return date.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
        }
        
        function showError(containerId, message) {
            document.getElementById(containerId).innerHTML = `
                <div class="empty-state">
                    <div class="empty-state-icon">âš ï¸</div>
                    <p>${message}</p>
                </div>
            `;
        }
        
        function showAlert(message, type) {
            const alert = document.createElement('div');
            alert.className = `alert alert-${type}`;
            alert.textContent = message;
            document.querySelector('.container').insertBefore(alert, document.querySelector('.container').firstChild);
            setTimeout(() => alert.remove(), 3000);
        }
        
        // Cleanup
        window.addEventListener('beforeunload', () => {
            Object.values(intervals).forEach(i => clearInterval(i));
        });
    </script>
</body>
</html>


