<?php
/**
 * Broker Dashboard - Real-Time Implementation
 * Lead management, property updates, site visits, document uploads
 * Real-time polling: stats, properties, leads, visits, documents
 */

require_once '../config.php';

$session_role = $_SESSION['role'] ?? ($_SESSION['user_role'] ?? '');
if (!isset($_SESSION['user_id']) || $session_role !== 'broker') {
    header('Location: ../broker-login.php');
    exit;
}

$broker_id = $_SESSION['user_id'];
$broker_name = $_SESSION['user_name'] ?? 'Broker';
$broker_email = $_SESSION['email'] ?? 'broker@Zemaraim.com';

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Broker 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: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); min-height: 100vh; }
        
        .broker-wrapper { display: flex; min-height: 100vh; }
        .sidebar { 
            width: 280px; 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            color: white; 
            padding: 30px 20px; 
            position: fixed; 
            height: 100vh; 
            overflow-y: auto; 
            box-shadow: 2px 0 15px rgba(0,0,0,0.1);
            z-index: 999;
            transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), visibility 0.3s ease;
            left: 0;
            top: 0;
        }
        .sidebar.mobile-open { 
            transform: translateX(0) !important; 
            visibility: visible;
        }
        .sidebar-overlay { 
            position: fixed; 
            top: 0; 
            left: 0; 
            width: 100%; 
            height: 100%; 
            background: rgba(0,0,0,0.5); 
            z-index: 998; 
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.3s ease;
        }
        .sidebar-overlay.active { 
            opacity: 1;
            pointer-events: auto; 
        }
        .sidebar-logo { font-size: 20px; font-weight: 700; margin-bottom: 40px; display: flex; align-items: center; gap: 10px; }
        .sidebar-menu { list-style: none; }
        .sidebar-menu li { margin-bottom: 10px; }
        .sidebar-menu a { 
            color: rgba(255,255,255,0.85); 
            text-decoration: none; 
            display: flex; 
            align-items: center; 
            gap: 12px; 
            padding: 12px 15px; 
            border-radius: 8px; 
            transition: all 0.3s ease;
        }
        .sidebar-menu a:hover { 
            background: rgba(255,255,255,0.2); 
            color: white;
            padding-left: 20px;
        }
        .main-content { margin-left: 280px; flex: 1; padding: 30px; overflow-y: auto; transition: margin-left 0.3s ease; }
        
        .mobile-menu-toggle { 
            display: none; 
            background: none; 
            border: none; 
            font-size: 24px; 
            cursor: pointer; 
            color: #333; 
            padding: 8px 12px; 
            margin-right: 15px;
        }
        .mobile-menu-toggle:hover { color: #667eea; }
        
        .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; background: white; padding: 20px 25px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); align-items: center; }
        .header-left { display: flex; align-items: center; flex: 1; }
        .header h1 { font-size: 28px; color: #333; margin: 0; font-weight: 700; }
        .header-subtitle { color: #999; font-size: 14px; margin-top: 5px; }
        
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 30px; }
        .stat-card { 
            background: white; 
            padding: 25px; 
            border-radius: 12px; 
            box-shadow: 0 2px 10px rgba(0,0,0,0.05); 
            border-left: 5px solid #667eea;
            transition: all 0.3s ease;
            position: relative;
        }
        .stat-card:hover { transform: translateY(-5px); box-shadow: 0 5px 20px rgba(0,0,0,0.1); }
        .stat-card h3 { font-size: 11px; color: #999; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 10px; font-weight: 600; }
        .stat-card .number { font-size: 36px; font-weight: 700; color: #667eea; }
        .stat-loading::after { content: '⟳'; display: inline-block; animation: spin 1s linear infinite; margin-left: 10px; }
        @keyframes spin { 100% { transform: rotate(360deg); } }
        
        .panel { background: white; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); padding: 25px; margin-bottom: 30px; }
        .panel h2 { font-size: 20px; margin-bottom: 25px; color: #333; font-weight: 700; border-bottom: 2px solid #f0f0f0; padding-bottom: 15px; }
        .panel.no-data { text-align: center; color: #999; padding: 50px 25px; }
        
        .btn { 
            padding: 10px 18px; 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
            color: white; 
            border: none; 
            border-radius: 8px; 
            cursor: pointer; 
            text-decoration: none; 
            display: inline-block;
            font-weight: 500;
            transition: all 0.3s ease;
            font-size: 14px;
        }
        .btn:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4); }
        .btn-sm { padding: 6px 12px; font-size: 12px; }
        .btn-danger { background: linear-gradient(135deg, #f93b1d 0%, #ea580c 100%); }
        .btn-success { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); }
        .btn-warning { background: linear-gradient(135deg, #f88c0f 0%, #f58709 100%); }
        .btn-secondary { background: linear-gradient(135deg, #9ca3af 0%, #6b7280 100%); }
        
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        table th { background: #f8f9fa; padding: 15px 12px; text-align: left; font-weight: 600; color: #333; border-bottom: 2px solid #e0e0e0; }
        table td { padding: 15px 12px; border-bottom: 1px solid #f0f0f0; }
        table tr:hover { background: #f8f9fa; }
        
        .status-badge { 
            padding: 6px 14px; 
            border-radius: 20px; 
            font-size: 12px; 
            font-weight: 600;
            display: inline-block;
        }
        .status-active { background: #d4edda; color: #155724; }
        .status-pending { background: #fff3cd; color: #856404; }
        .status-approved { background: #d1ecf1; color: #0c5460; }
        .status-rejected { background: #f8d7da; color: #721c24; }
        .status-responded { background: #cce5ff; color: #004085; }
        .status-declined { background: #f8d7da; color: #721c24; }
        .status-completed { background: #d4edda; color: #155724; }
        .status-finished { background: #d4edda; color: #155724; }
        .status-done { background: #d4edda; color: #155724; }
        .status-assigned { background: #dbeafe; color: #1e40af; }
        .status-working { background: #fef3c7; color: #92400e; }
        .status-finished_pending_admin { background: #fed7aa; color: #9a3412; }
        .status-finished_approved { background: #dcfce7; color: #166534; }
        
        .action-group { display: flex; gap: 8px; flex-wrap: wrap; }
        .leads-analytics-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
            gap: 12px;
            margin-bottom: 14px;
        }
        .leads-analytics-card {
            border: 1px solid #e5e7eb;
            border-radius: 10px;
            padding: 12px;
            background: #f8fafc;
        }
        .leads-analytics-card h4 {
            margin: 0 0 8px 0;
            font-size: 11px;
            color: #6b7280;
            text-transform: uppercase;
            letter-spacing: 0.02em;
        }
        .leads-analytics-value {
            margin: 0;
            font-size: 24px;
            font-weight: 700;
            color: #1f2937;
        }
        .leads-chart-grid {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 12px;
            margin-bottom: 14px;
        }
        .leads-chart-card {
            border: 1px solid #e5e7eb;
            border-radius: 10px;
            background: #fff;
            padding: 10px;
            min-width: 0;
        }
        .leads-chart-title {
            margin: 0 0 8px 0;
            font-size: 13px;
            color: #374151;
            font-weight: 700;
        }
        .lead-chart-canvas {
            width: 100%;
            height: 220px;
            display: block;
            background: #fff;
            border-radius: 8px;
        }
        
        .logout-btn { background: linear-gradient(135deg, #f74c89 0%, #f93b1d 100%); color: white; border: none; padding: 10px 18px; border-radius: 8px; cursor: pointer; font-weight: 500; transition: all 0.3s ease; }
        .logout-btn:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(247, 76, 137, 0.4); }
        
        .user-info { display: flex; align-items: center; gap: 15px; }
        .user-info .avatar { width: 40px; height: 40px; border-radius: 50%; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; display: flex; align-items: center; justify-content: center; font-weight: 700; }
        
        .notification { 
            position: fixed; 
            top: 20px; 
            right: 20px; 
            padding: 15px 20px; 
            border-radius: 8px; 
            color: white; 
            z-index: 2000; 
            animation: slideIn 0.3s ease;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        .notification.success { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); }
        .notification.error { background: linear-gradient(135deg, #f93b1d 0%, #ea580c 100%); }
        .notification.info { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
        @keyframes slideIn { from { transform: translateX(400px); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
        
        .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 3000; align-items: center; justify-content: center; }
        .modal.active { display: flex; }
        .modal-content { background: white; padding: 30px; border-radius: 12px; max-width: 500px; width: 90%; max-height: 90vh; overflow-y: auto; }
        .modal-header { font-size: 20px; font-weight: 700; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; }
        .modal-close { background: none; border: none; font-size: 24px; cursor: pointer; color: #999; }
        .property-thumb {
            width: 72px;
            height: 54px;
            object-fit: cover;
            border-radius: 8px;
            border: 1px solid #e2e8f0;
            background: #f1f5f9;
            display: block;
            margin-bottom: 8px;
        }
        .property-thumb-fallback {
            width: 72px;
            height: 54px;
            border-radius: 8px;
            border: 1px solid #e2e8f0;
            background: linear-gradient(135deg, #c7d2fe 0%, #e2e8f0 100%);
            color: #475569;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            margin-bottom: 8px;
        }
        .property-detail-image {
            width: 100%;
            max-height: 240px;
            object-fit: cover;
            border-radius: 10px;
            border: 1px solid #e5e7eb;
            margin-bottom: 14px;
        }
        .property-detail-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 10px 14px;
        }
        .property-detail-item {
            font-size: 13px;
            color: #334155;
        }
        .property-detail-item strong {
            color: #111827;
            margin-right: 6px;
        }
        
        .loading { text-align: center; padding: 40px; color: #999; }
        .loading::after { content: ''; display: block; width: 40px; height: 40px; margin: 20px auto; border: 4px solid #f0f0f0; border-top: 4px solid #667eea; border-radius: 50%; animation: spin 1s linear infinite; }
        
        .empty-state { text-align: center; padding: 60px 20px; color: #999; }
        .empty-state i { font-size: 48px; margin-bottom: 20px; opacity: 0.5; }
        
        .tabs { display: flex; gap: 10px; border-bottom: 2px solid #f0f0f0; margin-bottom: 20px; }
        .tab { padding: 12px 20px; cursor: pointer; border: none; background: none; color: #999; font-weight: 500; border-bottom: 3px solid transparent; transition: all 0.3s ease; }
        .tab.active { color: #667eea; border-bottom-color: #667eea; }

        .documents-layout {
            display: grid;
            grid-template-columns: minmax(280px, 380px) minmax(0, 1fr);
            gap: 20px;
            align-items: start;
            width: 100%;
            min-width: 0;
        }
        .documents-left-column {
            display: grid;
            grid-template-columns: 1fr;
            gap: 14px;
            min-width: 0;
        }
        .document-upload-card {
            border: 1px solid #e9ecef;
            border-radius: 12px;
            padding: 16px;
            background: #f8fafc;
            min-width: 0;
            overflow: hidden;
        }
        .document-upload-card h3 {
            margin: 0 0 14px 0;
            font-size: 16px;
            color: #333;
        }
        .document-form-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 12px;
        }
        .document-form-group {
            display: flex;
            flex-direction: column;
            gap: 6px;
            min-width: 0;
        }
        .document-form-group.full {
            grid-column: 1 / -1;
        }
        .document-form-group label {
            font-weight: 600;
            color: #374151;
            font-size: 13px;
        }
        .document-form-group input,
        .document-form-group select {
            border: 1px solid #d1d5db;
            border-radius: 8px;
            padding: 10px 12px;
            font-size: 14px;
            background: #fff;
            width: 100%;
            max-width: 100%;
            min-width: 0;
        }
        .document-form-group input[type="file"] {
            padding: 8px 10px;
            font-size: 13px;
            line-height: 1.3;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .document-form-group button,
        .document-form-group .btn {
            width: 100%;
        }
        .document-form-hint {
            font-size: 12px;
            color: #6b7280;
            word-break: break-word;
        }
        .table-wrap {
            overflow-x: auto;
            width: 100%;
            -webkit-overflow-scrolling: touch;
        }
        /* .documents-mobile-list {
            display: none;
            gap: 10px;
            margin-top: 10px;
        }
        .documents-mobile-card {
            border: 1px solid #e5e7eb;
            border-radius: 10px;
            padding: 10px;
            background: #fff;
        }
        .documents-mobile-title {
            font-weight: 700;
            color: #1f2937;
            margin-bottom: 8px;
            font-size: 14px;
            word-break: break-word;
        }
        .documents-mobile-meta {
            font-size: 12px;
            color: #4b5563;
            margin-bottom: 4px;
            word-break: break-word;
        } */
        .table-wrap table {
            min-width: 760px;
        }
        .doc-notes {
            max-width: 260px;
            font-size: 12px;
            color: #4b5563;
            line-height: 1.4;
        }
        .doc-meta {
            font-size: 12px;
            color: #6b7280;
            margin-top: 6px;
        }
        .section-subtitle {
            font-size: 12px;
            color: #6b7280;
            margin-top: -4px;
            margin-bottom: 10px;
            line-height: 1.4;
        }

        @media (max-width: 1200px) {
            .main-content { padding: 20px; }
            .stats-grid { grid-template-columns: repeat(2, 1fr); }
            .documents-layout { grid-template-columns: 1fr; }
            .table-wrap table { min-width: 700px; }
        }

        @media (max-width: 992px) {
            .stats-grid { grid-template-columns: repeat(2, 1fr); }
            .doc-notes { max-width: 200px; }
        }

        @media (max-width: 768px) {
            .mobile-menu-toggle { display: block !important; }
            .sidebar { 
                width: 280px; 
                transform: translateX(-100%);
                visibility: hidden;
                position: fixed;
                left: 0;
                top: 0;
                height: 100vh;
                padding-top: 20px;
                z-index: 999;
            }
            .sidebar.mobile-open { 
                transform: translateX(0);
                visibility: visible;
            }
            .sidebar-overlay { 
                opacity: 0;
                pointer-events: none;
            }
            .sidebar-overlay.active { 
                opacity: 1;
                pointer-events: auto;
            }
            .sidebar-logo { font-size: 18px; margin-bottom: 30px; }
            .sidebar-logo span { display: inline; }
            .sidebar-menu a span { display: inline; }
            .main-content { 
                margin-left: 0; 
                padding: 15px; 
            }
            .header { 
                flex-direction: column; 
                gap: 15px; 
                align-items: flex-start;
            }
            .header-left { flex: 1; width: 100%; }
            .header h1 { font-size: 22px; }
            .user-info { width: 100%; justify-content: space-between; }
            .stats-grid { grid-template-columns: 1fr; }
            .stat-card h3 { font-size: 10px; }
            .stat-card .number { font-size: 28px; }
            .action-group { flex-direction: column; }
            .action-group .btn { width: 100%; }
            .documents-layout { grid-template-columns: 1fr; }
            .document-form-grid { grid-template-columns: 1fr; }
            .documents-left-column { gap: 12px; }
            .document-upload-card { padding: 12px; border-radius: 10px; }
            .document-upload-card h3 { font-size: 15px; margin-bottom: 10px; }
            .document-form-group input,
            .document-form-group select { font-size: 13px; padding: 9px 10px; }
            .document-form-group input[type="file"] { font-size: 12px; }
            .table-wrap table { min-width: 640px; }
            .leads-chart-grid { grid-template-columns: 1fr; }
            .lead-chart-canvas { height: 200px; }
            table th, table td { padding: 10px 8px; font-size: 12px; }
            .btn-sm { padding: 4px 8px; font-size: 11px; }
            .panel { padding: 15px; }
            .panel h2 { font-size: 16px; }
            .logout-btn { padding: 8px 14px; font-size: 12px; }
        }

        @media (max-width: 480px) {
            .header { padding: 12px 12px; }
            .header h1 { font-size: 18px; }
            .header-subtitle { font-size: 12px; }
            .main-content { padding: 10px; }
            .stats-grid { gap: 12px; }
            .stat-card { padding: 15px; }
            .stat-card h3 { font-size: 9px; }
            .stat-card .number { font-size: 24px; }
            .sidebar { width: 260px; padding: 15px 10px; }
            .sidebar-logo { font-size: 14px; margin-bottom: 20px; }
            .sidebar-menu a { padding: 10px 12px; gap: 8px; }
            .sidebar-menu li { margin-bottom: 8px; }
            .panel { padding: 12px; margin-bottom: 15px; }
            .panel h2 { font-size: 14px; margin-bottom: 12px; }
            .btn { padding: 8px 12px; font-size: 12px; }
            .user-info { gap: 8px; }
            .user-info .avatar { width: 32px; height: 32px; font-size: 12px; }
            .tab { padding: 10px 15px; font-size: 13px; }
            .document-upload-card { padding: 10px; }
            .document-upload-card h3 { font-size: 14px; }
            .document-form-hint { font-size: 11px; }
            .table-wrap table { min-width: 560px; }
            .leads-analytics-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
            .lead-chart-canvas { height: 190px; }
            /* .documents-table-desktop { display: none; }
            .documents-mobile-list { display: grid; } */
            table { font-size: 12px; }
            table th, table td { padding: 8px 6px; }
            .btn-sm { padding: 4px 6px; font-size: 10px; }
            .property-detail-grid { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>

    <!-- Sidebar -->
    <div class="sidebar">
        <div class="sidebar-logo">
            <i class="fas fa-briefcase"></i>
            <span>Broker Central</span>
        </div>
        <ul class="sidebar-menu">
            <li><a href="#overview" class="tab-link" data-tab="overview"><i class="fas fa-chart-pie"></i> <span>Dashboard</span></a></li>
            <li><a href="#properties" class="tab-link" data-tab="properties"><i class="fas fa-home"></i> <span>Properties</span></a></li>
            <li><a href="#leads" class="tab-link" data-tab="leads"><i class="fas fa-chart-line"></i> <span>Leads</span></a></li>
            <li><a href="#visits" class="tab-link" data-tab="visits"><i class="fas fa-calendar"></i> <span>Site Visits</span></a></li>
            <li><a href="#documents" class="tab-link" data-tab="documents"><i class="fas fa-files"></i> <span>Documents</span></a></li>
            <li style="margin-top: 30px; border-top: 1px solid rgba(255,255,255,0.2); padding-top: 20px;">
                <a href="../logout.php"><i class="fas fa-sign-out-alt"></i> <span>Logout</span></a>
            </li>
        </ul>
    </div>

    <!-- Sidebar Overlay -->
    <div class="sidebar-overlay" id="sidebarOverlay"></div>

    <!-- Main Content -->
    <div class="main-content">
        <div class="header">
            <div class="header-left">
                <button class="mobile-menu-toggle" id="mobileMenuToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <div>
                    <h1>🏢 Broker Dashboard</h1>
                    <p class="header-subtitle">Real-Time Lead & Property Management</p>
                </div>
            </div>
            <div class="user-info">
                <div>
                    <div style="font-weight: 600; color: #333;"><?php echo htmlspecialchars($broker_name); ?></div>
                    <div style="font-size: 12px; color: #999;"><?php echo htmlspecialchars($broker_email); ?></div>
                </div>
                <div class="avatar"><?php echo strtoupper(substr($broker_name, 0, 1)); ?></div>
                <a href="../logout.php" class="logout-btn">Logout</a>
            </div>
        </div>

        <!-- Statistics -->
        <div class="stats-grid" id="overviewStats">
            <div class="stat-card stat-loading" id="stat-properties">
                <h3>🏠 Assigned Properties</h3>
                <div class="number">-</div>
            </div>
            <div class="stat-card stat-loading" id="stat-leads">
                <h3>👥 Active Leads</h3>
                <div class="number">-</div>
            </div>
            <div class="stat-card stat-loading" id="stat-visits">
                <h3>📅 Site Visits</h3>
                <div class="number">-</div>
            </div>
            <div class="stat-card stat-loading" id="stat-documents">
                <h3>Submitted Documents</h3>
                <div class="number">-</div>
            </div>
        </div>

        <!-- TAB CONTENT: Overview -->
        <div id="overview" class="tab-content">
            <div class="panel">
                <h2>📊 Dashboard Overview</h2>
                <p style="color: #999; margin-bottom: 20px;">Welcome to your broker dashboard! Real-time data updates every 5 seconds.</p>
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px;">
                    <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 10px;">
                        <div style="font-size: 12px; opacity: 0.9; margin-bottom: 10px;">📍 QUICK ACTION</div>
                        <div style="font-size: 18px; font-weight: 600; margin-bottom: 15px;">Manage Your Properties</div>
                        <button class="btn" onclick="switchTab('properties')" style="background: rgba(255,255,255,0.2); border: 1px solid white;">View Properties</button>
                    </div>
                    <div style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white; padding: 20px; border-radius: 10px;">
                        <div style="font-size: 12px; opacity: 0.9; margin-bottom: 10px;">👥 QUICK ACTION</div>
                        <div style="font-size: 18px; font-weight: 600; margin-bottom: 15px;">Respond to Leads</div>
                        <button class="btn" onclick="switchTab('leads')" style="background: rgba(255,255,255,0.2); border: 1px solid white;">View Leads</button>
                    </div>
                    <div style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white; padding: 20px; border-radius: 10px;">
                        <div style="font-size: 12px; opacity: 0.9; margin-bottom: 10px;">📅 QUICK ACTION</div>
                        <div style="font-size: 18px; font-weight: 600; margin-bottom: 15px;">Schedule Site Visits</div>
                        <button class="btn" onclick="switchTab('visits')" style="background: rgba(255,255,255,0.2); border: 1px solid white;">View Visits</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- TAB CONTENT: Properties -->
        <div id="properties" class="tab-content" style="display: none;">
            <div class="panel">
                <h2>🏠 My Assigned Properties</h2>
                <div id="properties-content" class="loading"></div>
            </div>
        </div>

        <!-- TAB CONTENT: Leads -->
        <div id="leads" class="tab-content" style="display: none;">
            <div class="panel">
                <h2>👥 Lead Management</h2>
                <div id="leads-content" class="loading"></div>
            </div>
        </div>

        <!-- TAB CONTENT: Site Visits -->
        <div id="visits" class="tab-content" style="display: none;">
            <div class="panel">
                <h2>📅 Scheduled Site Visits</h2>
                <div id="visits-content" class="loading"></div>
            </div>
        </div>

        <!-- TAB CONTENT: Documents -->
        <div id="documents" class="tab-content" style="display: none;">
            <div class="panel">
                <h2>📄 Documents</h2>
                <div id="documents-content" class="loading"></div>
            </div>
        </div>

    </div>

    <!-- Modals -->
    <div id="respond-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                Respond to Lead
                <button class="modal-close" onclick="closeModal('respond-modal')">×</button>
            </div>
            <form id="respond-form">
                <input type="hidden" id="respond-inquiry-id">
                <div style="margin-bottom: 20px;">
                    <label style="font-weight: 600; margin-bottom: 10px; display: block;">Your Response</label>
                    <textarea id="respond-message" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px; font-family: inherit; min-height: 120px; resize: vertical;"></textarea>
                </div>
                <div style="display: flex; gap: 10px;">
                    <button type="button" class="btn btn-secondary" onclick="closeModal('respond-modal')">Cancel</button>
                    <button type="submit" class="btn">Send Response</button>
                </div>
            </form>
        </div>
    </div>
    <div id="property-view-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                Property Details
                <button class="modal-close" onclick="closeModal('property-view-modal')">&times;</button>
            </div>
            <div id="property-view-body">
                <div class="loading">Loading property details...</div>
            </div>
        </div>
    </div>

    </div>

    <script src="../assets/js/vendor/jquery-3.6.0.min.js"></script>
    <script>
        // Real-Time Broker Dashboard - Complete Implementation
        console.log('🏢 Real-Time Broker Dashboard Started');

        // Mobile Menu Toggle Functions
        function toggleSidebar() {
            const sidebar = document.querySelector('.sidebar');
            const overlay = document.getElementById('sidebarOverlay');
            
            if (!sidebar || !overlay) {
                console.error('Sidebar or overlay element not found');
                return;
            }
            
            const isOpen = sidebar.classList.contains('mobile-open');
            console.log('Current state - Sidebar open:', isOpen);
            
            if (isOpen) {
                closeSidebar();
            } else {
                sidebar.classList.add('mobile-open');
                overlay.classList.add('active');
                console.log('✓ Sidebar opened');
            }
        }

        function closeSidebar() {
            const sidebar = document.querySelector('.sidebar');
            const overlay = document.getElementById('sidebarOverlay');
            
            if (sidebar) sidebar.classList.remove('mobile-open');
            if (overlay) overlay.classList.remove('active');
            console.log('✓ Sidebar closed');
        }

        // Initialize mobile menu on DOM ready
        document.addEventListener('DOMContentLoaded', function() {
            console.log('✓ DOM loaded - Initializing mobile menu');
            
            // Setup toggle button click handler
            const toggleBtn = document.getElementById('mobileMenuToggle');
            if (toggleBtn) {
                console.log('✓ Toggle button found, setting up click handler');
                toggleBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    console.log('☰ Toggle button clicked');
                    toggleSidebar();
                });
            } else {
                console.warn('✗ Toggle button NOT found');
            }

            // Setup overlay click handler - closes sidebar
            const overlay = document.getElementById('sidebarOverlay');
            if (overlay) {
                overlay.addEventListener('click', function(e) {
                    e.stopPropagation();
                    console.log('✓ Overlay clicked - closing sidebar');
                    closeSidebar();
                });
            }

            // Close sidebar when clicking menu links
            const sidebarLinks = document.querySelectorAll('.sidebar-menu a');
            sidebarLinks.forEach(link => {
                link.addEventListener('click', function(e) {
                    // Don't prevent default on logout links
                    if (window.innerWidth <= 768 && !this.href.includes('logout')) {
                        console.log('✓ Menu link clicked - closing sidebar');
                        closeSidebar();
                    }
                });
            });
        });

        // Handle window resize - close sidebar on desktop
        window.addEventListener('resize', function() {
            if (window.innerWidth > 768) {
                const sidebar = document.querySelector('.sidebar');
                if (sidebar && sidebar.classList.contains('mobile-open')) {
                    console.log('✓ Screen resized to desktop - closing sidebar');
                    closeSidebar();
                }
            }
            if (activeTab === 'leads' && document.getElementById('leads-content')) {
                renderLeads(leadRecordsState, leadAnalyticsState);
            }
        });

        const API_BASE = '../api/broker/';
        let pollInterval = null;
        let lastUpdate = {};
        let activeTab = 'overview';
        let brokerPropertiesCache = [];
        let isUploadingDocument = false;
        let lastDocumentsSignature = '';
        let lastPropertyRequestsSignature = '';
        let documentsFormState = {
            dirty: false,
            document_name: '',
            document_type: '',
            property_id: ''
        };
        let listingRequestFormState = {
            dirty: false,
            request_mode: 'new',
            property_id: '',
            title: '',
            type: 'house',
            price: '',
            address: '',
            city: '',
            state: '',
            bedrooms: '0',
            bathrooms: '0',
            image_url: '',
            description: ''
        };
        let leadRecordsState = [];
        let leadAnalyticsState = null;
        let isUploadingListingImage = false;
        const POLL_INTERVAL = 5000; // 5 seconds

        // ===============================================
        // INITIALIZATION
        // ===============================================
        document.addEventListener('DOMContentLoaded', function() {
            console.log('Dashboard DOM loaded - initializing real-time features');
            
            // Set up tab navigation
            document.querySelectorAll('.tab-link').forEach(link => {
                link.addEventListener('click', function(e) {
                    e.preventDefault();
                    const tabName = this.dataset.tab;
                    switchTab(tabName);
                });
            });

            // Set up event listeners
            document.getElementById('respond-form').addEventListener('submit', submitLeadResponse);
            bindDocumentFormEvents();

            // Enforce initial state: show only dashboard section
            switchTab('overview');

            // Initial data load
            updateAllData();

            // Start polling for real-time updates
            startPolling();

            console.log('✅ Dashboard initialized');
        });

        // ===============================================
        // REAL-TIME POLLING SYSTEM
        // ===============================================
        function startPolling() {
            console.log('Starting real-time polling...');
            
            // Poll immediately, then every 5 seconds
            updateAllData();
            
            pollInterval = setInterval(() => {
                updateAllData();
            }, POLL_INTERVAL);
        }

        function stopPolling() {
            if (pollInterval) {
                clearInterval(pollInterval);
                pollInterval = null;
            }
        }

        async function updateAllData() {
            try {
                await Promise.all([
                    updateStats(),
                    updatePropertiesIfNeeded(),
                    updateLeadsIfNeeded(),
                    updateVisitsIfNeeded(),
                    updateDocumentsIfNeeded()
                ]);
            } catch (error) {
                console.error('Error updating data:', error);
            }
        }

        // ===============================================
        // FETCH STATS
        // ===============================================
        async function updateStats() {
            try {
                const response = await fetch(API_BASE + 'get-stats.php');
                const data = await response.json();

                if (data.success) {
                    // Update stat cards with null checks
                    const statProperties = document.querySelector('#stat-properties .number');
                    const statLeads = document.querySelector('#stat-leads .number');
                    const statVisits = document.querySelector('#stat-visits .number');
                    const statDocuments = document.querySelector('#stat-documents .number');

                    if (statProperties) statProperties.textContent = data.stats.assigned_properties || 0;
                    if (statLeads) statLeads.textContent = data.stats.active_leads || 0;
                    if (statVisits) statVisits.textContent = data.stats.scheduled_visits || 0;
                    if (statDocuments) statDocuments.textContent = data.stats.total_documents || 0;

                    // Remove loading animation
                    document.querySelectorAll('.stat-loading').forEach(card => {
                        card.classList.remove('stat-loading');
                    });

                    lastUpdate.stats = new Date().getTime();
                }
            } catch (error) {
                console.error('Error updating stats:', error);
            }
        }

        // ===============================================
        // FETCH PROPERTIES
        // ===============================================
        async function updatePropertiesIfNeeded() {
            if (activeTab !== 'properties') return; // Only update if tab is visible

            try {
                const response = await fetch(API_BASE + 'get-properties.php');
                const data = await response.json();

                if (data.success) {
                    renderProperties(data.properties);
                    lastUpdate.properties = new Date().getTime();
                } else {
                    renderTabError('properties-content', data.message || 'Failed to load properties');
                }
            } catch (error) {
                console.error('Error updating properties:', error);
                renderTabError('properties-content', 'Could not load properties right now.');
            }
        }

        function getAssignmentStatusLabel(status) {
            const normalized = String(status || 'assigned').toLowerCase();
            const labels = {
                unassigned: 'Unassigned',
                assigned: 'Assigned',
                working: 'Working',
                finished_pending_admin: 'Finished - Pending Admin',
                finished_approved: 'Finished - Approved',
                pending: 'Pending',
                approved: 'Approved',
                rejected: 'Rejected'
            };
            return labels[normalized] || normalized.replace(/_/g, ' ');
        }

        function renderAssignmentActionButton(property) {
            const status = String(property.assignment_status || 'assigned').toLowerCase();
            if (status === 'assigned') {
                return `<button class="btn btn-sm btn-success" onclick="updateAssignmentWorkflow(${Number(property.id)}, 'confirm')">Confirm Work</button>`;
            }
            if (status === 'working') {
                return `<button class="btn btn-sm btn-warning" onclick="updateAssignmentWorkflow(${Number(property.id)}, 'finish')">Mark Finished</button>`;
            }
            return '';
        }

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

        function renderProperties(properties) {
            const container = document.getElementById('properties-content');
            if (!container) return;
            container.classList.remove('loading');

            if (!properties || properties.length === 0) {
                container.innerHTML = '<div class="empty-state"><i class="fas fa-inbox"></i><p>No properties assigned yet</p></div>';
                return;
            }

            let html = `
                <div class="table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th>Property</th>
                            <th>Location</th>
                            <th>Price</th>
                            <th>Status</th>
                            <th>Work Progress</th>
                            <th>Inquiries</th>
                            <th>Listed</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
            `;

            properties.forEach(prop => {
                const inquiries = prop.inquiry_count || 0;
                const statusClass = 'status-' + (prop.status || 'active');
                const assignmentStatus = String(prop.assignment_status || 'assigned').toLowerCase();
                const assignmentReview = String(prop.assignment_review_status || 'pending').toLowerCase();
                const imageUrl = normalizeImagePath(prop.image_url || '');
                const createdDate = new Date(prop.created_at).toLocaleDateString('en-US', { 
                    year: 'numeric', 
                    month: 'short', 
                    day: 'numeric' 
                });
                const imageHtml = imageUrl
                    ? `<img src="${escapeHtml(imageUrl)}" alt="Property image" class="property-thumb" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';"><div class="property-thumb-fallback" style="display:none;"><i class='fas fa-home'></i></div>`
                    : `<div class="property-thumb-fallback"><i class='fas fa-home'></i></div>`;

                html += `
                    <tr>
                        <td>${imageHtml}<strong>${escapeHtml(prop.title)}</strong></td>
                        <td>${escapeHtml(prop.city || 'N/A')}</td>
                        <td>$${(prop.price || 0).toLocaleString()}</td>
                        <td><span class="status-badge ${statusClass}">${ucfirst(prop.status || 'active')}</span></td>
                        <td>
                            <span class="status-badge status-${assignmentStatus}">${escapeHtml(getAssignmentStatusLabel(assignmentStatus))}</span>
                            <div style="font-size:11px;color:#6b7280;margin-top:6px;">Admin Review: ${escapeHtml(getAssignmentStatusLabel(assignmentReview))}</div>
                        </td>
                        <td><span style="background: #cce5ff; color: #004085; padding: 4px 10px; border-radius: 15px; font-size: 12px; font-weight: 600;">${inquiries}</span></td>
                        <td>${createdDate}</td>
                        <td>
                            <div class="action-group">
                                <button class="btn btn-sm" onclick="viewPropertyDetails(${prop.id}, '${escapeHtml(prop.title)}')">View</button>
                                <button class="btn btn-sm btn-secondary" onclick="editProperty(${prop.id})">Request Update</button>
                                ${renderAssignmentActionButton(prop)}
                            </div>
                        </td>
                    </tr>
                `;
            });

            html += '</tbody></table></div>';
            container.innerHTML = html;
        }

        // ===============================================
        // FETCH LEADS
        // ===============================================
        async function updateLeadsIfNeeded() {
            if (activeTab !== 'leads') return;

            try {
                const [leadsResponse, analyticsResponse] = await Promise.all([
                    fetch(API_BASE + 'get-leads.php'),
                    fetch(API_BASE + 'get-lead-analytics.php')
                ]);
                const leadsData = await leadsResponse.json();
                const analyticsData = await analyticsResponse.json();

                if (leadsData.success) {
                    leadRecordsState = Array.isArray(leadsData.leads) ? leadsData.leads : [];
                    leadAnalyticsState = analyticsData.success ? (analyticsData.analytics || null) : null;
                    renderLeads(leadRecordsState, leadAnalyticsState);
                    lastUpdate.leads = new Date().getTime();
                } else {
                    renderTabError('leads-content', leadsData.message || 'Failed to load leads');
                }
            } catch (error) {
                console.error('Error updating leads:', error);
                renderTabError('leads-content', 'Could not load leads right now.');
            }
        }

        function drawLeadsLineChart(canvasId, labels, totalData, handledData) {
            const canvas = document.getElementById(canvasId);
            if (!canvas) return;

            const width = canvas.clientWidth || 700;
            const height = canvas.clientHeight || 220;
            canvas.width = width;
            canvas.height = height;

            const ctx = canvas.getContext('2d');
            if (!ctx) return;
            ctx.clearRect(0, 0, width, height);

            const maxValue = Math.max(1, ...(totalData || []), ...(handledData || []));
            const padding = { top: 16, right: 14, bottom: 34, left: 30 };
            const chartWidth = width - padding.left - padding.right;
            const chartHeight = height - padding.top - padding.bottom;
            const count = Math.max(2, (labels || []).length);
            const xStep = count > 1 ? chartWidth / (count - 1) : chartWidth;

            ctx.strokeStyle = '#eceff3';
            ctx.lineWidth = 1;
            for (let i = 0; i <= 4; i++) {
                const y = padding.top + (chartHeight * i / 4);
                ctx.beginPath();
                ctx.moveTo(padding.left, y);
                ctx.lineTo(padding.left + chartWidth, y);
                ctx.stroke();
            }

            function drawSeries(series, color) {
                ctx.strokeStyle = color;
                ctx.lineWidth = 2;
                ctx.beginPath();
                (series || []).forEach((value, index) => {
                    const x = padding.left + xStep * index;
                    const y = padding.top + chartHeight - ((Number(value || 0) / maxValue) * chartHeight);
                    if (index === 0) ctx.moveTo(x, y);
                    else ctx.lineTo(x, y);
                });
                ctx.stroke();

                ctx.fillStyle = color;
                (series || []).forEach((value, index) => {
                    const x = padding.left + xStep * index;
                    const y = padding.top + chartHeight - ((Number(value || 0) / maxValue) * chartHeight);
                    ctx.beginPath();
                    ctx.arc(x, y, 2.5, 0, Math.PI * 2);
                    ctx.fill();
                });
            }

            drawSeries(totalData, '#667eea');
            drawSeries(handledData, '#10b981');

            ctx.fillStyle = '#6b7280';
            ctx.font = '10px Segoe UI';
            ctx.textAlign = 'center';
            (labels || []).forEach((label, index) => {
                const x = padding.left + xStep * index;
                const text = String(label || '').split(' ')[0];
                ctx.fillText(text, x, height - 12);
            });
        }

        function drawLeadsStatusBarChart(canvasId, labels, values) {
            const canvas = document.getElementById(canvasId);
            if (!canvas) return;

            const width = canvas.clientWidth || 340;
            const height = canvas.clientHeight || 220;
            canvas.width = width;
            canvas.height = height;

            const ctx = canvas.getContext('2d');
            if (!ctx) return;
            ctx.clearRect(0, 0, width, height);

            const count = Math.max(1, (labels || []).length);
            const maxValue = Math.max(1, ...(values || []), 1);
            const padding = { top: 16, right: 12, bottom: 40, left: 26 };
            const chartWidth = width - padding.left - padding.right;
            const chartHeight = height - padding.top - padding.bottom;
            const gap = 8;
            const barWidth = Math.max(10, (chartWidth - gap * (count - 1)) / count);
            const colors = ['#f59e0b', '#3b82f6', '#10b981', '#ef4444'];

            for (let i = 0; i < count; i++) {
                const val = Number(values[i] || 0);
                const x = padding.left + i * (barWidth + gap);
                const h = (val / maxValue) * chartHeight;
                const y = padding.top + chartHeight - h;

                ctx.fillStyle = colors[i % colors.length];
                ctx.fillRect(x, y, barWidth, h);

                ctx.fillStyle = '#4b5563';
                ctx.font = '10px Segoe UI';
                ctx.textAlign = 'center';
                ctx.fillText(String(val), x + barWidth / 2, y - 4);
                const label = String(labels[i] || '');
                ctx.fillText(label.length > 8 ? label.slice(0, 8) + '.' : label, x + barWidth / 2, height - 12);
            }
        }

        function renderLeads(leads, analytics = null) {
            const container = document.getElementById('leads-content');
            if (!container) return;
            container.classList.remove('loading');

            const safeAnalytics = analytics && typeof analytics === 'object'
                ? analytics
                : { summary: {}, trend: { labels: [], total: [], handled: [] }, prediction: {} };
            const summary = safeAnalytics.summary || {};
            const trend = safeAnalytics.trend || { labels: [], total: [], handled: [] };
            const prediction = safeAnalytics.prediction || {};
            const nextMonthHandled = Number(prediction.next_month_handled || 0);

            let html = `
                <div class="leads-analytics-grid">
                    <div class="leads-analytics-card">
                        <h4>Total Leads</h4>
                        <p class="leads-analytics-value">${Number(summary.total || 0).toLocaleString()}</p>
                    </div>
                    <div class="leads-analytics-card">
                        <h4>Assigned Properties</h4>
                        <p class="leads-analytics-value">${Number(summary.assigned_properties_total || 0).toLocaleString()}</p>
                    </div>
                    <div class="leads-analytics-card">
                        <h4>Approved Leads</h4>
                        <p class="leads-analytics-value">${Number(summary.approved || 0).toLocaleString()}</p>
                    </div>
                    <div class="leads-analytics-card">
                        <h4>Finished Leads</h4>
                        <p class="leads-analytics-value">${Number(summary.finished || 0).toLocaleString()}</p>
                    </div>
                    <div class="leads-analytics-card">
                        <h4>Handled Leads</h4>
                        <p class="leads-analytics-value">${Number(summary.handled || 0).toLocaleString()}</p>
                    </div>
                    <div class="leads-analytics-card">
                        <h4>Conversion Rate</h4>
                        <p class="leads-analytics-value">${Number(summary.conversion_rate || 0).toFixed(1)}%</p>
                    </div>
                    <div class="leads-analytics-card">
                        <h4>Predicted Next Month</h4>
                        <p class="leads-analytics-value">${nextMonthHandled.toLocaleString()}</p>
                    </div>
                </div>
                <div class="leads-chart-grid">
                    <div class="leads-chart-card">
                        <div class="leads-chart-title">Lead Trend: Total vs Handled (6 Months)</div>
                        <canvas id="leadsTrendCanvas" class="lead-chart-canvas"></canvas>
                    </div>
                    <div class="leads-chart-card">
                        <div class="leads-chart-title">Lead Status Distribution</div>
                        <canvas id="leadsStatusCanvas" class="lead-chart-canvas"></canvas>
                    </div>
                </div>
            `;

            if (!leads || leads.length === 0) {
                html += '<div class="empty-state"><i class="fas fa-user-slash"></i><p>No active leads at the moment</p></div>';
                container.innerHTML = html;
            } else {
                html += `
                    <div class="table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>Customer</th>
                                <th>Property</th>
                                <th>Message</th>
                                <th>Status</th>
                                <th>Date</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                `;

                leads.forEach(lead => {
                    const statusClass = 'status-' + (lead.status || 'pending');
                    const createdDate = new Date(lead.created_at).toLocaleDateString('en-US', { 
                        year: 'numeric', 
                        month: 'short', 
                        day: 'numeric' 
                    });

                    html += `
                        <tr>
                            <td>
                                <strong>${escapeHtml(lead.customer_name || 'Unknown')}</strong><br>
                                <small style="color: #999;">${escapeHtml(lead.email || 'N/A')}</small>
                            </td>
                            <td>${escapeHtml(lead.property_title || 'N/A')}</td>
                            <td><small>${escapeHtml((lead.message || 'N/A').substring(0, 50))}...</small></td>
                            <td><span class="status-badge ${statusClass}">${ucfirst(lead.status)}</span></td>
                            <td>${createdDate}</td>
                            <td>
                                <div class="action-group">
                                    <button class="btn btn-sm btn-success" onclick="respondToLead(${lead.id})">Respond</button>
                                    <button class="btn btn-sm btn-danger" onclick="declineLead(${lead.id})">Decline</button>
                                </div>
                            </td>
                        </tr>
                    `;
                });

                html += '</tbody></table></div>';
                container.innerHTML = html;
            }

            drawLeadsLineChart(
                'leadsTrendCanvas',
                Array.isArray(trend.labels) ? trend.labels : [],
                Array.isArray(trend.total) ? trend.total : [],
                Array.isArray(trend.handled) ? trend.handled : []
            );
            drawLeadsStatusBarChart(
                'leadsStatusCanvas',
                ['Pending', 'Responded', 'Approved', 'Finished', 'Working', 'Declined'],
                [
                    Number(summary.pending || 0),
                    Number(summary.responded || 0),
                    Number(summary.approved || 0),
                    Number(summary.finished || 0),
                    Number(summary.working || 0),
                    Number(summary.declined || 0)
                ]
            );
        }

        // ===============================================
        // FETCH VISITS
        // ===============================================
        async function updateVisitsIfNeeded() {
            if (activeTab !== 'visits') return;

            try {
                const response = await fetch(API_BASE + 'get-visits.php');
                const data = await response.json();

                if (data.success) {
                    renderVisits(data.appointments || []);
                    lastUpdate.visits = new Date().getTime();
                } else {
                    renderTabError('visits-content', data.message || 'Failed to load visits');
                }
            } catch (error) {
                console.error('Error updating visits:', error);
                renderTabError('visits-content', 'Could not load visits right now.');
            }
        }

        function renderVisits(visits) {
            const container = document.getElementById('visits-content');
            if (!container) return;
            container.classList.remove('loading');

            if (!visits || visits.length === 0) {
                container.innerHTML = '<div class="empty-state"><i class="fas fa-calendar-times"></i><p>No scheduled site visits</p></div>';
                return;
            }

            let html = `
                <div class="table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th>Customer</th>
                            <th>Property</th>
                            <th>Date & Time</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
            `;

            visits.forEach(visit => {
                const statusClass = 'status-' + (visit.status || 'pending');
                const appointmentDate = visit.appointment_date ? new Date(visit.appointment_date) : null;
                const formattedDate = appointmentDate && !Number.isNaN(appointmentDate.getTime())
                    ? appointmentDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
                    : 'N/A';
                const normalizedStatus = String(visit.status || 'pending').toLowerCase();
                const isDone = ['completed', 'done', 'finished'].includes(normalizedStatus);
                const canConfirm = ['pending', 'approved', 'scheduled'].includes(normalizedStatus);
                const canComplete = ['confirmed'].includes(normalizedStatus);
                const timeText = visit.appointment_time ? ` at ${visit.appointment_time}` : '';

                html += `
                    <tr>
                        <td>
                            <strong>${escapeHtml(visit.customer_name || 'Unknown')}</strong><br>
                            <small style="color: #999;">${escapeHtml(visit.phone || 'N/A')}</small>
                        </td>
                        <td>${escapeHtml(visit.property_title || 'N/A')}</td>
                        <td>${formattedDate}${timeText}</td>
                        <td><span class="status-badge ${statusClass}">${ucfirst(visit.status)}</span></td>
                        <td>
                            <div class="action-group">
                                ${isDone
                                    ? `<span style="font-size:12px;color:#16a34a;font-weight:600;">Done</span>`
                                    : ''}
                                ${canConfirm
                                    ? `<button class="btn btn-sm btn-success" onclick="confirmVisit(${Number(visit.id)})">Confirm</button>`
                                    : ''}
                                ${canComplete
                                    ? `<button class="btn btn-sm btn-warning" onclick="completeVisit(${Number(visit.id)})">Mark Done</button>`
                                    : ''}
                                ${!isDone && !canConfirm && !canComplete
                                    ? `<button class="btn btn-sm btn-secondary" onclick="rescheduleVisit(${Number(visit.id)})">Reschedule</button>`
                                    : ''}
                            </div>
                        </td>
                    </tr>
                `;
            });

            html += '</tbody></table></div>';
            container.innerHTML = html;
        }

        function renderTabError(containerId, message) {
            const container = document.getElementById(containerId);
            if (!container) return;
            container.classList.remove('loading');
            container.innerHTML = `<div class="empty-state"><p>${escapeHtml(message || 'Unable to load data')}</p></div>`;
        }

        // ===============================================
        // FETCH DOCUMENTS
        // ===============================================
        async function updateDocumentsIfNeeded() {
            if (activeTab !== 'documents') return;

            try {
                const [docsResponse, propertiesResponse, requestsResponse] = await Promise.all([
                    fetch(API_BASE + 'get-documents.php'),
                    fetch(API_BASE + 'get-properties.php'),
                    fetch(API_BASE + 'get-property-requests.php')
                ]);
                const docsData = await docsResponse.json();
                const propertiesData = await propertiesResponse.json();
                const requestsData = await requestsResponse.json();

                if (propertiesData.success && Array.isArray(propertiesData.properties)) {
                    brokerPropertiesCache = propertiesData.properties;
                    refreshPropertySelectOptions();
                }

                if (docsData.success) {
                    const documents = docsData.documents || [];
                    const requests = requestsData.success ? (requestsData.requests || []) : [];
                    const signature = documents
                        .map((doc) => `${doc.id}:${doc.approval_status}:${doc.approved_at || ''}:${doc.uploaded_at || ''}`)
                        .join('|');
                    const requestSignature = requests
                        .map((req) => `${req.id}:${req.approval_status}:${req.reviewed_at || ''}:${req.updated_at || ''}`)
                        .join('|');
                    const hasSelectedFile = hasDocumentFileSelected();
                    const formIsDirty = isDocumentFormDirty();
                    const listingFormDirty = isListingRequestFormDirty();

                    if (!isUploadingDocument && (formIsDirty || hasSelectedFile || listingFormDirty)) {
                        lastDocumentsSignature = signature;
                        lastPropertyRequestsSignature = requestSignature;
                        lastUpdate.documents = new Date().getTime();
                        return;
                    }
                    if (
                        signature === lastDocumentsSignature &&
                        requestSignature === lastPropertyRequestsSignature &&
                        document.getElementById('documents-content')?.dataset.rendered === '1'
                    ) {
                        lastUpdate.documents = new Date().getTime();
                        return;
                    }

                    renderDocuments(documents, requests);
                    lastDocumentsSignature = signature;
                    lastPropertyRequestsSignature = requestSignature;
                    lastUpdate.documents = new Date().getTime();
                } else {
                    const container = document.getElementById('documents-content');
                    if (container) {
                        container.classList.remove('loading');
                        container.innerHTML = `<div class="empty-state"><p>${escapeHtml(docsData.message || 'Failed to load documents')}</p></div>`;
                    }
                }
            } catch (error) {
                console.error('Error updating documents:', error);
                const container = document.getElementById('documents-content');
                if (container) {
                    container.classList.remove('loading');
                    container.innerHTML = `<div class="empty-state"><p>Could not load documents right now.</p></div>`;
                }
            }
        }

        function renderDocuments(documents, propertyRequests = []) {
            const container = document.getElementById('documents-content');
            const previousState = collectDocumentFormState();
            const previousListingState = collectListingRequestFormState();
            container.classList.remove('loading');
            container.dataset.rendered = '1';
            let html = `
                <div class="documents-layout">
                    <div class="documents-left-column">
                        <div class="document-upload-card">
                            <h3>Upload Property Document</h3>
                            <div class="section-subtitle">Send supporting files to admin for verification.</div>
                            <div class="document-form-grid">
                                <div class="document-form-group full">
                                    <label for="brokerDocumentFile">Document File *</label>
                                    <input type="file" id="brokerDocumentFile" accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.gif,.webp,.mp4,.avi,.mov">
                                    <div class="document-form-hint">Allowed: PDF, DOC, XLS, images, and videos (max 50MB).</div>
                                </div>
                                <div class="document-form-group">
                                    <label for="brokerDocumentName">Document Name</label>
                                    <input type="text" id="brokerDocumentName" placeholder="Optional custom name">
                                </div>
                                <div class="document-form-group">
                                    <label for="brokerDocumentType">Document Type</label>
                                    <input type="text" id="brokerDocumentType" placeholder="Auto from extension">
                                </div>
                                <div class="document-form-group full">
                                    <label for="brokerDocumentPropertyId">Property</label>
                                    <select id="brokerDocumentPropertyId">
                                        <option value="">Not linked to a property</option>
                                        ${buildBrokerPropertyOptions()}
                                    </select>
                                </div>
                                <div class="document-form-group full">
                                    <button type="button" class="btn" onclick="uploadBrokerDocument()">Upload for Approval</button>
                                </div>
                            </div>
                        </div>

                        <div class="document-upload-card">
                            <h3>Submit Property For Admin Approval</h3>
                            <div class="section-subtitle">Broker submits listing/update. Admin only sets final price and approves or rejects.</div>
                            <div class="document-form-grid">
                                <div class="document-form-group">
                                    <label for="brokerPropertyReqMode">Request Type</label>
                                    <select id="brokerPropertyReqMode">
                                        <option value="new">New Listing</option>
                                        <option value="update">Update Existing</option>
                                    </select>
                                </div>
                                <div class="document-form-group">
                                    <label for="brokerPropertyReqPropertyId">Existing Property</label>
                                    <select id="brokerPropertyReqPropertyId">
                                        <option value="">Select property for update</option>
                                        ${buildBrokerPropertyOptions()}
                                    </select>
                                </div>
                                <div class="document-form-group">
                                    <label for="brokerPropertyReqTitle">Title *</label>
                                    <input type="text" id="brokerPropertyReqTitle" placeholder="Property title">
                                </div>
                                <div class="document-form-group">
                                    <label for="brokerPropertyReqType">Type *</label>
                                    <select id="brokerPropertyReqType">
                                        <option value="house">House</option>
                                        <option value="apartment">Apartment</option>
                                        <option value="villa">Villa</option>
                                        <option value="commercial">Commercial</option>
                                        <option value="land">Land</option>
                                    </select>
                                </div>
                                <div class="document-form-group">
                                    <label for="brokerPropertyReqPrice">Requested Price *</label>
                                    <input type="number" id="brokerPropertyReqPrice" min="0" step="0.01" placeholder="0.00">
                                </div>
                                <div class="document-form-group">
                                    <label for="brokerPropertyReqAddress">Address *</label>
                                    <input type="text" id="brokerPropertyReqAddress" placeholder="Address">
                                </div>
                                <div class="document-form-group">
                                    <label for="brokerPropertyReqCity">City *</label>
                                    <input type="text" id="brokerPropertyReqCity" placeholder="City">
                                </div>
                                <div class="document-form-group">
                                    <label for="brokerPropertyReqState">State</label>
                                    <input type="text" id="brokerPropertyReqState" placeholder="State">
                                </div>
                                <div class="document-form-group">
                                    <label for="brokerPropertyReqBedrooms">Bedrooms</label>
                                    <input type="number" id="brokerPropertyReqBedrooms" min="0" step="1" value="0">
                                </div>
                                <div class="document-form-group">
                                    <label for="brokerPropertyReqBathrooms">Bathrooms</label>
                                    <input type="number" id="brokerPropertyReqBathrooms" min="0" step="1" value="0">
                                </div>
                                <div class="document-form-group full">
                                    <label for="brokerPropertyReqImageUrl">Image URL</label>
                                    <input type="text" id="brokerPropertyReqImageUrl" placeholder="assets/img/properties/example.jpg">
                                </div>
                                <div class="document-form-group full">
                                    <label for="brokerPropertyReqImageFile">Upload Image (Optional)</label>
                                    <input type="file" id="brokerPropertyReqImageFile" accept=".jpg,.jpeg,.png,.webp,.gif">
                                    <div class="document-form-hint">If selected, uploaded image path will be used automatically.</div>
                                </div>
                                <div class="document-form-group full">
                                    <label for="brokerPropertyReqDescription">Description</label>
                                    <input type="text" id="brokerPropertyReqDescription" placeholder="Short description">
                                </div>
                                <div class="document-form-group full">
                                    <button type="button" class="btn" onclick="submitPropertyApprovalRequest()">Submit Request</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div>
            `;

            if (!documents || documents.length === 0) {
                html += `
                    <div class="empty-state">
                        <i class="fas fa-file-upload"></i>
                        <p>No documents uploaded yet</p>
                    </div>
                    <div id="propertyApprovalRequestStatusWrap" style="margin-top:14px;"></div>
                `;
                html += '</div></div>';
                container.innerHTML = html;
                restoreDocumentFormState(previousState);
                renderPropertyRequestStatus(propertyRequests);
                restoreListingRequestFormState(previousListingState);
                return;
            }

            html += `
                <div class="table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th>Document Name</th>
                            <th>Property</th>
                            <th>Type</th>
                            <th>Size</th>
                            <th>Approval Status</th>
                            <th>Admin Details</th>
                            <th>Uploaded</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
            `;

            // let mobileHtml = '<div class="documents-mobile-list">';

            documents.forEach(doc => {
                const statusClass = 'status-' + (doc.approval_status || 'pending');
                const uploadedDate = new Date(doc.uploaded_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
                const fileSize = doc.file_size ? (doc.file_size / 1024).toFixed(2) + ' KB' : 'N/A';
                const reviewedDate = doc.approved_at ? new Date(doc.approved_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) : '';
                const adminNotes = (doc.admin_notes || '').trim();
                const docUrl = normalizeDocumentPath(doc.file_path || '');
                const propertyTitle = findPropertyTitleById(doc.property_id);

                html += `
                    <tr>
                        <td><strong>${escapeHtml(doc.document_name)}</strong></td>
                        <td>${escapeHtml(propertyTitle)}</td>
                        <td>${escapeHtml(doc.document_type || 'N/A')}</td>
                        <td>${fileSize}</td>
                        <td><span class="status-badge ${statusClass}">${ucfirst(doc.approval_status)}</span></td>
                        <td>
                            ${adminNotes ? `<div class="doc-notes">${escapeHtml(adminNotes)}</div>` : '<span class="doc-meta">No admin notes</span>'}
                            ${reviewedDate ? `<div class="doc-meta">Reviewed: ${reviewedDate}</div>` : '<div class="doc-meta">Awaiting review</div>'}
                        </td>
                        <td>${uploadedDate}</td>
                        <td>
                            <div class="action-group">
                                <a href="${escapeHtml(docUrl)}" class="btn btn-sm" target="_blank" rel="noopener">View</a>
                            </div>
                        </td>
                    </tr>
                `;

                // mobileHtml += `
                //     <div class="documents-mobile-card">
                //         <div class="documents-mobile-title">${escapeHtml(doc.document_name)}</div>
                //         <div class="documents-mobile-meta"><strong>Property:</strong> ${escapeHtml(propertyTitle)}</div>
                //         <div class="documents-mobile-meta"><strong>Type:</strong> ${escapeHtml(doc.document_type || 'N/A')}</div>
                //         <div class="documents-mobile-meta"><strong>Size:</strong> ${fileSize}</div>
                //         <div class="documents-mobile-meta"><strong>Status:</strong> <span class="status-badge ${statusClass}">${ucfirst(doc.approval_status)}</span></div>
                //         <div class="documents-mobile-meta"><strong>Uploaded:</strong> ${uploadedDate}</div>
                //         <div class="documents-mobile-meta"><strong>Admin:</strong> ${adminNotes ? escapeHtml(adminNotes) : 'No admin notes'}</div>
                //         <div class="documents-mobile-meta">${reviewedDate ? 'Reviewed: ' + reviewedDate : 'Awaiting review'}</div>
                //         <div style="margin-top:8px;">
                //             <a href="${escapeHtml(docUrl)}" class="btn btn-sm" target="_blank" rel="noopener">View</a>
                //         </div>
                //     </div>
                // `;
            });

            // mobileHtml += '</div>';
            html += '</tbody></table></div>';
            // html += mobileHtml;
            html += '<div id="propertyApprovalRequestStatusWrap" style="margin-top:14px;"></div>';
            html += '</div></div>';
            container.innerHTML = html;
            restoreDocumentFormState(previousState);
            renderPropertyRequestStatus(propertyRequests);
            restoreListingRequestFormState(previousListingState);
        }

        function buildBrokerPropertyOptions() {
            if (!Array.isArray(brokerPropertiesCache) || brokerPropertiesCache.length === 0) {
                return '';
            }

            return brokerPropertiesCache
                .map((property) => `<option value="${Number(property.id)}">${escapeHtml(property.title || ('Property #' + property.id))}</option>`)
                .join('');
        }

        function refreshPropertySelectOptions() {
            const listingSelect = document.getElementById('brokerPropertyReqPropertyId');
            const documentSelect = document.getElementById('brokerDocumentPropertyId');
            const optionsHtml = buildBrokerPropertyOptions();

            if (listingSelect) {
                const current = listingSelect.value;
                listingSelect.innerHTML = `<option value="">Select property for update</option>${optionsHtml}`;
                if (current && Array.from(listingSelect.options).some((option) => option.value === current)) {
                    listingSelect.value = current;
                }
            }

            if (documentSelect) {
                const current = documentSelect.value;
                documentSelect.innerHTML = `<option value="">Not linked to a property</option>${optionsHtml}`;
                if (current && Array.from(documentSelect.options).some((option) => option.value === current)) {
                    documentSelect.value = current;
                }
            }
        }

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

        function findPropertyTitleById(propertyId) {
            const id = Number(propertyId || 0);
            if (!id) return 'N/A';
            const property = (brokerPropertiesCache || []).find((item) => Number(item.id) === id);
            return property?.title || `Property #${id}`;
        }

        async function uploadBrokerDocument() {
            if (isUploadingDocument) return;

            const fileInput = document.getElementById('brokerDocumentFile');
            const documentNameInput = document.getElementById('brokerDocumentName');
            const documentTypeInput = document.getElementById('brokerDocumentType');
            const propertyIdInput = document.getElementById('brokerDocumentPropertyId');

            const file = fileInput?.files?.[0];
            if (!file) {
                showNotification('Please select a document file', 'error');
                return;
            }

            const formData = new FormData();
            formData.append('document', file);
            formData.append('document_name', (documentNameInput?.value || '').trim() || file.name);

            const documentType = (documentTypeInput?.value || '').trim();
            if (documentType) {
                formData.append('document_type', documentType);
            }

            const propertyId = Number(propertyIdInput?.value || 0);
            if (propertyId > 0) {
                formData.append('property_id', String(propertyId));
            }

            isUploadingDocument = true;
            try {
                const response = await fetch(API_BASE + 'upload-document.php', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();

                if (!data.success) {
                    showNotification(data.message || 'Upload failed', 'error');
                    return;
                }

                showNotification(data.message || 'Document submitted for admin review', 'success');
                if (fileInput) fileInput.value = '';
                if (documentNameInput) documentNameInput.value = '';
                if (documentTypeInput) documentTypeInput.value = '';
                if (propertyIdInput) propertyIdInput.value = '';
                documentsFormState = { dirty: false, document_name: '', document_type: '', property_id: '' };
                await updateDocumentsIfNeeded();
                await updateStats();
            } catch (error) {
                console.error('Error uploading document:', error);
                showNotification('Error uploading document', 'error');
            } finally {
                isUploadingDocument = false;
            }
        }

        function bindDocumentFormEvents() {
            const documentsContent = document.getElementById('documents-content');
            if (!documentsContent) return;

            documentsContent.addEventListener('input', (event) => {
                const id = event.target && event.target.id ? event.target.id : '';
                if (id.startsWith('brokerDocument')) {
                    documentsFormState = collectDocumentFormState();
                    documentsFormState.dirty = true;
                }
                if (id.startsWith('brokerPropertyReq')) {
                    listingRequestFormState = collectListingRequestFormState();
                    listingRequestFormState.dirty = true;
                }
            });

            documentsContent.addEventListener('change', (event) => {
                const id = event.target && event.target.id ? event.target.id : '';
                if (id.startsWith('brokerDocument')) {
                    documentsFormState = collectDocumentFormState();
                    documentsFormState.dirty = true;
                }
                if (id.startsWith('brokerPropertyReq')) {
                    listingRequestFormState = collectListingRequestFormState();
                    listingRequestFormState.dirty = true;
                    if (id === 'brokerPropertyReqMode' || id === 'brokerPropertyReqPropertyId') {
                        updatePropertyRequestModeUI();
                        syncPropertyRequestFormBySelection();
                    }
                }
            });
        }

        function collectDocumentFormState() {
            const nameInput = document.getElementById('brokerDocumentName');
            const typeInput = document.getElementById('brokerDocumentType');
            const propertyInput = document.getElementById('brokerDocumentPropertyId');

            return {
                dirty: documentsFormState.dirty,
                document_name: nameInput ? nameInput.value : documentsFormState.document_name,
                document_type: typeInput ? typeInput.value : documentsFormState.document_type,
                property_id: propertyInput ? propertyInput.value : documentsFormState.property_id
            };
        }

        function restoreDocumentFormState(state) {
            const source = state || documentsFormState || {};
            const nameInput = document.getElementById('brokerDocumentName');
            const typeInput = document.getElementById('brokerDocumentType');
            const propertyInput = document.getElementById('brokerDocumentPropertyId');

            if (nameInput && typeof source.document_name === 'string') {
                nameInput.value = source.document_name;
            }
            if (typeInput && typeof source.document_type === 'string') {
                typeInput.value = source.document_type;
            }
            if (propertyInput && typeof source.property_id === 'string') {
                propertyInput.value = source.property_id;
            }
            documentsFormState = {
                dirty: Boolean(source.dirty),
                document_name: nameInput ? nameInput.value : '',
                document_type: typeInput ? typeInput.value : '',
                property_id: propertyInput ? propertyInput.value : ''
            };
        }

        function hasDocumentFileSelected() {
            const fileInput = document.getElementById('brokerDocumentFile');
            return Boolean(fileInput && fileInput.files && fileInput.files.length > 0);
        }

        function isDocumentFormDirty() {
            const current = collectDocumentFormState();
            const hasText = Boolean((current.document_name || '').trim() || (current.document_type || '').trim() || (current.property_id || '').trim());
            const dirty = Boolean(hasText || hasDocumentFileSelected());
            documentsFormState.dirty = dirty;
            return dirty;
        }

        function collectListingRequestFormState() {
            const modeInput = document.getElementById('brokerPropertyReqMode');
            const propertyInput = document.getElementById('brokerPropertyReqPropertyId');
            const titleInput = document.getElementById('brokerPropertyReqTitle');
            const typeInput = document.getElementById('brokerPropertyReqType');
            const priceInput = document.getElementById('brokerPropertyReqPrice');
            const addressInput = document.getElementById('brokerPropertyReqAddress');
            const cityInput = document.getElementById('brokerPropertyReqCity');
            const stateInput = document.getElementById('brokerPropertyReqState');
            const bedroomsInput = document.getElementById('brokerPropertyReqBedrooms');
            const bathroomsInput = document.getElementById('brokerPropertyReqBathrooms');
            const imageInput = document.getElementById('brokerPropertyReqImageUrl');
            const descriptionInput = document.getElementById('brokerPropertyReqDescription');

            return {
                dirty: listingRequestFormState.dirty,
                request_mode: modeInput ? modeInput.value : listingRequestFormState.request_mode,
                property_id: propertyInput ? propertyInput.value : listingRequestFormState.property_id,
                title: titleInput ? titleInput.value : listingRequestFormState.title,
                type: typeInput ? typeInput.value : listingRequestFormState.type,
                price: priceInput ? priceInput.value : listingRequestFormState.price,
                address: addressInput ? addressInput.value : listingRequestFormState.address,
                city: cityInput ? cityInput.value : listingRequestFormState.city,
                state: stateInput ? stateInput.value : listingRequestFormState.state,
                bedrooms: bedroomsInput ? bedroomsInput.value : listingRequestFormState.bedrooms,
                bathrooms: bathroomsInput ? bathroomsInput.value : listingRequestFormState.bathrooms,
                image_url: imageInput ? imageInput.value : listingRequestFormState.image_url,
                description: descriptionInput ? descriptionInput.value : listingRequestFormState.description
            };
        }

        function restoreListingRequestFormState(state) {
            const source = state || listingRequestFormState || {};
            const setValue = (id, value) => {
                const element = document.getElementById(id);
                if (element && typeof value === 'string') {
                    element.value = value;
                }
            };

            setValue('brokerPropertyReqMode', source.request_mode || 'new');
            setValue('brokerPropertyReqPropertyId', source.property_id || '');
            setValue('brokerPropertyReqTitle', source.title || '');
            setValue('brokerPropertyReqType', source.type || 'house');
            setValue('brokerPropertyReqPrice', source.price || '');
            setValue('brokerPropertyReqAddress', source.address || '');
            setValue('brokerPropertyReqCity', source.city || '');
            setValue('brokerPropertyReqState', source.state || '');
            setValue('brokerPropertyReqBedrooms', source.bedrooms || '0');
            setValue('brokerPropertyReqBathrooms', source.bathrooms || '0');
            setValue('brokerPropertyReqImageUrl', source.image_url || '');
            setValue('brokerPropertyReqDescription', source.description || '');

            listingRequestFormState = {
                dirty: Boolean(source.dirty),
                request_mode: document.getElementById('brokerPropertyReqMode')?.value || 'new',
                property_id: document.getElementById('brokerPropertyReqPropertyId')?.value || '',
                title: document.getElementById('brokerPropertyReqTitle')?.value || '',
                type: document.getElementById('brokerPropertyReqType')?.value || 'house',
                price: document.getElementById('brokerPropertyReqPrice')?.value || '',
                address: document.getElementById('brokerPropertyReqAddress')?.value || '',
                city: document.getElementById('brokerPropertyReqCity')?.value || '',
                state: document.getElementById('brokerPropertyReqState')?.value || '',
                bedrooms: document.getElementById('brokerPropertyReqBedrooms')?.value || '0',
                bathrooms: document.getElementById('brokerPropertyReqBathrooms')?.value || '0',
                image_url: document.getElementById('brokerPropertyReqImageUrl')?.value || '',
                description: document.getElementById('brokerPropertyReqDescription')?.value || ''
            };
            updatePropertyRequestModeUI();
        }

        function isListingRequestFormDirty() {
            const current = collectListingRequestFormState();
            const dirty = Boolean(
                (current.title || '').trim() ||
                (current.price || '').trim() ||
                (current.address || '').trim() ||
                (current.city || '').trim() ||
                (current.state || '').trim() ||
                (current.image_url || '').trim() ||
                (current.description || '').trim() ||
                (current.property_id || '').trim() ||
                hasListingImageFileSelected() ||
                current.request_mode === 'update'
            );
            listingRequestFormState.dirty = dirty;
            return dirty;
        }

        function hasListingImageFileSelected() {
            const fileInput = document.getElementById('brokerPropertyReqImageFile');
            return Boolean(fileInput && fileInput.files && fileInput.files.length > 0);
        }

        function updatePropertyRequestModeUI() {
            const mode = document.getElementById('brokerPropertyReqMode')?.value || 'new';
            const propertyInput = document.getElementById('brokerPropertyReqPropertyId');
            if (!propertyInput) return;

            const isUpdateMode = mode === 'update';
            propertyInput.disabled = !isUpdateMode;
            propertyInput.style.opacity = isUpdateMode ? '1' : '0.75';
            if (!isUpdateMode) {
                propertyInput.value = '';
            }
        }

        function syncPropertyRequestFormBySelection() {
            const mode = document.getElementById('brokerPropertyReqMode')?.value || 'new';
            const propertyId = Number(document.getElementById('brokerPropertyReqPropertyId')?.value || 0);
            if (mode !== 'update' || propertyId <= 0) {
                return;
            }

            const selected = (brokerPropertiesCache || []).find((p) => Number(p.id) === propertyId);
            if (!selected) {
                return;
            }

            const setValue = (id, value) => {
                const element = document.getElementById(id);
                if (element) {
                    element.value = value ?? '';
                }
            };

            setValue('brokerPropertyReqTitle', selected.title || '');
            setValue('brokerPropertyReqType', selected.type || 'house');
            setValue('brokerPropertyReqPrice', selected.price ? String(selected.price) : '');
            setValue('brokerPropertyReqAddress', selected.address || '');
            setValue('brokerPropertyReqCity', selected.city || '');
            setValue('brokerPropertyReqState', selected.state || '');
            setValue('brokerPropertyReqBedrooms', selected.bedrooms != null ? String(selected.bedrooms) : '0');
            setValue('brokerPropertyReqBathrooms', selected.bathrooms != null ? String(selected.bathrooms) : '0');
            setValue('brokerPropertyReqImageUrl', selected.image_url || '');
            setValue('brokerPropertyReqDescription', selected.description || '');

            listingRequestFormState = collectListingRequestFormState();
            listingRequestFormState.dirty = true;
        }

        async function submitPropertyApprovalRequest() {
            const mode = document.getElementById('brokerPropertyReqMode')?.value || 'new';
            const payload = {
                title: (document.getElementById('brokerPropertyReqTitle')?.value || '').trim(),
                type: (document.getElementById('brokerPropertyReqType')?.value || 'house').trim(),
                price: Number(document.getElementById('brokerPropertyReqPrice')?.value || 0),
                address: (document.getElementById('brokerPropertyReqAddress')?.value || '').trim(),
                city: (document.getElementById('brokerPropertyReqCity')?.value || '').trim(),
                state: (document.getElementById('brokerPropertyReqState')?.value || '').trim(),
                bedrooms: Number(document.getElementById('brokerPropertyReqBedrooms')?.value || 0),
                bathrooms: Number(document.getElementById('brokerPropertyReqBathrooms')?.value || 0),
                image_url: (document.getElementById('brokerPropertyReqImageUrl')?.value || '').trim(),
                description: (document.getElementById('brokerPropertyReqDescription')?.value || '').trim()
            };

            if (!payload.title || !payload.type || payload.price <= 0 || !payload.address || !payload.city) {
                showNotification('Please fill title, type, requested price, address, and city', 'error');
                return;
            }

            let endpoint = API_BASE + 'submit-property.php';
            if (mode === 'update') {
                const propertyId = Number(document.getElementById('brokerPropertyReqPropertyId')?.value || 0);
                if (propertyId <= 0) {
                    showNotification('Select an existing property for update', 'error');
                    return;
                }
                endpoint = API_BASE + 'update-property.php';
                payload.property_id = propertyId;
            }

            try {
                payload.image_url = await uploadListingImageIfNeeded(payload.image_url);
                const response = await fetch(endpoint, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload)
                });
                const data = await response.json();

                if (!data.success) {
                    showNotification(data.message || 'Failed to submit request', 'error');
                    return;
                }

                showNotification(data.message || 'Property request submitted for admin approval', 'success');
                const listingImageFile = document.getElementById('brokerPropertyReqImageFile');
                if (listingImageFile) listingImageFile.value = '';
                listingRequestFormState = {
                    dirty: false,
                    request_mode: 'new',
                    property_id: '',
                    title: '',
                    type: 'house',
                    price: '',
                    address: '',
                    city: '',
                    state: '',
                    bedrooms: '0',
                    bathrooms: '0',
                    image_url: '',
                    description: ''
                };
                await updateDocumentsIfNeeded();
            } catch (error) {
                console.error('Error submitting property request:', error);
                showNotification('Error submitting property request', 'error');
            }
        }

        async function uploadListingImageIfNeeded(currentImageUrl) {
            const fileInput = document.getElementById('brokerPropertyReqImageFile');
            if (!fileInput || !fileInput.files || !fileInput.files.length) {
                return currentImageUrl;
            }
            if (isUploadingListingImage) {
                throw new Error('Image upload already in progress');
            }

            isUploadingListingImage = true;
            try {
                const formData = new FormData();
                formData.append('image', fileInput.files[0]);
                const response = await fetch(API_BASE + 'property-upload-image.php', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();
                if (!data.success) {
                    throw new Error(data.message || 'Property image upload failed');
                }
                const imageUrlInput = document.getElementById('brokerPropertyReqImageUrl');
                if (imageUrlInput) imageUrlInput.value = data.image_url || '';
                return data.image_url || currentImageUrl;
            } finally {
                isUploadingListingImage = false;
            }
        }

        function renderPropertyRequestStatus(requests) {
            const container = document.getElementById('propertyApprovalRequestStatusWrap');
            if (!container) return;

            if (!Array.isArray(requests) || requests.length === 0) {
                container.innerHTML = '<div style="padding:10px 0;color:#777;font-size:13px;">No property approval requests submitted yet.</div>';
                return;
            }

            let html = '<h3 style="margin: 0 0 10px 0; font-size:16px;">Property Request Status (Real-Time)</h3>';
            html += '<div class="table-wrap"><table><thead><tr><th>ID</th><th>Request</th><th>Property</th><th>Requested Price</th><th>Admin Price</th><th>Status</th><th>Details</th></tr></thead><tbody>';

            requests.forEach((req) => {
                const statusClass = 'status-' + (req.approval_status || 'pending');
                const requestType = req.request_type === 'new_listing' ? 'New Listing' : 'Update';
                const details = (req.admin_notes || '').trim() || (req.reviewed_at ? 'Reviewed by admin' : 'Waiting for admin review');
                html += `
                    <tr>
                        <td>#${req.id}</td>
                        <td>${requestType}</td>
                        <td>${escapeHtml(req.property_label || req.title || 'N/A')}</td>
                        <td>${req.price ? '$' + Number(req.price).toLocaleString() : '-'}</td>
                        <td>${req.admin_price ? '$' + Number(req.admin_price).toLocaleString() : '-'}</td>
                        <td><span class="status-badge ${statusClass}">${ucfirst(req.approval_status || 'pending')}</span></td>
                        <td><span class="doc-meta">${escapeHtml(details)}</span></td>
                    </tr>
                `;
            });

            html += '</tbody></table></div>';
            container.innerHTML = html;
        }

        // ===============================================
        // LEAD ACTIONS
        // ===============================================
        function respondToLead(inquiryId) {
            document.getElementById('respond-inquiry-id').value = inquiryId;
            document.getElementById('respond-message').value = '';
            openModal('respond-modal');
        }

        async function submitLeadResponse(e) {
            e.preventDefault();
            const inquiryId = document.getElementById('respond-inquiry-id').value;
            const message = document.getElementById('respond-message').value.trim();

            if (!message) {
                showNotification('Please enter a response message', 'error');
                return;
            }

            try {
                const response = await fetch(API_BASE + 'manage-lead.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        inquiry_id: inquiryId,
                        action: 'respond',
                        response: message
                    })
                });

                const data = await response.json();

                if (data.success) {
                    showNotification('Response sent successfully! ✅', 'success');
                    closeModal('respond-modal');
                    await updateLeadsIfNeeded();
                } else {
                    showNotification(data.message || 'Error sending response', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                showNotification('Error sending response', 'error');
            }
        }

        async function declineLead(inquiryId) {
            if (!confirm('Are you sure you want to decline this lead?')) return;

            try {
                const response = await fetch(API_BASE + 'manage-lead.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        inquiry_id: inquiryId,
                        action: 'disqualify'
                    })
                });

                const data = await response.json();

                if (data.success) {
                    showNotification('Lead declined ✅', 'success');
                    await updateLeadsIfNeeded();
                } else {
                    showNotification(data.message || 'Error declining lead', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                showNotification('Error declining lead', 'error');
            }
        }

        // ===============================================
        // VISIT ACTIONS
        // ===============================================
        async function confirmVisit(appointmentId) {
            try {
                const response = await fetch(API_BASE + 'manage-visit.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'confirm',
                        appointment_id: appointmentId
                    })
                });

                const data = await response.json();

                if (data.success) {
                    showNotification('Visit confirmed ✅', 'success');
                    await updateVisitsIfNeeded();
                } else {
                    showNotification(data.message || 'Error confirming visit', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                showNotification('Error confirming visit', 'error');
            }
        }

        async function completeVisit(appointmentId) {
            try {
                const response = await fetch(API_BASE + 'manage-visit.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        action: 'complete',
                        appointment_id: appointmentId
                    })
                });

                const data = await response.json();

                if (data.success) {
                    showNotification('Visit marked complete ✅', 'success');
                    await updateVisitsIfNeeded();
                } else {
                    showNotification(data.message || 'Error marking visit complete', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                showNotification('Error marking visit complete', 'error');
            }
        }

        function rescheduleVisit(appointmentId) {
            showNotification('Reschedule feature coming soon', 'info');
        }

        async function updateAssignmentWorkflow(propertyId, action) {
            const normalizedAction = action === 'finish' ? 'finish' : 'confirm';
            try {
                const response = await fetch(API_BASE + 'update-assignment-status.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ property_id: Number(propertyId), action: normalizedAction })
                });
                const data = await response.json();
                if (!data.success) {
                    showNotification(data.message || 'Could not update assignment', 'error');
                    return;
                }
                showNotification(data.message || 'Assignment updated', 'success');
                await updatePropertiesIfNeeded();
            } catch (error) {
                console.error('Error updating assignment workflow:', error);
                showNotification('Could not update assignment', 'error');
            }
        }

        // ===============================================
        // UI UTILITIES
        // ===============================================
        function switchTab(tabName) {
            activeTab = tabName;

            // Hide all tabs
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.style.display = 'none';
            });

            // Update sidebar active state
            document.querySelectorAll('.sidebar-menu .tab-link').forEach(link => {
                link.classList.remove('active');
            });
            const activeLink = document.querySelector(`.sidebar-menu .tab-link[data-tab="${tabName}"]`);
            if (activeLink) activeLink.classList.add('active');
            
            // Show selected tab
            const selectedTab = document.getElementById(tabName);
            if (selectedTab) {
                selectedTab.style.display = 'block';

                // Trigger data update for this tab
                if (tabName === 'properties') updatePropertiesIfNeeded();
                else if (tabName === 'leads') updateLeadsIfNeeded();
                else if (tabName === 'visits') updateVisitsIfNeeded();
                else if (tabName === 'documents') updateDocumentsIfNeeded();
            }

            // Show dashboard stats only on overview tab
            const overviewStats = document.getElementById('overviewStats');
            if (overviewStats) {
                overviewStats.style.display = tabName === 'overview' ? 'grid' : 'none';
            }
        }

        function openModal(modalId) {
            document.getElementById(modalId).classList.add('active');
        }

        function closeModal(modalId) {
            document.getElementById(modalId).classList.remove('active');
        }

        function showNotification(message, type = 'info') {
            const notification = document.createElement('div');
            notification.className = `notification ${type}`;
            notification.textContent = message;
            document.body.appendChild(notification);

            setTimeout(() => {
                notification.style.opacity = '0';
                setTimeout(() => notification.remove(), 300);
            }, 4000);
        }

        // ===============================================
        // HELPER FUNCTIONS
        // ===============================================
        function escapeHtml(text) {
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return text ? String(text).replace(/[&<>"']/g, m => map[m]) : '';
        }

        function ucfirst(str) {
            return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
        }

        function viewPropertyDetails(propId, propTitle) {
            const body = document.getElementById('property-view-body');
            if (!body) return;
            body.innerHTML = '<div class="loading">Loading property details...</div>';
            openModal('property-view-modal');

            fetch(`../api/get-property.php?id=${Number(propId)}`)
                .then((response) => response.json())
                .then((data) => {
                    if (!data.success || !data.property) {
                        body.innerHTML = `<div class="empty-state"><p>${escapeHtml(data.message || 'Property not found')}</p></div>`;
                        return;
                    }
                    const property = data.property;
                    const imageUrl = normalizeImagePath(property.image_url || '');
                    body.innerHTML = `
                        ${imageUrl ? `<img src="${escapeHtml(imageUrl)}" alt="${escapeHtml(property.title || 'Property')}" class="property-detail-image">` : ''}
                        <h3 style="margin:0 0 10px 0; font-size:20px; color:#111827;">${escapeHtml(property.title || 'Property')}</h3>
                        <p style="margin:0 0 12px 0; color:#475569; font-size:14px;">${escapeHtml(property.description || 'No description available')}</p>
                        <div class="property-detail-grid">
                            <div class="property-detail-item"><strong>Type:</strong>${escapeHtml(property.type || 'N/A')}</div>
                            <div class="property-detail-item"><strong>Status:</strong>${escapeHtml(property.status || 'N/A')}</div>
                            <div class="property-detail-item"><strong>Price:</strong>$${Number(property.price || 0).toLocaleString()}</div>
                            <div class="property-detail-item"><strong>Bedrooms:</strong>${escapeHtml(property.bedrooms ?? 'N/A')}</div>
                            <div class="property-detail-item"><strong>Bathrooms:</strong>${escapeHtml(property.bathrooms ?? 'N/A')}</div>
                            <div class="property-detail-item"><strong>Area:</strong>${escapeHtml(property.area ?? 'N/A')}</div>
                            <div class="property-detail-item"><strong>Address:</strong>${escapeHtml(property.address || 'N/A')}</div>
                            <div class="property-detail-item"><strong>City/State:</strong>${escapeHtml((property.city || 'N/A') + (property.state ? ', ' + property.state : ''))}</div>
                        </div>
                    `;
                })
                .catch((error) => {
                    console.error('Error loading property details:', error);
                    body.innerHTML = '<div class="empty-state"><p>Could not load property details right now.</p></div>';
                });
        }

        function editProperty(propId) {
            switchTab('documents');
            setTimeout(() => {
                const modeInput = document.getElementById('brokerPropertyReqMode');
                const propertyInput = document.getElementById('brokerPropertyReqPropertyId');
                if (modeInput) modeInput.value = 'update';
                if (propertyInput) propertyInput.value = String(propId);
                updatePropertyRequestModeUI();
                syncPropertyRequestFormBySelection();
                showNotification('Property update request form ready. Submit for admin approval.', 'info');
            }, 50);
        }

        function deleteDocument(docId) {
            if (confirm('Delete this document?')) {
                showNotification('Document deleted ✅', 'success');
            }
        }

        // ===============================================
        // CLEANUP
        // ===============================================
        window.addEventListener('beforeunload', () => {
            stopPolling();
        });

        console.log('✅ Real-Time Broker Dashboard Ready');
    </script>

</body>
</html>





