<?php
require_once '../config.php';

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

$admin_id = $_SESSION['user_id'];
$admin_name = $_SESSION['user_name'];

// Ensure settings table exists
$mysqli->query("CREATE TABLE IF NOT EXISTS site_settings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    setting_key VARCHAR(100) UNIQUE NOT NULL,
    setting_value TEXT,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)");

// Get statistics
$stats = [
    'total_users' => $mysqli->query("SELECT COUNT(*) as count FROM users")->fetch_assoc()['count'],
    'total_customers' => $mysqli->query("SELECT COUNT(*) as count FROM customers")->fetch_assoc()['count'],
    'total_brokers' => $mysqli->query("SELECT COUNT(*) as count FROM users WHERE role = 'broker' AND status = 'active'")->fetch_assoc()['count'],
    'total_agents' => $mysqli->query("SELECT COUNT(*) as count FROM users WHERE role = 'staff' AND status = 'active'")->fetch_assoc()['count'],
    'total_properties' => $mysqli->query("SELECT COUNT(*) as count FROM properties")->fetch_assoc()['count'],
];

function table_exists($db, $table_name) {
    $safe_table = $db->real_escape_string($table_name);
    $result = $db->query("SHOW TABLES LIKE '" . $safe_table . "'");
    return $result && $result->num_rows > 0;
}

function table_has_column($db, $table_name, $column_name) {
    $safe_table = $db->real_escape_string($table_name);
    $safe_column = $db->real_escape_string($column_name);
    $result = $db->query("SHOW COLUMNS FROM `" . $safe_table . "` LIKE '" . $safe_column . "'");
    return $result && $result->num_rows > 0;
}

// Analytics data for admin dashboard
$has_inquiries_table = table_exists($mysqli, 'inquiries');
$has_appointments_table = table_exists($mysqli, 'appointments');
$has_properties_table = table_exists($mysqli, 'properties');

$analytics = [
    'total_inquiries' => 0,
    'open_inquiries' => 0,
    'total_appointments' => 0,
    'scheduled_visits' => 0,
    'completed_visits' => 0,
    'listed_properties' => 0,
    'finished_properties' => 0,
    'properties_with_activity' => 0,
    'broker_pending_properties' => 0,
    'broker_approval_pending_properties' => 0,
    'broker_finished_properties' => 0
];

$recent_inquiries = [];
$recent_appointments = [];
$property_activity = [];
$trend_labels = [];
$trend_inquiries = [];
$trend_appointments = [];
$appointment_status_labels = ['Pending', 'Approved', 'Scheduled', 'Confirmed', 'Completed', 'Declined', 'Cancelled', 'Other'];
$appointment_status_counts = array_fill(0, count($appointment_status_labels), 0);
$listing_trend_labels = [];
$listing_trend_counts = [];
$listing_city_labels = [];
$listing_city_counts = [];
$property_status_breakdown = [
    'active' => 0,
    'inactive' => 0,
    'sold' => 0,
    'other' => 0
];

if ($has_properties_table) {
    $listed_result = $mysqli->query("SELECT COUNT(*) AS count FROM properties");
    if ($listed_result) {
        $analytics['listed_properties'] = intval($listed_result->fetch_assoc()['count'] ?? 0);
    }

    $finished_result = $mysqli->query("
        SELECT COUNT(*) AS count
        FROM properties
        WHERE LOWER(COALESCE(status, '')) IN ('sold', 'completed', 'closed')
    ");
    if ($finished_result) {
        $analytics['finished_properties'] = intval($finished_result->fetch_assoc()['count'] ?? 0);
    }

    $status_result = $mysqli->query("
        SELECT LOWER(COALESCE(status, 'other')) AS status_name, COUNT(*) AS count
        FROM properties
        GROUP BY LOWER(COALESCE(status, 'other'))
    ");
    if ($status_result) {
        while ($row = $status_result->fetch_assoc()) {
            $status_name = $row['status_name'];
            $count = intval($row['count'] ?? 0);
            if (isset($property_status_breakdown[$status_name])) {
                $property_status_breakdown[$status_name] = $count;
            } else {
                $property_status_breakdown['other'] += $count;
            }
        }
    }
}

if (table_exists($mysqli, 'property_assignment_workflow')) {
    $broker_pending_result = $mysqli->query("
        SELECT COUNT(*) AS count
        FROM property_assignment_workflow
        WHERE LOWER(COALESCE(workflow_status, '')) IN ('assigned', 'working')
    ");
    if ($broker_pending_result) {
        $analytics['broker_pending_properties'] = intval($broker_pending_result->fetch_assoc()['count'] ?? 0);
    }

    $broker_approval_pending_result = $mysqli->query("
        SELECT COUNT(*) AS count
        FROM property_assignment_workflow
        WHERE LOWER(COALESCE(workflow_status, '')) = 'finished_pending_admin'
    ");
    if ($broker_approval_pending_result) {
        $analytics['broker_approval_pending_properties'] = intval($broker_approval_pending_result->fetch_assoc()['count'] ?? 0);
    }

    $broker_finished_result = $mysqli->query("
        SELECT COUNT(*) AS count
        FROM property_assignment_workflow
        WHERE LOWER(COALESCE(workflow_status, '')) = 'finished_approved'
    ");
    if ($broker_finished_result) {
        $analytics['broker_finished_properties'] = intval($broker_finished_result->fetch_assoc()['count'] ?? 0);
    }
}

if ($has_inquiries_table) {
    $inquiry_count_result = $mysqli->query("SELECT COUNT(*) AS count FROM inquiries");
    if ($inquiry_count_result) {
        $analytics['total_inquiries'] = intval($inquiry_count_result->fetch_assoc()['count'] ?? 0);
    }

    $open_inquiry_result = $mysqli->query("
        SELECT COUNT(*) AS count
        FROM inquiries
        WHERE LOWER(COALESCE(status, 'pending')) IN ('pending', 'new', 'responded')
    ");
    if ($open_inquiry_result) {
        $analytics['open_inquiries'] = intval($open_inquiry_result->fetch_assoc()['count'] ?? 0);
    }

    $recent_inquiries_result = $mysqli->query("
        SELECT
            i.id,
            COALESCE(p.title, 'N/A') AS property_title,
            COALESCE(i.status, 'pending') AS inquiry_status,
            i.created_at,
            LEFT(COALESCE(i.message, ''), 120) AS inquiry_message
        FROM inquiries i
        LEFT JOIN properties p ON p.id = i.property_id
        ORDER BY i.created_at DESC
        LIMIT 8
    ");
    if ($recent_inquiries_result) {
        while ($row = $recent_inquiries_result->fetch_assoc()) {
            $recent_inquiries[] = $row;
        }
    }
}

if ($has_appointments_table) {
    $appointment_count_result = $mysqli->query("SELECT COUNT(*) AS count FROM appointments");
    if ($appointment_count_result) {
        $analytics['total_appointments'] = intval($appointment_count_result->fetch_assoc()['count'] ?? 0);
    }

    $scheduled_visits_result = $mysqli->query("
        SELECT COUNT(*) AS count
        FROM appointments
        WHERE LOWER(COALESCE(status, 'pending')) IN ('pending', 'approved', 'scheduled', 'confirmed')
    ");
    if ($scheduled_visits_result) {
        $analytics['scheduled_visits'] = intval($scheduled_visits_result->fetch_assoc()['count'] ?? 0);
    }

    $completed_visits_result = $mysqli->query("
        SELECT COUNT(*) AS count
        FROM appointments
        WHERE LOWER(COALESCE(status, '')) IN ('completed', 'done', 'finished')
    ");
    if ($completed_visits_result) {
        $analytics['completed_visits'] = intval($completed_visits_result->fetch_assoc()['count'] ?? 0);
    }

    $recent_appointments_result = $mysqli->query("
        SELECT
            a.id,
            COALESCE(p.title, 'N/A') AS property_title,
            COALESCE(a.status, 'pending') AS appointment_status,
            a.appointment_date,
            a.appointment_time,
            a.created_at
        FROM appointments a
        LEFT JOIN properties p ON p.id = a.property_id
        ORDER BY COALESCE(a.appointment_date, DATE(a.created_at)) DESC, COALESCE(a.appointment_time, '00:00:00') DESC
        LIMIT 8
    ");
    if ($recent_appointments_result) {
        while ($row = $recent_appointments_result->fetch_assoc()) {
            $recent_appointments[] = $row;
        }
    }

    $appointment_status_result = $mysqli->query("
        SELECT LOWER(COALESCE(status, 'other')) AS status_name, COUNT(*) AS count
        FROM appointments
        GROUP BY LOWER(COALESCE(status, 'other'))
    ");
    if ($appointment_status_result) {
        $status_index_map = [
            'pending' => 0,
            'approved' => 1,
            'scheduled' => 2,
            'confirmed' => 3,
            'completed' => 4,
            'declined' => 5,
            'cancelled' => 6
        ];
        while ($row = $appointment_status_result->fetch_assoc()) {
            $status_name = $row['status_name'];
            $count = intval($row['count'] ?? 0);
            if (isset($status_index_map[$status_name])) {
                $appointment_status_counts[$status_index_map[$status_name]] = $count;
            } else {
                $appointment_status_counts[7] += $count;
            }
        }
    }
}

if ($has_properties_table) {
    $property_activity_query = "
        SELECT
            p.id,
            p.title,
            p.city,
            COALESCE(p.status, 'unknown') AS property_status,
            COALESCE(iq.inquiry_count, 0) AS inquiry_count,
            COALESCE(ap.visit_count, 0) AS visit_count,
            COALESCE(ap.completed_visits, 0) AS completed_visit_count
        FROM properties p
        LEFT JOIN (
            SELECT property_id, COUNT(*) AS inquiry_count
            FROM inquiries
            GROUP BY property_id
        ) iq ON iq.property_id = p.id
        LEFT JOIN (
            SELECT
                property_id,
                COUNT(*) AS visit_count,
                SUM(CASE WHEN LOWER(COALESCE(status, '')) IN ('completed', 'done', 'finished') THEN 1 ELSE 0 END) AS completed_visits
            FROM appointments
            GROUP BY property_id
        ) ap ON ap.property_id = p.id
        ORDER BY inquiry_count DESC, visit_count DESC, p.created_at DESC
        LIMIT 12
    ";

    if (!$has_inquiries_table && !$has_appointments_table) {
        $property_activity_query = "
            SELECT
                p.id,
                p.title,
                p.city,
                COALESCE(p.status, 'unknown') AS property_status,
                0 AS inquiry_count,
                0 AS visit_count,
                0 AS completed_visit_count
            FROM properties p
            ORDER BY p.created_at DESC
            LIMIT 12
        ";
    } elseif (!$has_inquiries_table) {
        $property_activity_query = "
            SELECT
                p.id,
                p.title,
                p.city,
                COALESCE(p.status, 'unknown') AS property_status,
                0 AS inquiry_count,
                COALESCE(ap.visit_count, 0) AS visit_count,
                COALESCE(ap.completed_visits, 0) AS completed_visit_count
            FROM properties p
            LEFT JOIN (
                SELECT
                    property_id,
                    COUNT(*) AS visit_count,
                    SUM(CASE WHEN LOWER(COALESCE(status, '')) IN ('completed', 'done', 'finished') THEN 1 ELSE 0 END) AS completed_visits
                FROM appointments
                GROUP BY property_id
            ) ap ON ap.property_id = p.id
            ORDER BY visit_count DESC, p.created_at DESC
            LIMIT 12
        ";
    } elseif (!$has_appointments_table) {
        $property_activity_query = "
            SELECT
                p.id,
                p.title,
                p.city,
                COALESCE(p.status, 'unknown') AS property_status,
                COALESCE(iq.inquiry_count, 0) AS inquiry_count,
                0 AS visit_count,
                0 AS completed_visit_count
            FROM properties p
            LEFT JOIN (
                SELECT property_id, COUNT(*) AS inquiry_count
                FROM inquiries
                GROUP BY property_id
            ) iq ON iq.property_id = p.id
            ORDER BY inquiry_count DESC, p.created_at DESC
            LIMIT 12
        ";
    }

    $property_activity_result = $mysqli->query($property_activity_query);
    if ($property_activity_result) {
        while ($row = $property_activity_result->fetch_assoc()) {
            $property_activity[] = $row;
            if (intval($row['inquiry_count']) > 0 || intval($row['visit_count']) > 0) {
                $analytics['properties_with_activity']++;
            }
        }
    }
}

// Build last 6 months labels and trend series for chart
$trend_map = [];
for ($i = 5; $i >= 0; $i--) {
    $month_key = date('Y-m', strtotime("-$i month"));
    $trend_map[$month_key] = count($trend_labels);
    $trend_labels[] = date('M Y', strtotime($month_key . '-01'));
    $trend_inquiries[] = 0;
    $trend_appointments[] = 0;
}

if ($has_inquiries_table) {
    $inquiry_trend_result = $mysqli->query("
        SELECT DATE_FORMAT(created_at, '%Y-%m') AS month_key, COUNT(*) AS count
        FROM inquiries
        WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)
        GROUP BY DATE_FORMAT(created_at, '%Y-%m')
    ");
    if ($inquiry_trend_result) {
        while ($row = $inquiry_trend_result->fetch_assoc()) {
            $month_key = $row['month_key'];
            if (isset($trend_map[$month_key])) {
                $trend_inquiries[$trend_map[$month_key]] = intval($row['count'] ?? 0);
            }
        }
    }
}

if ($has_appointments_table) {
    $appointment_trend_result = $mysqli->query("
        SELECT DATE_FORMAT(created_at, '%Y-%m') AS month_key, COUNT(*) AS count
        FROM appointments
        WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)
        GROUP BY DATE_FORMAT(created_at, '%Y-%m')
    ");
    if ($appointment_trend_result) {
        while ($row = $appointment_trend_result->fetch_assoc()) {
            $month_key = $row['month_key'];
            if (isset($trend_map[$month_key])) {
                $trend_appointments[$trend_map[$month_key]] = intval($row['count'] ?? 0);
            }
        }
    }
}

if ($has_properties_table) {
    $listing_trend_map = [];
    for ($i = 5; $i >= 0; $i--) {
        $month_key = date('Y-m', strtotime("-$i month"));
        $listing_trend_map[$month_key] = count($listing_trend_labels);
        $listing_trend_labels[] = date('M Y', strtotime($month_key . '-01'));
        $listing_trend_counts[] = 0;
    }

    $listing_trend_result = $mysqli->query("
        SELECT DATE_FORMAT(created_at, '%Y-%m') AS month_key, COUNT(*) AS count
        FROM properties
        WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)
        GROUP BY DATE_FORMAT(created_at, '%Y-%m')
    ");
    if ($listing_trend_result) {
        while ($row = $listing_trend_result->fetch_assoc()) {
            $month_key = $row['month_key'];
            if (isset($listing_trend_map[$month_key])) {
                $listing_trend_counts[$listing_trend_map[$month_key]] = intval($row['count'] ?? 0);
            }
        }
    }

    $listing_city_result = $mysqli->query("
        SELECT COALESCE(NULLIF(TRIM(city), ''), 'Unknown') AS city_name, COUNT(*) AS count
        FROM properties
        GROUP BY COALESCE(NULLIF(TRIM(city), ''), 'Unknown')
        ORDER BY count DESC
        LIMIT 6
    ");
    if ($listing_city_result) {
        while ($row = $listing_city_result->fetch_assoc()) {
            $listing_city_labels[] = $row['city_name'];
            $listing_city_counts[] = intval($row['count'] ?? 0);
        }
    }
}

// Handle actions
$action = $_GET['action'] ?? '';
$message = '';

if ($action === 'save_settings' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $settings_input = [
        'company_name' => trim($_POST['company_name'] ?? 'Zemaraim Real Estate'),
        'company_email' => trim($_POST['company_email'] ?? 'info@Zemaraim.com'),
        'company_phone' => trim($_POST['company_phone'] ?? '+1 (555) 123-4567'),
        'company_address' => trim($_POST['company_address'] ?? ''),
        'default_currency' => trim($_POST['default_currency'] ?? 'USD'),
        'default_city' => trim($_POST['default_city'] ?? ''),
        'default_commission_percent' => trim($_POST['default_commission_percent'] ?? '2.50'),
        'default_property_status' => trim($_POST['default_property_status'] ?? 'active'),
        'allow_public_inquiries' => isset($_POST['allow_public_inquiries']) ? '1' : '0'
    ];

    $save_stmt = $mysqli->prepare("
        INSERT INTO site_settings (setting_key, setting_value)
        VALUES (?, ?)
        ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)
    ");

    if ($save_stmt) {
        foreach ($settings_input as $setting_key => $setting_value) {
            $save_stmt->bind_param('ss', $setting_key, $setting_value);
            $save_stmt->execute();
        }
        $save_stmt->close();
        $message = "Settings saved successfully!";
    } else {
        $message = "Error saving settings";
    }
}

if ($action === 'add_user' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $full_name = trim($_POST['full_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $role = $_POST['role'] ?? 'customer';
    $password = password_hash($_POST['password'] ?? 'password123', PASSWORD_DEFAULT);

    $stmt = $mysqli->prepare("INSERT INTO users (full_name, email, phone, role, password, status) VALUES (?, ?, ?, ?, ?, 'active')");
    $stmt->bind_param('sssss', $full_name, $email, $phone, $role, $password);
    
    if ($stmt->execute()) {
        $message = "âœ“ User created successfully!";
    } else {
        $message = "âœ— Error creating user";
    }
    $stmt->close();
}

// Fetch users
$users_result = $mysqli->query("SELECT id, full_name, email, phone, role, status, created_at FROM users ORDER BY created_at DESC LIMIT 20");
$brokers_result = $mysqli->query("SELECT id, full_name, email, phone, role, status, created_at FROM users WHERE role = 'broker' ORDER BY created_at DESC LIMIT 50");
$staff_result = $mysqli->query("SELECT id, full_name, email, phone, role, status, created_at FROM users WHERE role = 'staff' ORDER BY created_at DESC LIMIT 50");
$property_broker_fk_table = 'users';
$fk_table_result = $mysqli->query("
    SELECT LOWER(REFERENCED_TABLE_NAME) AS ref_table
    FROM information_schema.KEY_COLUMN_USAGE
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = 'properties'
      AND COLUMN_NAME = 'broker_id'
      AND REFERENCED_TABLE_NAME IS NOT NULL
    LIMIT 1
");
if ($fk_table_result && ($fk_table_row = $fk_table_result->fetch_assoc())) {
    $detected_fk_table = strtolower((string)($fk_table_row['ref_table'] ?? ''));
    if ($detected_fk_table === 'brokers' || $detected_fk_table === 'users') {
        $property_broker_fk_table = $detected_fk_table;
    }
}
$brokers_for_select_result = $property_broker_fk_table === 'brokers'
    ? $mysqli->query("SELECT id, name AS full_name FROM brokers ORDER BY name ASC")
    : $mysqli->query("SELECT id, full_name FROM users WHERE role = 'broker' AND status = 'active' ORDER BY full_name ASC");
$customer_firstname_expr = table_has_column($mysqli, 'customers', 'firstname')
    ? "firstname AS firstname"
    : (table_has_column($mysqli, 'customers', 'full_name') ? "full_name AS firstname" : "'' AS firstname");
$customer_lastname_expr = table_has_column($mysqli, 'customers', 'lastname')
    ? "lastname AS lastname"
    : "'' AS lastname";
$customer_email_expr = table_has_column($mysqli, 'customers', 'email')
    ? "email AS email"
    : "'' AS email";
$customer_phone_expr = table_has_column($mysqli, 'customers', 'phone')
    ? "phone AS phone"
    : "'' AS phone";
$customer_city_expr = table_has_column($mysqli, 'customers', 'city')
    ? "city AS city"
    : "'' AS city";
$customer_role_expr = table_has_column($mysqli, 'customers', 'role')
    ? "role AS role"
    : "'customer' AS role";
$customer_status_expr = table_has_column($mysqli, 'customers', 'status')
    ? "status AS status"
    : "'active' AS status";
$customer_created_expr = table_has_column($mysqli, 'customers', 'created_at')
    ? "created_at AS created_at"
    : "NOW() AS created_at";

$customers_result = $mysqli->query("
    SELECT
        id,
        $customer_firstname_expr,
        $customer_lastname_expr,
        $customer_email_expr,
        $customer_phone_expr,
        $customer_city_expr,
        $customer_role_expr,
        $customer_status_expr,
        $customer_created_expr
    FROM customers
    ORDER BY id DESC
    LIMIT 100
");

// Load settings with defaults
$settings_defaults = [
    'company_name' => 'Zemaraim Real Estate',
    'company_email' => 'info@Zemaraim.com',
    'company_phone' => '+1 (555) 123-4567',
    'company_address' => '',
    'default_currency' => 'USD',
    'default_city' => '',
    'default_commission_percent' => '2.50',
    'default_property_status' => 'active',
    'allow_public_inquiries' => '1'
];

$settings = $settings_defaults;
$settings_result = $mysqli->query("SELECT setting_key, setting_value FROM site_settings");
if ($settings_result) {
    while ($setting_row = $settings_result->fetch_assoc()) {
        $settings[$setting_row['setting_key']] = $setting_row['setting_value'];
    }
}

$broker_options = [];
if ($brokers_for_select_result) {
    while ($broker_opt = $brokers_for_select_result->fetch_assoc()) {
        $broker_options[] = $broker_opt;
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard - Zemaraim</title>
    <link rel="stylesheet" href="../assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="../assets/css/fontawesome.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Poppins', sans-serif; background: #f5f7fa; }
        .admin-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; left: 0; top: 0; z-index: 999; }
        .sidebar-overlay { position: fixed; inset: 0; background: rgba(0, 0, 0, 0.5); opacity: 0; pointer-events: none; transition: opacity 0.3s ease; z-index: 998; display: none; }
        .sidebar-overlay.active { opacity: 1; pointer-events: auto; display: block; }
        .sidebar.mobile-open { transform: translateX(0); visibility: visible; }
        .mobile-menu-toggle { display: none; background: none; border: none; color: #667eea; font-size: 24px; cursor: pointer; padding: 8px 12px; border-radius: 5px; transition: all 0.3s; }
        .mobile-menu-toggle:hover { background: rgba(0, 0, 0, 0.05); }
        .sidebar-logo { font-size: 24px; font-weight: 700; margin-bottom: 40px; display: flex; align-items: center; gap: 10px; }
        .sidebar-menu { list-style: none; }
        .sidebar-menu li { margin-bottom: 15px; }
        .sidebar-menu a { color: white; text-decoration: none; display: flex; align-items: center; gap: 10px; padding: 10px; border-radius: 5px; transition: all 0.3s; opacity: 0.8; }
        .sidebar-menu a:hover { opacity: 1; background: rgba(255,255,255,0.1); }
        .sidebar-menu a.active { background: rgba(255,255,255,0.2); opacity: 1; }
        .main-content{ margin-left: 280px; padding: 30px; flex: 1; }
        .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 40px; gap: 15px; }
        .header-left { display: flex; align-items: center; gap: 15px; }
        .header h1 { font-size: 28px; color: #333; }
        .user-info { display: flex; align-items: center; gap: 15px; }
        .user-info .avatar { width: 40px; height: 40px; border-radius: 50%; background: #667eea; color: white; display: flex; align-items: center; justify-content: center; }
        .logout-btn { background: #dc3545; color: white; border: none; padding: 8px 16px; border-radius: 5px; cursor: pointer; text-decoration: none; }
        .logout-btn:hover { background: #c82333; }
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 40px; }
        .stat-card { background: white; padding: 25px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.08); border-left: 4px solid #667eea; }
        .stat-card h3 { font-size: 12px; color: #999; text-transform: uppercase; margin-bottom: 10px; }
        .stat-card .number { font-size: 32px; font-weight: 700; color: #333; }
        .panel { background: white; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.08); padding: 25px; margin-top: 20px; }
        .panel h2 { font-size: 20px; margin-bottom: 20px; color: #333; }
        .btn { padding: 10px 20px; background: #667eea; color: white; border: none; border-radius: 5px; cursor: pointer; text-decoration: none; display: inline-block; }
        .btn:hover { background: #764ba2; }
        .btn-sm { padding: 6px 12px; font-size: 12px; }
        .btn-secondary { background: #999; }
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; margin-bottom: 8px; font-weight: 600; color: #333; }
        .form-group input, .form-group select { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px; }
        .form-group input:focus, .form-group select:focus { outline: none; border-color: #667eea; box-shadow: 0 0 0 3px rgba(102,126,234,0.1); }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        table th { background: #f8f9fa; padding: 12px; text-align: left; font-weight: 600; color: #333; border-bottom: 2px solid #ddd; }
        table td { padding: 12px; border-bottom: 1px solid #eee; }
        table tr:hover { background: #f8f9fa; }
        .table-responsive { overflow-x: auto; width: 100%; }
        .approval-table { min-width: 980px; }
        .approval-media-wrap { display: flex; align-items: center; gap: 10px; }
        .approval-media {
            width: 78px;
            height: 56px;
            border-radius: 8px;
            object-fit: cover;
            border: 1px solid #dbe0ea;
            background: #f3f4f6;
            flex-shrink: 0;
        }
        .approval-media-placeholder {
            width: 78px;
            height: 56px;
            border-radius: 8px;
            border: 1px dashed #cbd5e1;
            color: #64748b;
            background: #f8fafc;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 11px;
            text-transform: uppercase;
            flex-shrink: 0;
        }
        .approval-property-cell { min-width: 220px; }
        .approval-actions { display: flex; gap: 6px; flex-wrap: wrap; }
        .approval-price-input {
            width: 130px;
            padding: 6px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .approval-details-modal {
            display: none;
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, 0.55);
            z-index: 12000;
            padding: 16px;
            align-items: center;
            justify-content: center;
        }
        .approval-details-modal.active {
            display: flex;
        }
        .approval-details-dialog {
            width: min(760px, 100%);
            max-height: 92vh;
            overflow: auto;
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 18px 50px rgba(0, 0, 0, 0.25);
            padding: 18px;
        }
        .approval-details-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 10px;
            margin-bottom: 14px;
        }
        .approval-details-title {
            font-size: 18px;
            font-weight: 700;
            color: #222;
            margin: 0;
        }
        .approval-details-close {
            border: none;
            background: #f1f5f9;
            color: #334155;
            border-radius: 6px;
            padding: 6px 10px;
            cursor: pointer;
            font-weight: 600;
        }
        .approval-details-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 10px 14px;
        }
        .approval-details-item {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 10px;
        }
        .approval-details-label {
            font-size: 12px;
            color: #64748b;
            margin-bottom: 4px;
            text-transform: uppercase;
            letter-spacing: .02em;
        }
        .approval-details-value {
            font-size: 14px;
            color: #0f172a;
            word-break: break-word;
        }
        .approval-details-wide {
            grid-column: 1 / -1;
        }
        .status-badge { padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: 600; }
        .status-active { background: #d4edda; color: #155724; }
        .status-suspended { background: #f8d7da; color: #721c24; }
        .status-inactive { background: #f8d7da; color: #721c24; }
        .role-badge { padding: 4px 12px; border-radius: 5px; font-size: 12px; font-weight: 600; }
        .role-admin { background: #667eea; color: white; }
        .role-broker { background: #764ba2; color: white; }
        .role-staff { background: #17a2b8; color: white; }
        .role-customer { background: #999; color: white; }
        .message { padding: 15px; border-radius: 5px; margin-bottom: 20px; }
        .message.success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .message.error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .modal { display: none; }
        .modal.active { display: block; }
        #addUserForm.modal.active,
        #editUserForm.modal.active {
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, 0.55);
            z-index: 9999;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            overflow-y: auto;
        }
        .user-modal-dialog {
            width: min(760px, 100%);
            max-height: 90vh;
            overflow-y: auto;
            background: #fff;
            border-radius: 14px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.25);
            padding: 22px;
        }
        .user-form-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 14px;
        }
        .user-form-grid .full-row { grid-column: 1 / -1; }
        .user-modal-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
            margin-bottom: 16px;
        }
        .user-modal-header h3 {
            margin: 0;
        }
        .user-modal-actions {
            display: flex;
            gap: 10px;
            margin-top: 6px;
            flex-wrap: wrap;
        }
        #addPropertyForm.modal.active {
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, 0.55);
            z-index: 9999;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            overflow-y: auto;
        }
        .property-modal-dialog {
            width: min(980px, 100%);
            max-height: 92vh;
            overflow-y: auto;
            background: #fff;
            border-radius: 14px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.25);
            padding: 24px;
        }
        .property-form-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 16px;
        }
        .property-form-grid .full-row {
            grid-column: 1 / -1;
        }
        .image-upload-box {
            border: 1px dashed #c8d0ea;
            background: #f8faff;
            border-radius: 10px;
            padding: 12px;
        }
        .image-preview {
            margin-top: 10px;
            width: 100%;
            max-height: 180px;
            object-fit: cover;
            border-radius: 8px;
            border: 1px solid #e2e6f3;
            display: none;
        }
        .helper-text {
            font-size: 12px;
            color: #777;
            margin-top: 6px;
        }
        .assign-card {
            margin-top: 22px;
            padding: 16px;
            border: 1px solid #e5e7eb;
            border-radius: 10px;
            background: #f8fafc;
        }
        .assign-grid {
            display: grid;
            grid-template-columns: 2fr 2fr auto;
            gap: 12px;
            align-items: end;
        }
        .assign-toolbar {
            margin-top: 10px;
            display: flex;
            gap: 12px;
            align-items: center;
            flex-wrap: wrap;
        }
        .assign-toolbar .form-group {
            margin: 0;
            min-width: 220px;
            flex: 1 1 260px;
        }
        .assign-current {
            margin-top: 8px;
            font-size: 13px;
            color: #4b5563;
        }
        .assign-table {
            margin-top: 14px;
            max-height: 320px;
            overflow: auto;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            background: #fff;
        }
        .assign-status {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 999px;
            font-size: 11px;
            background: #e2e8f0;
            color: #334155;
            text-transform: capitalize;
        }
        .assign-status.unassigned { background: #e5e7eb; color: #374151; }
        .assign-status.assigned { background: #dbeafe; color: #1e40af; }
        .assign-status.working { background: #fef3c7; color: #92400e; }
        .assign-status.finished_pending_admin { background: #fed7aa; color: #9a3412; }
        .assign-status.finished_approved { background: #dcfce7; color: #166534; }
        .assign-hint {
            font-size: 12px;
            color: #6b7280;
            margin-top: 8px;
        }
        .approvals-sections {
            margin-top: 30px;
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 18px;
            align-items: start;
        }
        .approvals-card {
            border: 1px solid #e5e7eb;
            border-radius: 12px;
            background: #f8fafc;
            padding: 14px;
            min-width: 0;
            overflow: hidden;
        }
        .approvals-card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 10px;
            margin-bottom: 10px;
            flex-wrap: wrap;
        }
        .approvals-card-title {
            font-size: 18px;
            margin: 0;
            color: #1f2937;
        }
        .approvals-card-body {
            background: #fff;
            border: 1px solid #e5e7eb;
            border-radius: 10px;
            padding: 10px;
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }
        .assign-thumb {
            width: 64px;
            height: 48px;
            object-fit: cover;
            border-radius: 8px;
            border: 1px solid #dbe1ec;
            background: #f1f5f9;
        }
        .assign-thumb-fallback {
            width: 64px;
            height: 48px;
            border-radius: 8px;
            border: 1px solid #dbe1ec;
            background: linear-gradient(135deg, #c7d2fe 0%, #e2e8f0 100%);
            color: #475569;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
        }
        .feedback-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 14px;
        }
        .feedback-card {
            border: 1px solid #e5e7eb;
            border-radius: 10px;
            padding: 14px;
            background: #f8fafc;
        }
        .feedback-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 10px;
            margin-bottom: 8px;
        }
        .feedback-subject {
            font-size: 15px;
            font-weight: 700;
            color: #1f2937;
            margin: 0;
        }
        .feedback-meta {
            font-size: 12px;
            color: #6b7280;
            margin: 2px 0;
        }
        .feedback-message {
            font-size: 13px;
            color: #374151;
            margin-top: 8px;
            white-space: pre-wrap;
        }
        .feedback-rating {
            font-size: 13px;
            color: #f59e0b;
            margin-top: 8px;
        }
        #addServiceForm.modal.active {
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, 0.55);
            z-index: 9999;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            overflow-y: auto;
        }
        .service-modal-dialog {
            width: min(820px, 100%);
            max-height: 92vh;
            overflow-y: auto;
            background: #fff;
            border-radius: 14px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.25);
            padding: 24px;
        }
        .service-form-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 16px;
        }
        .service-form-grid .full-row {
            grid-column: 1 / -1;
        }
        @media (max-width: 1024px) {
            .service-form-grid {
                grid-template-columns: repeat(2, minmax(0, 1fr));
            }
        }
        @media (max-width: 768px) {
            .service-modal-dialog {
                padding: 16px;
                width: 95%;
            }
            .service-form-grid {
                grid-template-columns: 1fr;
                gap: 12px;
            }
        }
        @media (max-width: 480px) {
            .service-modal-dialog {
                padding: 12px;
                max-height: 95vh;
            }
            .service-form-grid {
                grid-template-columns: 1fr;
            }
        }
        .settings-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        .settings-card { background: #f8f9fa; padding: 20px; border-radius: 10px; margin-bottom: 20px; }
        .settings-card h3 { margin-bottom: 15px; font-size: 16px; color: #333; }
        .settings-actions { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 10px; }
        .analytics-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 15px; margin-bottom: 25px; }
        .analytics-card { background: #f8f9fa; border-radius: 8px; padding: 15px; border-left: 4px solid #667eea; }
        .analytics-card h4 { font-size: 12px; color: #666; margin: 0 0 8px 0; text-transform: uppercase; }
        .analytics-card .value { font-size: 26px; font-weight: 700; color: #333; margin: 0; }
        .analytics-section-title { font-size: 18px; font-weight: 700; color: #333; margin: 25px 0 10px 0; }
        .analytics-table-wrap { overflow-x: auto; }
        .analytics-empty { color: #888; font-style: italic; padding: 10px 0; }
        .analytics-charts-grid { display: grid; grid-template-columns: 2fr 1fr; gap: 20px; margin: 10px 0 20px; }
        .chart-card { background: #f8f9fa; border-radius: 10px; padding: 15px; }
        .chart-title { font-size: 15px; font-weight: 700; color: #333; margin-bottom: 12px; }
        .trend-chart-canvas { width: 100%; height: 230px; display: block; background: #fff; border-radius: 8px; }
        .chart-legend { display: flex; gap: 15px; margin-top: 10px; flex-wrap: wrap; font-size: 12px; color: #666; }
        .legend-dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; margin-right: 6px; }
        .donut-wrap { display: flex; align-items: center; gap: 15px; flex-wrap: wrap; }
        .donut-chart {
            width: 170px;
            height: 170px;
            border-radius: 50%;
            background: conic-gradient(
                #28a745 0deg var(--slice-active),
                #ffc107 var(--slice-active) var(--slice-inactive),
                #dc3545 var(--slice-inactive) var(--slice-sold),
                #6c757d var(--slice-sold) 360deg
            );
            position: relative;
        }
        .donut-chart::after {
            content: "";
            position: absolute;
            width: 95px;
            height: 95px;
            border-radius: 50%;
            background: #f8f9fa;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
        .donut-labels { font-size: 13px; color: #555; }
        .donut-labels div { margin-bottom: 7px; }
        .mini-charts-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 15px; margin: 10px 0 18px; }
        .mini-chart-canvas { width: 100%; height: 210px; display: block; background: #fff; border-radius: 8px; }
        @media (max-width: 1200px) {
            .sidebar { width: 280px; }
            .main-content { margin-left: 280px; }
            .analytics-grid { grid-template-columns: repeat(2, 1fr); }
        }
        @media (max-width: 992px) {
            .sidebar { width: 280px; }
            .main-content { margin-left: 280px; padding: 25px; }
            .header { flex-direction: column; align-items: flex-start; gap: 15px; }
            .header h1 { font-size: 24px; }
            .user-info { gap: 12px; }
            .stats-grid { grid-template-columns: repeat(2, 1fr); }
            .analytics-grid { grid-template-columns: 1fr; }
            .analytics-charts-grid { grid-template-columns: 1fr; }
            .service-grid, .property-grid { grid-template-columns: repeat(2, 1fr); }
        }
        @media (max-width: 768px) {
            .admin-wrapper { flex-direction: column; }
            .sidebar { width: auto; position: fixed; left: 0; top: 0; transform: translateX(-100%); visibility: hidden; transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), visibility 0.3s ease; padding: 20px 15px; max-height: 100vh; overflow-y: auto; z-index: 999; }
            .mobile-menu-toggle { display: block; }
            .main-content { margin-left: 0; padding: 20px; }
            .header { flex-direction: row; align-items: center; margin-bottom: 25px; position: sticky; top: 0; background: #f5f7fa; z-index: 100; padding: 15px 0; }
            .header-left { gap: 12px; }
            .header h1 { font-size: 20px; }
            .user-info { gap: 10px; font-size: 14px; }
            .user-info .avatar { width: 36px; height: 36px; }
            .logout-btn { padding: 6px 12px; font-size: 12px; }
            .stats-grid { grid-template-columns: repeat(2, 1fr); gap: 15px; margin-bottom: 25px; }
            .stat-card { padding: 18px; }
            .stat-card h3 { font-size: 11px; }
            .stat-card .number { font-size: 24px; }
            .panel { padding: 18px; margin-top: 15px; }
            .panel h2 { font-size: 18px; margin-bottom: 15px; }
            .table-responsive { overflow-x: auto; }
            .service-grid { grid-template-columns: 1fr; }
            .property-grid { grid-template-columns: 1fr; }
            .settings-grid { grid-template-columns: 1fr; }
            .analytics-grid { grid-template-columns: 1fr; }
            .analytics-charts-grid { grid-template-columns: 1fr; }
            .property-modal-dialog { padding: 16px; max-height: 95vh; }
            .property-form-grid { grid-template-columns: 1fr; }
            .assign-grid { grid-template-columns: 1fr; }
            .assign-toolbar { flex-direction: column; align-items: stretch; }
            .approvals-sections { grid-template-columns: 1fr; }
            .feedback-grid { grid-template-columns: 1fr; }
            .service-modal-dialog { padding: 16px; max-height: 95vh; }
            .service-form-grid { grid-template-columns: 1fr; }
            .user-modal-dialog { padding: 16px; max-height: 95vh; }
            .user-form-grid { grid-template-columns: 1fr; }
            .user-modal-actions .btn { flex: 1 1 100%; }
            .approval-table { min-width: 860px; }
            .approval-media, .approval-media-placeholder { width: 64px; height: 48px; }
            .approval-details-grid { grid-template-columns: 1fr; }
            .sidebar-logo { font-size: 18px; margin-bottom: 25px; }
            .sidebar-logo span { display: inline; }
        }
        @media (max-width: 480px) {
            .sidebar { padding: 15px 12px; }
            .main-content { padding: 15px; }
            .header { margin-bottom: 20px; }
            .header h1 { font-size: 18px; }
            .user-info { gap: 8px; font-size: 12px; }
            .user-info .avatar { width: 32px; height: 32px; font-size: 12px; }
            .logout-btn { padding: 5px 10px; font-size: 11px; }
            .stats-grid { grid-template-columns: 1fr; gap: 12px; margin-bottom: 20px; }
            .stat-card { padding: 15px; }
            .stat-card h3 { font-size: 10px; }
            .stat-card .number { font-size: 22px; }
            .panel { padding: 15px; margin-top: 12px; }
            .panel h2 { font-size: 16px; margin-bottom: 12px; }
            .btn { padding: 8px 12px; font-size: 12px; }
            .btn-sm { padding: 5px 10px; font-size: 10px; }
            .form-group input, .form-group select { padding: 8px; font-size: 13px; }
            table { font-size: 12px; }
            table th { padding: 10px; }
            table td { padding: 10px; }
            .service-card, .property-card { padding: 15px; }
            .card-title { font-size: 14px; }
            .card-meta { font-size: 12px; }
            .card-actions { gap: 4px; }
            .btn-edit, .btn-delete { padding: 5px; font-size: 10px; }
            .sidebar-logo { font-size: 16px; margin-bottom: 20px; }
            .sidebar-menu li { margin-bottom: 12px; }
            .sidebar-menu a { padding: 8px; font-size: 13px; }
            .approvals-card { padding: 12px; }
            .approvals-card-title { font-size: 16px; }
            .approvals-card-body { padding: 8px; }
        }
        .service-grid, .property-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px; margin-top: 20px; }
        .service-card, .property-card { background: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.08); transition: all 0.3s; position: relative; }
        .service-card:hover, .property-card:hover { transform: translateY(-3px); box-shadow: 0 5px 20px rgba(0,0,0,0.15); }
        .property-image { width: 100%; height: 200px; object-fit: cover; border-radius: 8px; margin-bottom: 15px; }
        .property-image-placeholder { width: 100%; height: 200px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 8px; margin-bottom: 15px; display: flex; align-items: center; justify-content: center; color: white; font-size: 40px; }
        .card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; }
        .card-title { font-size: 16px; font-weight: 600; color: #333; }
        .card-meta { font-size: 13px; color: #999; margin: 8px 0; }
        .card-actions { display: flex; gap: 8px; margin-top: 15px; flex-wrap: wrap; }
        .btn-edit, .btn-delete { flex: 1; min-width: 80px; padding: 8px; font-size: 12px; border: none; border-radius: 5px; cursor: pointer; font-weight: 600; transition: all 0.3s; }
        .btn-edit { background: #667eea; color: white; }
        .btn-edit:hover { background: #764ba2; transform: translateY(-2px); }
        .btn-delete { background: #dc3545; color: white; }
        .btn-delete:hover { background: #c82333; transform: translateY(-2px); }
        .pagination { display: flex; gap: 5px; margin-top: 20px; justify-content: center; flex-wrap: wrap; }
        .pagination button { padding: 8px 12px; border: 1px solid #ddd; background: white; cursor: pointer; border-radius: 5px; transition: all 0.3s; }
        .pagination button.active { background: #667eea; color: white; border-color: #667eea; }
        .pagination button:hover { border-color: #667eea; }
        .tabs { display: flex; gap: 10px; margin-bottom: 20px; border-bottom: 2px solid #eee; }
        .tab-button { padding: 10px 20px; background: none; border: none; cursor: pointer; border-bottom: 3px solid transparent; color: #999; font-weight: 600; transition: all 0.3s; }
        .tab-button.active { color: #667eea; border-bottom-color: #667eea; }
        .spinner { display: inline-block; width: 30px; height: 30px; border: 3px solid #f3f3f3; border-top: 3px solid #667eea; border-radius: 50%; animation: spin 1s linear infinite; }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
        
        /* Modal Styles */
        .modal { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; border-radius: 10px; box-shadow: 0 10px 40px rgba(0,0,0,0.2); z-index: 1001; max-height: 90vh; overflow-y: auto; }
        .modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 1000; }
        .modal-content { padding: 0; }
        .modal-header { padding: 20px; border-bottom: 1px solid #eee; display: flex; justify-content: space-between; align-items: center; }
        .modal-header h3 { margin: 0; color: #333; font-size: 18px; }
        .modal-close { background: none; border: none; font-size: 24px; cursor: pointer; color: #999; }
        .modal-close:hover { color: #333; }
        .modal-body { padding: 20px; }
        .modal-body .form-group { margin-bottom: 15px; }
        .modal-body textarea { resize: vertical; }
        .modal-footer { padding: 15px 20px; border-top: 1px solid #eee; display: flex; gap: 10px; justify-content: flex-end; }
        #heroSliderModal {
            position: fixed;
            inset: 0;
            z-index: 1001;
            padding: 18px;
            overflow-y: auto;
            transform: none;
            left: 0;
            top: 0;
            margin: 0;
            border-radius: 0;
            background: transparent;
            box-shadow: none;
            max-height: 100vh;
        }
        #heroSliderModal .modal-content {
            max-width: 980px;
            width: 100%;
            margin: 0 auto;
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 24px 50px rgba(0, 0, 0, 0.22);
        }
        .hero-slider-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
            gap: 20px;
        }
        @media (max-width: 1024px) {
            .hero-slider-list {
                grid-template-columns: repeat(2, 1fr);
                gap: 15px;
            }
        }
        @media (max-width: 768px) {
            .hero-slider-list {
                grid-template-columns: 1fr;
                gap: 15px;
            }
        }
        .hero-slider-form-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 14px;
        }
        .hero-slider-form-grid .full-row {
            grid-column: 1 / -1;
        }
        .hero-slider-card {
            background: #fff;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            transition: transform 0.3s;
        }
        .hero-slider-card:hover {
            transform: translateY(-2px);
        }
        .hero-slider-thumb {
            width: 100%;
            height: 168px;
            object-fit: cover;
            border-bottom: 1px solid #eef1f7;
            background: #f6f8fc;
        }
        .hero-slider-thumb-placeholder {
            width: 100%;
            height: 168px;
            border-bottom: 1px solid #eef1f7;
            background: linear-gradient(135deg, #e0e7ff 0%, #f1f5f9 100%);
            color: #475569;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 22px;
        }
        .hero-slider-card-buttons {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        .hero-slider-card-buttons button {
            flex: 1;
            min-width: 80px;
        }
        @media (max-width: 480px) {
            .hero-slider-card-buttons {
                flex-direction: column;
            }
            .hero-slider-card-buttons button {
                flex: 1 1 100%;
            }
        }
        .hero-url-custom {
            display: none;
            margin-top: 8px;
        }
        
        @media (max-width: 1024px) {
            .service-grid, .property-grid { grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); }
        }
        @media (max-width: 768px) {
            .service-grid, .property-grid { grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); }
            .card-actions { gap: 5px; }
            .btn-edit, .btn-delete { padding: 6px; font-size: 11px; }
            .modal { width: 90vw; max-width: 500px; }
            #heroSliderModal { padding: 12px; }
            #heroSliderModal .modal-content { max-width: 100%; }
            .hero-slider-form-grid { grid-template-columns: 1fr; }
            .hero-slider-list { grid-template-columns: 1fr; }
            .modal-footer { flex-wrap: wrap; }
            .modal-footer .btn { flex: 1 1 100%; }
        }
    </style>
</head>
<body>

    <!-- Sidebar -->
    <div class="sidebar">
        <div class="sidebar-logo">
            <i class="fas fa-th-large"></i>
            <span>Dashboard</span>
        </div>
        <ul class="sidebar-menu">
            <li><a href="?section=overview" class="active"><i class="fas fa-chart-pie"></i> <span>Overview</span></a></li>
            <li><a href="?section=users"><i class="fas fa-users"></i> <span>Users</span></a></li>
            <li><a href="?section=customers"><i class="fas fa-user"></i> <span>Customers</span></a></li>
            <li><a href="?section=brokers"><i class="fas fa-briefcase"></i> <span>Brokers</span></a></li>
            <li><a href="?section=staff"><i class="fas fa-user-tie"></i> <span>Staff</span></a></li>
            <li><a href="?section=properties"><i class="fas fa-home"></i> <span>Properties</span></a></li>
            <li><a href="?section=assignments"><i class="fas fa-link"></i> <span>Assign Property</span></a></li>
            <li><a href="?section=feedback"><i class="fas fa-star"></i> <span>Customer Feedback</span></a></li>
            <li><a href="?section=services"><i class="fas fa-cogs"></i> <span>Services</span></a></li>
            <li><a href="?section=heroSliderPanel"><i class="fas fa-sliders-h"></i> <span>Hero Slider</span></a></li>
            <li><a href="?section=analytics"><i class="fas fa-bar-chart"></i> <span>Analytics</span></a></li>
            <li><a href="?section=settings"><i class="fas fa-cog"></i> <span>Settings</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> Admin Dashboard</h1>
                    <p style="color: #999; margin-top: 5px;">Welcome back, <?php echo htmlspecialchars($admin_name); ?>!</p>
                </div>
            </div>
            <div class="user-info">
                <span><?php echo htmlspecialchars($_SESSION['email']); ?></span>
                <div class="avatar"><?php echo strtoupper(substr($admin_name, 0, 1)); ?></div>
                <a href="../logout.php" class="logout-btn">Logout</a>
            </div>
        </div>

        <?php if ($message): ?>
            <div class="message <?php echo strpos($message, 'âœ“') !== false ? 'success' : 'error'; ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>

        <!-- Statistics -->
        <div class="stats-grid">
            <div class="stat-card" style="border-left-color: #667eea;">
                <h3>Total Users</h3>
                <div class="number"><?php echo $stats['total_users']; ?></div>
            </div>
            <div class="stat-card" style="border-left-color: #20c997;">
                <h3>Total Customers</h3>
                <div class="number"><?php echo $stats['total_customers']; ?></div>
            </div>
            <div class="stat-card" style="border-left-color: #764ba2;">
                <h3>Active Brokers</h3>
                <div class="number"><?php echo $stats['total_brokers']; ?></div>
            </div>
            <div class="stat-card" style="border-left-color: #17a2b8;">
                <h3>Active Staff</h3>
                <div class="number"><?php echo $stats['total_agents']; ?></div>
            </div>
            <div class="stat-card" style="border-left-color: #28a745;">
                <h3>Total Properties</h3>
                <div class="number"><?php echo $stats['total_properties']; ?></div>
            </div>
        </div>

        <!-- Users Management Panel -->
        <div class="panel" id="overviewPanel" style="display: none;">
            <h2>Overview</h2>
            <p style="color:#666; margin:0;">Use the sidebar to manage users, customers, brokers, staff, properties, services, analytics, and settings.</p>
        </div>

        <div class="panel" id="usersPanel" style="display: none;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h2> User Management</h2>
                <button class="btn" onclick="showAddUserForm()">+ Add New User</button>
            </div>

            <div id="addUserForm" class="modal" onclick="handleUserModalOverlayClick(event, 'addUserForm')">
                <div class="user-modal-dialog">
                    <div class="user-modal-header">
                        <h3>Add New User</h3>
                        <button type="button" class="btn btn-secondary btn-sm" onclick="hideAddUserForm()">Close</button>
                    </div>
                    <form method="POST" action="?action=add_user">
                    <div class="user-form-grid">
                        <div class="form-group">
                            <label>Full Name *</label>
                            <input type="text" name="full_name" required>
                        </div>
                        <div class="form-group">
                            <label>Email *</label>
                            <input type="email" name="email" required>
                        </div>
                        <div class="form-group">
                            <label>Phone</label>
                            <input type="tel" name="phone">
                        </div>
                        <div class="form-group">
                            <label>Role *</label>
                            <select name="role" required>
                                <option value="customer">Customer</option>
                                <option value="broker">Broker</option>
                                <option value="staff">Staff</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Password *</label>
                            <input type="password" name="password" placeholder="Leave blank for default: password123" value="password123">
                        </div>
                    </div>
                    <div class="user-modal-actions">
                        <button type="submit" class="btn">Create User</button>
                        <button type="button" class="btn btn-secondary" onclick="hideAddUserForm()">Cancel</button>
                    </div>
                    </form>
                </div>
            </div>

            <div id="editUserForm" class="modal" onclick="handleUserModalOverlayClick(event, 'editUserForm')">
                <div class="user-modal-dialog">
                    <h3 style="margin-bottom: 16px;">Edit User</h3>
                    <input type="hidden" id="editUserId">
                    <div class="user-form-grid">
                        <div class="form-group">
                            <label>Full Name *</label>
                            <input type="text" id="editUserName" required>
                        </div>
                        <div class="form-group">
                            <label>Email *</label>
                            <input type="email" id="editUserEmail" required>
                        </div>
                        <div class="form-group">
                            <label>Phone</label>
                            <input type="text" id="editUserPhone">
                        </div>
                        <div class="form-group">
                            <label>Role *</label>
                            <select id="editUserRole">
                                <option value="customer">Customer</option>
                                <option value="broker">Broker</option>
                                <option value="staff">Staff</option>
                                <option value="admin">Admin</option>
                            </select>
                        </div>
                        <div class="form-group full-row">
                            <label>Status</label>
                            <select id="editUserStatus">
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                        </div>
                    </div>
                    <div style="display:flex; gap:10px;">
                        <button type="button" class="btn" onclick="saveUserEdit()">Save Changes</button>
                        <button type="button" class="btn btn-secondary" onclick="hideEditUserForm()">Cancel</button>
                    </div>
                </div>
            </div>

            <div class="table-responsive">
                <table>
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Role</th>
                            <th>Status</th>
                            <th>Joined</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($user = $users_result->fetch_assoc()): ?>
                            <tr data-user-id="<?php echo intval($user['id']); ?>" data-user-role="<?php echo htmlspecialchars($user['role']); ?>">
                                <td><?php echo htmlspecialchars($user['full_name']); ?></td>
                                <td><?php echo htmlspecialchars($user['email']); ?></td>
                                <td><span class="role-badge role-<?php echo $user['role']; ?>"><?php echo ucfirst($user['role']); ?></span></td>
                                <td><span class="status-badge status-<?php echo $user['status']; ?>"><?php echo ucfirst($user['status']); ?></span></td>
                                <td><?php echo date('M d, Y', strtotime($user['created_at'])); ?></td>
                                <td>
                                    <button class="btn btn-sm" onclick="editUser(<?php echo $user['id']; ?>)">Edit</button>
                                    <button class="btn btn-sm btn-secondary" onclick="suspendUser(<?php echo $user['id']; ?>)"><?php echo $user['status'] === 'active' ? 'Suspend' : 'Activate'; ?></button>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Customers Panel -->
        <div class="panel" id="customersPanel" style="display: none;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h2>Customers</h2>
                <span class="role-badge role-customer">Total: <?php echo $stats['total_customers']; ?></span>
            </div>

            <div class="table-responsive">
                <table>
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Phone</th>
                            <th>City</th>
                            <th>Role</th>
                            <th>Status</th>
                            <th>Joined</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($customers_result && $customers_result->num_rows > 0): ?>
                            <?php while ($customer = $customers_result->fetch_assoc()): ?>
                                <tr data-customer-id="<?php echo intval($customer['id']); ?>">
                                    <td><?php echo htmlspecialchars(trim(($customer['firstname'] ?? '') . ' ' . ($customer['lastname'] ?? ''))); ?></td>
                                    <td><?php echo htmlspecialchars($customer['email'] ?? '-'); ?></td>
                                    <td><?php echo htmlspecialchars($customer['phone'] ?? '-'); ?></td>
                                    <td><?php echo htmlspecialchars($customer['city'] ?? '-'); ?></td>
                                    <td><span class="role-badge role-customer"><?php echo htmlspecialchars(ucfirst($customer['role'] ?? 'customer')); ?></span></td>
                                    <td><span class="status-badge status-<?php echo (($customer['status'] ?? 'active') === 'inactive') ? 'inactive' : 'active'; ?>"><?php echo htmlspecialchars(ucfirst($customer['status'] ?? 'active')); ?></span></td>
                                    <td><?php echo !empty($customer['created_at']) ? date('M d, Y', strtotime($customer['created_at'])) : '-'; ?></td>
                                    <td>
                                        <button class="btn btn-sm btn-secondary" onclick="toggleCustomerStatus(<?php echo intval($customer['id']); ?>)"><?php echo (($customer['status'] ?? 'active') === 'inactive') ? 'Activate' : 'Suspend'; ?></button>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="8" style="text-align:center; color:#777;">No customers found.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Brokers Panel -->
        <div class="panel" id="brokersPanel" style="display: none;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h2>Broker Users</h2>
                <span class="role-badge role-broker">Total: <?php echo $stats['total_brokers']; ?></span>
            </div>

            <div class="table-responsive">
                <table>
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Phone</th>
                            <th>Status</th>
                            <th>Joined</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($brokers_result && $brokers_result->num_rows > 0): ?>
                            <?php while ($broker = $brokers_result->fetch_assoc()): ?>
                                <tr data-user-id="<?php echo intval($broker['id']); ?>" data-user-role="<?php echo htmlspecialchars($broker['role']); ?>">
                                    <td><?php echo htmlspecialchars($broker['full_name']); ?></td>
                                    <td><?php echo htmlspecialchars($broker['email']); ?></td>
                                    <td><?php echo htmlspecialchars($broker['phone'] ?? '-'); ?></td>
                                    <td><span class="status-badge status-<?php echo $broker['status']; ?>"><?php echo ucfirst($broker['status']); ?></span></td>
                                    <td><?php echo date('M d, Y', strtotime($broker['created_at'])); ?></td>
                                    <td>
                                        <button class="btn btn-sm" onclick="editUser(<?php echo $broker['id']; ?>)">Edit</button>
                                        <button class="btn btn-sm btn-secondary" onclick="suspendUser(<?php echo $broker['id']; ?>)"><?php echo $broker['status'] === 'active' ? 'Suspend' : 'Activate'; ?></button>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="6" style="text-align:center; color:#777;">No broker users found.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Staff Panel -->
        <div class="panel" id="staffPanel" style="display: none;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h2>Staff Users</h2>
                <span class="role-badge role-staff">Total: <?php echo $stats['total_agents']; ?></span>
            </div>

            <div class="table-responsive">
                <table>
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Phone</th>
                            <th>Status</th>
                            <th>Joined</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($staff_result && $staff_result->num_rows > 0): ?>
                            <?php while ($staff = $staff_result->fetch_assoc()): ?>
                                <tr data-user-id="<?php echo intval($staff['id']); ?>" data-user-role="<?php echo htmlspecialchars($staff['role']); ?>">
                                    <td><?php echo htmlspecialchars($staff['full_name']); ?></td>
                                    <td><?php echo htmlspecialchars($staff['email']); ?></td>
                                    <td><?php echo htmlspecialchars($staff['phone'] ?? '-'); ?></td>
                                    <td><span class="status-badge status-<?php echo $staff['status']; ?>"><?php echo ucfirst($staff['status']); ?></span></td>
                                    <td><?php echo date('M d, Y', strtotime($staff['created_at'])); ?></td>
                                    <td>
                                        <button class="btn btn-sm" onclick="editUser(<?php echo $staff['id']; ?>)">Edit</button>
                                        <button class="btn btn-sm btn-secondary" onclick="suspendUser(<?php echo $staff['id']; ?>)"><?php echo $staff['status'] === 'active' ? 'Suspend' : 'Activate'; ?></button>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="6" style="text-align:center; color:#777;">No staff users found.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Properties Management Panel -->
        <div class="panel" id="propertiesPanel" style="display: none;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h2 Properties Management</h2>
                <button class="btn" onclick="openAddPropertyModal()">+ Add New Property</button>
            </div>

            <div id="addPropertyForm" class="modal">
                <div class="property-modal-dialog">
                    <h3 id="propertyFormTitle" style="margin-bottom: 20px;">Add New Property</h3>
                    <div class="property-form-grid">
                        <div class="form-group">
                            <label>Title *</label>
                            <input type="text" id="propertyTitle" required>
                        </div>
                        <div class="form-group">
                            <label>Type *</label>
                            <select id="propertyType" required>
                                <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="form-group">
                            <label>Price *</label>
                            <input type="number" id="propertyPrice" min="0" step="1" required>
                        </div>
                        <div class="form-group">
                            <label>Status</label>
                            <select id="propertyStatus">
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                                <option value="sold">Sold</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Assign Broker</label>
                            <select id="propertyBrokerId">
                                <option value="0">Unassigned</option>
                                <?php foreach ($broker_options as $broker_option): ?>
                                    <option value="<?php echo intval($broker_option['id']); ?>">
                                        <?php echo htmlspecialchars($broker_option['full_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Address *</label>
                            <input type="text" id="propertyAddress" required>
                        </div>
                        <div class="form-group">
                            <label>City *</label>
                            <input type="text" id="propertyCity" required>
                        </div>
                        <div class="form-group">
                            <label>State</label>
                            <input type="text" id="propertyState">
                        </div>
                        <div class="form-group">
                            <label>Bedrooms</label>
                            <input type="number" id="propertyBedrooms" min="0" step="1" value="0">
                        </div>
                        <div class="form-group">
                            <label>Bathrooms</label>
                            <input type="number" id="propertyBathrooms" min="0" step="1" value="0">
                        </div>
                        <div class="form-group full-row">
                            <label>Property Image Upload</label>
                            <div class="image-upload-box">
                                <input type="file" id="propertyImageFile" accept="image/*">
                                <div class="helper-text">Upload JPG, PNG, WEBP, or GIF image (max 5MB).</div>
                                <img id="propertyImagePreview" class="image-preview" alt="Property preview">
                            </div>
                        </div>
                        <div class="form-group full-row">
                            <label>Image URL (optional)</label>
                            <input type="text" id="propertyImageUrl" placeholder="assets/img/properties/example.jpg">
                            <div class="helper-text">You can upload an image above or paste a URL/path here.</div>
                        </div>
                        <div class="form-group full-row">
                            <label>Description</label>
                            <textarea id="propertyDescription" rows="4" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-family: inherit;"></textarea>
                        </div>
                    </div>
                    <div style="display: flex; gap: 10px; margin-top: 6px;">
                        <button type="button" class="btn" onclick="saveProperty()">Save Property</button>
                        <button type="button" class="btn btn-secondary" onclick="closeAddPropertyModal()">Cancel</button>
                    </div>
                </div>
            </div>
            
            <div id="propertiesContent">
                <div style="text-align: center; padding: 40px;">
                    <div class="spinner"></div>
                    <p>Loading properties...</p>
                </div>
            </div>
            <div class="approvals-sections">
                <section class="approvals-card">
                    <div class="approvals-card-header">
                        <h3 class="approvals-card-title">Pending Broker Listings & Updates</h3>
                        <button class="btn btn-sm btn-secondary" onclick="loadPropertyApprovals()">Refresh Requests</button>
                    </div>
                    <div class="approvals-card-body">
                        <div id="propertyApprovalsContent">
                            <div style="text-align: center; padding: 15px; color:#777;">Loading requests...</div>
                        </div>
                    </div>
                </section>
                <section class="approvals-card">
                    <div class="approvals-card-header">
                        <h3 class="approvals-card-title">Pending Broker Documents</h3>
                        <button class="btn btn-sm btn-secondary" onclick="loadDocumentApprovals()">Refresh Documents</button>
                    </div>
                    <div class="approvals-card-body">
                        <div id="documentApprovalsContent">
                            <div style="text-align: center; padding: 15px; color:#777;">Loading documents...</div>
                        </div>
                    </div>
                </section>
            </div>
        </div>

        <div class="panel" id="assignmentsPanel" style="display: none;">
            <div style="display:flex; justify-content: space-between; align-items:center; margin-bottom: 20px;">
                <h2>Assign Property To Broker</h2>
                <button class="btn btn-sm btn-secondary" onclick="loadPropertyAssignments()">Refresh Assignments</button>
            </div>
            <div class="assign-card" style="margin-top: 0;">
                <div class="assign-grid">
                    <div class="form-group" style="margin:0;">
                        <label for="assignPropertySelect">Property</label>
                        <select id="assignPropertySelect" onchange="handleAssignmentPropertySelection()">
                            <option value="">Select a property</option>
                        </select>
                    </div>
                    <div class="form-group" style="margin:0;">
                        <label for="assignBrokerSelect">Broker</label>
                        <select id="assignBrokerSelect">
                            <option value="0">Unassigned</option>
                        </select>
                    </div>
                    <button class="btn" type="button" onclick="assignPropertyToBroker()">Assign Now</button>
                </div>
                <div class="assign-toolbar">
                    <div class="form-group">
                        <label for="assignStatusFilter">Filter By Work Status</label>
                        <select id="assignStatusFilter" onchange="handleAssignmentFilterChange()">
                            <option value="all">All</option>
                            <option value="working">Currently Working</option>
                            <option value="finished">Finished (Pending + Approved)</option>
                            <option value="finished_pending_admin">Finished - Pending Admin</option>
                            <option value="finished_approved">Finished - Approved</option>
                            <option value="assigned">Assigned (Not Confirmed)</option>
                            <option value="unassigned">Unassigned</option>
                        </select>
                    </div>
                </div>
                <div id="assignmentCurrentInfo" class="assign-current">Current assignment: -</div>
                <div class="assign-hint">This section auto-refreshes every 5 seconds for real-time updates.</div>
                <div id="assignmentTableWrap" class="assign-table" style="margin-top:10px;">
                    <div style="padding: 14px; color:#6b7280;">Loading assignment data...</div>
                </div>
            </div>
        </div>

        <div class="panel" id="feedbackPanel" style="display: none;">
            <div style="display:flex; justify-content: space-between; align-items:center; margin-bottom: 20px;">
                <h2>Customer Reviews - Approval Workflow</h2>
                <button class="btn btn-sm btn-secondary" onclick="loadPendingReviews()"><i class="fas fa-sync"></i> Refresh</button>
            </div>

            <!-- Filter Tabs -->
            <div style="display: flex; gap: 10px; margin-bottom: 20px; border-bottom: 2px solid #e0e0e0; padding-bottom: 15px;">
                <button class="filter-btn active" onclick="filterReviews('pending')" style="padding: 8px 16px; border: none; background: none; color: #667eea; font-weight: 600; cursor: pointer; border-bottom: 3px solid #667eea;">
                    <i class="fas fa-hourglass-half"></i> Pending (<span id="pendingCount">0</span>)
                </button>
                <button class="filter-btn" onclick="filterReviews('approved')" style="padding: 8px 16px; border: none; background: none; color: #999; font-weight: 600; cursor: pointer;">
                    <i class="fas fa-check-circle"></i> Approved (<span id="approvedCount">0</span>)
                </button>
                <button class="filter-btn" onclick="filterReviews('rejected')" style="padding: 8px 16px; border: none; background: none; color: #999; font-weight: 600; cursor: pointer;">
                    <i class="fas fa-times-circle"></i> Rejected (<span id="rejectedCount">0</span>)
                </button>
                <button class="filter-btn" onclick="filterReviews('all')" style="padding: 8px 16px; border: none; background: none; color: #999; font-weight: 600; cursor: pointer;">
                    <i class="fas fa-list"></i> All Reviews
                </button>
            </div>

            <!-- Reviews List -->
            <div id="feedbackContent">
                <div style="text-align: center; padding: 40px; color:#6b7280;">
                    <i class="fas fa-spinner fa-spin" style="font-size: 24px; margin-bottom: 10px; display: block;"></i>
                    Loading reviews...
                </div>
            </div>
        </div>

        <!-- Services Management Panel -->
        <div class="panel" id="servicesPanel" style="display: none;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h2> Services Management</h2>
                <button class="btn" onclick="openAddServiceModal()">+ Add New Service</button>
            </div>

            <div id="addServiceForm" class="modal">
                <div class="service-modal-dialog">
                    <h3 id="serviceFormTitle" style="margin-bottom: 20px;">Add New Service</h3>
                    <div class="service-form-grid">
                        <div class="form-group">
                            <label>Service Title *</label>
                            <input type="text" id="serviceTitle" placeholder="e.g., Property Management" required>
                        </div>
                        <div class="form-group">
                            <label>Status</label>
                            <select id="serviceStatus">
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Icon Class (FontAwesome)</label>
                            <input type="text" id="serviceIcon" placeholder="e.g., fas fa-home" value="fas fa-cogs">
                        </div>
                        <div class="form-group">
                            <label>Price</label>
                            <input type="number" id="servicePrice" placeholder="0.00" step="0.01" min="0">
                        </div>
                        <div class="form-group full-row">
                            <label>Description</label>
                            <textarea id="serviceDescription" placeholder="Service description" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-family: inherit;" rows="5"></textarea>
                        </div>
                    </div>
                    <div style="display: flex; gap: 10px; margin-top: 6px;">
                        <button type="button" class="btn" onclick="saveService()">Save Service</button>
                        <button type="button" class="btn btn-secondary" onclick="closeAddServiceModal()">Cancel</button>
                    </div>
                </div>
            </div>

            <div id="servicesContent">
                <div style="text-align: center; padding: 40px;">
                    <div class="spinner"></div>
                    <p>Loading services...</p>
                </div>
            </div>
        </div>

        <!-- Analytics Panel -->
        <div class="panel" id="analyticsPanel" style="display: none;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h2>Website Analytics</h2>
                <a class="btn btn-secondary" href="?section=analytics">Refresh</a>
            </div>

            <div class="analytics-grid">
                <div class="analytics-card">
                    <h4>Total Inquiries</h4>
                    <p class="value"><?php echo number_format($analytics['total_inquiries']); ?></p>
                </div>
                <div class="analytics-card">
                    <h4>Open Inquiries</h4>
                    <p class="value"><?php echo number_format($analytics['open_inquiries']); ?></p>
                </div>
                <div class="analytics-card">
                    <h4>Total Appointments</h4>
                    <p class="value"><?php echo number_format($analytics['total_appointments']); ?></p>
                </div>
                <div class="analytics-card">
                    <h4>Scheduled Visits</h4>
                    <p class="value"><?php echo number_format($analytics['scheduled_visits']); ?></p>
                </div>
                <div class="analytics-card">
                    <h4>Completed Visits</h4>
                    <p class="value"><?php echo number_format($analytics['completed_visits']); ?></p>
                </div>
                <div class="analytics-card">
                    <h4>Finished Properties</h4>
                    <p class="value"><?php echo number_format($analytics['finished_properties']); ?></p>
                </div>
                <div class="analytics-card">
                    <h4>Listed Properties</h4>
                    <p class="value"><?php echo number_format($analytics['listed_properties']); ?></p>
                </div>
                <div class="analytics-card">
                    <h4>Properties With Activity</h4>
                    <p class="value"><?php echo number_format($analytics['properties_with_activity']); ?></p>
                </div>
                <div class="analytics-card">
                    <h4>Broker Pending Properties</h4>
                    <p class="value" id="analyticsBrokerPending"><?php echo number_format($analytics['broker_pending_properties']); ?></p>
                </div>
                <div class="analytics-card">
                    <h4>Broker Approval Pending</h4>
                    <p class="value" id="analyticsBrokerApprovalPending"><?php echo number_format($analytics['broker_approval_pending_properties']); ?></p>
                </div>
                <div class="analytics-card">
                    <h4>Broker Finished Properties</h4>
                    <p class="value" id="analyticsBrokerFinished"><?php echo number_format($analytics['broker_finished_properties']); ?></p>
                </div>
            </div>

            <?php
                $status_total = array_sum($property_status_breakdown);
                $active_deg = $status_total > 0 ? round(($property_status_breakdown['active'] / $status_total) * 360, 2) : 0;
                $inactive_deg = $status_total > 0 ? round(($property_status_breakdown['inactive'] / $status_total) * 360, 2) : 0;
                $sold_deg = $status_total > 0 ? round(($property_status_breakdown['sold'] / $status_total) * 360, 2) : 0;
                $slice_active = $active_deg;
                $slice_inactive = $active_deg + $inactive_deg;
                $slice_sold = $active_deg + $inactive_deg + $sold_deg;
            ?>

            <div class="analytics-charts-grid">
                <div class="chart-card">
                    <div class="chart-title">6-Month Trend: Inquiries vs Appointments</div>
                    <canvas id="trendChartCanvas" class="trend-chart-canvas"></canvas>
                    <div class="chart-legend">
                        <span><span class="legend-dot" style="background:#667eea;"></span>Inquiries</span>
                        <span><span class="legend-dot" style="background:#17a2b8;"></span>Appointments</span>
                    </div>
                </div>

                <div class="chart-card">
                    <div class="chart-title">Property Status Breakdown</div>
                    <div class="donut-wrap">
                        <div
                            class="donut-chart"
                            style="--slice-active: <?php echo $slice_active; ?>deg; --slice-inactive: <?php echo $slice_inactive; ?>deg; --slice-sold: <?php echo $slice_sold; ?>deg;"
                        ></div>
                        <div class="donut-labels">
                            <div><span class="legend-dot" style="background:#28a745;"></span>Active: <?php echo intval($property_status_breakdown['active']); ?></div>
                            <div><span class="legend-dot" style="background:#ffc107;"></span>Inactive: <?php echo intval($property_status_breakdown['inactive']); ?></div>
                            <div><span class="legend-dot" style="background:#dc3545;"></span>Sold: <?php echo intval($property_status_breakdown['sold']); ?></div>
                            <div><span class="legend-dot" style="background:#6c757d;"></span>Other: <?php echo intval($property_status_breakdown['other']); ?></div>
                        </div>
                    </div>
                </div>
            </div>

            <h3 class="analytics-section-title">Appointments & Property Listing Analytics</h3>
            <div class="mini-charts-grid">
                <div class="chart-card">
                    <div class="chart-title">Appointments Status Distribution</div>
                    <canvas id="appointmentStatusCanvas" class="mini-chart-canvas"></canvas>
                </div>
                <div class="chart-card">
                    <div class="chart-title">Property Listings (Last 6 Months)</div>
                    <canvas id="propertyListingTrendCanvas" class="mini-chart-canvas"></canvas>
                </div>
                <div class="chart-card">
                    <div class="chart-title">Top Listing Cities</div>
                    <canvas id="topListingCitiesCanvas" class="mini-chart-canvas"></canvas>
                </div>
                <div class="chart-card">
                    <div class="chart-title">Broker Property Workflow</div>
                    <canvas id="brokerWorkflowCanvas" class="mini-chart-canvas"></canvas>
                </div>
            </div>

            <h3 class="analytics-section-title">Recent Inquiries</h3>
            <?php if (count($recent_inquiries) > 0): ?>
                <div class="analytics-table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Property</th>
                                <th>Status</th>
                                <th>Message</th>
                                <th>Date</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($recent_inquiries as $inquiry): ?>
                                <tr>
                                    <td>#<?php echo intval($inquiry['id']); ?></td>
                                    <td><?php echo htmlspecialchars($inquiry['property_title']); ?></td>
                                    <td><?php echo htmlspecialchars(ucfirst($inquiry['inquiry_status'])); ?></td>
                                    <td><?php echo htmlspecialchars($inquiry['inquiry_message']); ?></td>
                                    <td><?php echo !empty($inquiry['created_at']) ? date('M d, Y H:i', strtotime($inquiry['created_at'])) : 'N/A'; ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="analytics-empty">No inquiry data found.</div>
            <?php endif; ?>

            <h3 class="analytics-section-title">Recent Appointments / Schedule Visits</h3>
            <?php if (count($recent_appointments) > 0): ?>
                <div class="analytics-table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Property</th>
                                <th>Status</th>
                                <th>Visit Date</th>
                                <th>Visit Time</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($recent_appointments as $appointment): ?>
                                <tr>
                                    <td>#<?php echo intval($appointment['id']); ?></td>
                                    <td><?php echo htmlspecialchars($appointment['property_title']); ?></td>
                                    <td><?php echo htmlspecialchars(ucfirst($appointment['appointment_status'])); ?></td>
                                    <td><?php echo !empty($appointment['appointment_date']) ? date('M d, Y', strtotime($appointment['appointment_date'])) : 'N/A'; ?></td>
                                    <td><?php echo !empty($appointment['appointment_time']) ? date('h:i A', strtotime($appointment['appointment_time'])) : 'N/A'; ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="analytics-empty">No appointment data found.</div>
            <?php endif; ?>

            <h3 class="analytics-section-title">Property Activity List</h3>
            <?php if (count($property_activity) > 0): ?>
                <div class="analytics-table-wrap">
                    <table>
                        <thead>
                            <tr>
                                <th>Property</th>
                                <th>City</th>
                                <th>Status</th>
                                <th>Inquiries</th>
                                <th>Visits</th>
                                <th>Completed Visits</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($property_activity as $property): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($property['title']); ?></td>
                                    <td><?php echo htmlspecialchars($property['city'] ?? 'N/A'); ?></td>
                                    <td><?php echo htmlspecialchars(ucfirst($property['property_status'])); ?></td>
                                    <td><?php echo intval($property['inquiry_count']); ?></td>
                                    <td><?php echo intval($property['visit_count']); ?></td>
                                    <td><?php echo intval($property['completed_visit_count']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="analytics-empty">No property activity data found.</div>
            <?php endif; ?>
        </div>

        <!-- Settings Panel -->
        <div class="panel" id="settingsPanel" style="display: none;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h2>Real Estate Settings</h2>
            </div>

            <form method="POST" action="?action=save_settings&section=settings">
                <div class="settings-grid">
                    <div class="settings-card">
                        <h3>Company Information</h3>
                        <div class="form-group">
                            <label>Company Name</label>
                            <input type="text" name="company_name" value="<?php echo htmlspecialchars($settings['company_name']); ?>" required>
                        </div>
                        <div class="form-group">
                            <label>Company Email</label>
                            <input type="email" name="company_email" value="<?php echo htmlspecialchars($settings['company_email']); ?>" required>
                        </div>
                        <div class="form-group">
                            <label>Company Phone</label>
                            <input type="text" name="company_phone" value="<?php echo htmlspecialchars($settings['company_phone']); ?>" required>
                        </div>
                        <div class="form-group">
                            <label>Office Address</label>
                            <input type="text" name="company_address" value="<?php echo htmlspecialchars($settings['company_address']); ?>">
                        </div>
                    </div>

                    <div class="settings-card">
                        <h3>Listing Defaults</h3>
                        <div class="form-group">
                            <label>Default Currency</label>
                            <select name="default_currency">
                                <option value="USD" <?php echo $settings['default_currency'] === 'USD' ? 'selected' : ''; ?>>USD</option>
                                <option value="EUR" <?php echo $settings['default_currency'] === 'EUR' ? 'selected' : ''; ?>>EUR</option>
                                <option value="GBP" <?php echo $settings['default_currency'] === 'GBP' ? 'selected' : ''; ?>>GBP</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Default City</label>
                            <input type="text" name="default_city" value="<?php echo htmlspecialchars($settings['default_city']); ?>">
                        </div>
                        <div class="form-group">
                            <label>Default Commission (%)</label>
                            <input type="number" name="default_commission_percent" min="0" step="0.01" value="<?php echo htmlspecialchars($settings['default_commission_percent']); ?>">
                        </div>
                        <div class="form-group">
                            <label>Default Property Status</label>
                            <select name="default_property_status">
                                <option value="active" <?php echo $settings['default_property_status'] === 'active' ? 'selected' : ''; ?>>Active</option>
                                <option value="inactive" <?php echo $settings['default_property_status'] === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                                <option value="sold" <?php echo $settings['default_property_status'] === 'sold' ? 'selected' : ''; ?>>Sold</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label style="display: flex; align-items: center; gap: 8px;">
                                <input type="checkbox" name="allow_public_inquiries" value="1" <?php echo $settings['allow_public_inquiries'] === '1' ? 'checked' : ''; ?> style="width: auto;">
                                Allow Public Inquiries
                            </label>
                        </div>
                    </div>
                </div>

                <div class="settings-actions">
                    <button type="submit" class="btn">Save Settings</button>
                    <a href="../api/download-database.php" class="btn btn-secondary">Download Database (.sql)</a>
                </div>
            </form>
        </div>

        <!-- Hero Slider Management Panel -->
        <div class="panel" id="heroSliderPanel" style="display: none;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h2>Hero Slider Management</h2>
                <button type="button" class="btn" onclick="openHeroSliderModal()">
                    <i class="fas fa-plus"></i> Add New Slider
                </button>
            </div>

            <!-- Hero Slider List -->
            <div id="heroSliderList" class="hero-slider-list">
                <!-- Will be populated by JavaScript -->
            </div>

            <!-- Hero Slider Modal -->
            <div id="heroSliderModal" class="modal" style="display: none;">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3 id="heroSliderModalTitle">Add Hero Slider</h3>
                        <button type="button" class="modal-close" onclick="closeHeroSliderModal()">×</button>
                    </div>
                    <div class="modal-body">
                                                <form id="heroSliderForm">
                            <input type="hidden" id="heroSliderId">

                            <div class="hero-slider-form-grid">
                                <div class="form-group full-row">
                                    <label>Tag / Category</label>
                                    <input type="text" id="heroSliderTag" placeholder="e.g., Premium Properties" required>
                                </div>

                                <div class="form-group full-row">
                                    <label>Main Title</label>
                                    <input type="text" id="heroSliderTitle" placeholder="e.g., Find Your Dream Apartment" required>
                                </div>

                                <div class="form-group full-row">
                                    <label>Subtitle / Description</label>
                                    <textarea id="heroSliderSubtitle" rows="3" placeholder="Detailed description..." required></textarea>
                                </div>

                                <div class="form-group">
                                    <label>Button 1 Text</label>
                                    <input type="text" id="heroSliderButton1Text" placeholder="e.g., Explore">
                                </div>
                                <div class="form-group">
                                    <label>Button 1 Page</label>
                                    <select id="heroSliderButton1Url" onchange="handleHeroUrlSelectChange('heroSliderButton1Url','heroSliderButton1Custom')">
                                        <option value="">Select page</option>
                                        <option value="about.php">about.php</option>
                                        <option value="properties.php">properties.php</option>
                                        <option value="service.php">service.php</option>
                                        <option value="contact.php">contact.php</option>
                                        <option value="appointment.php">appointment.php</option>
                                        <option value="__custom__">Custom URL</option>
                                    </select>
                                    <input type="text" id="heroSliderButton1Custom" class="hero-url-custom" placeholder="Custom URL">
                                </div>

                                <div class="form-group">
                                    <label>Button 2 Text</label>
                                    <input type="text" id="heroSliderButton2Text" placeholder="e.g., Contact">
                                </div>
                                <div class="form-group">
                                    <label>Button 2 Page</label>
                                    <select id="heroSliderButton2Url" onchange="handleHeroUrlSelectChange('heroSliderButton2Url','heroSliderButton2Custom')">
                                        <option value="">Select page</option>
                                        <option value="about.php">about.php</option>
                                        <option value="properties.php">properties.php</option>
                                        <option value="service.php">service.php</option>
                                        <option value="contact.php">contact.php</option>
                                        <option value="appointment.php">appointment.php</option>
                                        <option value="__custom__">Custom URL</option>
                                    </select>
                                    <input type="text" id="heroSliderButton2Custom" class="hero-url-custom" placeholder="Custom URL">
                                </div>

                                <div class="form-group full-row">
                                    <label>Background Image</label>
                                    <div class="image-upload-box">
                                        <input type="file" id="heroSliderImageFile" accept="image/*" onchange="previewHeroSliderImage(event)">
                                        <div class="helper-text">Upload JPG, PNG, WEBP, or GIF image (max 5MB).</div>
                                        <img id="heroSliderImagePreview" class="image-preview" alt="Hero slider preview">
                                    </div>
                                </div>

                                <div class="form-group full-row">
                                    <label>Background Image URL / Path</label>
                                    <input type="text" id="heroSliderImageUrl" placeholder="e.g., assets/img/hero/uploads/hero_20260219_ab12cd34.jpg">
                                    <div class="helper-text">This value is auto-filled after upload, or you can paste an existing path.</div>
                                </div>

                                <div class="form-group">
                                    <label>Stat 1 Icon</label>
                                    <input type="text" id="heroSliderStat1Icon" placeholder="fas fa-check-circle">
                                </div>
                                <div class="form-group">
                                    <label>Stat 1 Text</label>
                                    <input type="text" id="heroSliderStat1Text" placeholder="e.g., 22K+ Properties">
                                </div>

                                <div class="form-group">
                                    <label>Stat 2 Icon</label>
                                    <input type="text" id="heroSliderStat2Icon" placeholder="fas fa-users">
                                </div>
                                <div class="form-group">
                                    <label>Stat 2 Text</label>
                                    <input type="text" id="heroSliderStat2Text" placeholder="e.g., 140K+ Customers">
                                </div>

                                <div class="form-group">
                                    <label>Display Order</label>
                                    <input type="number" id="heroSliderDisplayOrder" value="1" min="1">
                                </div>
                                <div class="form-group">
                                    <label>Status</label>
                                    <select id="heroSliderStatus">
                                        <option value="active">Active</option>
                                        <option value="inactive">Inactive</option>
                                    </select>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" onclick="closeHeroSliderModal()">Cancel</button>
                        <button type="button" class="btn" onclick="saveHeroSlider()">Save Slider</button>
                    </div>
                </div>
            </div>

            <!-- Modal Overlay -->
            <div id="heroSliderModalOverlay" class="modal-overlay" onclick="closeHeroSliderModal()" style="display: none;"></div>
        </div>

    </div>

    <div id="approvalDetailsModal" class="approval-details-modal" onclick="closeApprovalDetailsModal(event)">
        <div class="approval-details-dialog">
            <div class="approval-details-header">
                <h3 id="approvalDetailsTitle" class="approval-details-title">Details</h3>
                <button type="button" class="approval-details-close" onclick="closeApprovalDetailsModal()">Close</button>
            </div>
            <div id="approvalDetailsBody"></div>
        </div>
    </div>

    <script>
        let currentSection = new URLSearchParams(window.location.search).get('section') || 'overview';
        const trendLabels = <?php echo json_encode($trend_labels); ?>;
        const trendInquiries = <?php echo json_encode($trend_inquiries); ?>;
        const trendAppointments = <?php echo json_encode($trend_appointments); ?>;
        const brokerOptions = <?php echo json_encode($broker_options); ?>;
        const appointmentStatusLabels = <?php echo json_encode($appointment_status_labels); ?>;
        const appointmentStatusCounts = <?php echo json_encode($appointment_status_counts); ?>;
        const propertyListingTrendLabels = <?php echo json_encode($listing_trend_labels); ?>;
        const propertyListingTrendCounts = <?php echo json_encode($listing_trend_counts); ?>;
        const topListingCityLabels = <?php echo json_encode($listing_city_labels); ?>;
        const topListingCityCounts = <?php echo json_encode($listing_city_counts); ?>;
        let brokerWorkflowCounts = [
            <?php echo intval($analytics['broker_pending_properties']); ?>,
            <?php echo intval($analytics['broker_approval_pending_properties']); ?>,
            <?php echo intval($analytics['broker_finished_properties']); ?>
        ];
        let analyticsChartRendered = false;

        function renderTrendChart() {
            const canvas = document.getElementById('trendChartCanvas');
            if (!canvas) return;

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

            const ctx = canvas.getContext('2d');
            if (!ctx) return;

            ctx.clearRect(0, 0, width, height);

            const maxDataValue = Math.max(1, ...trendInquiries, ...trendAppointments);
            const chartPadding = { top: 20, right: 20, bottom: 35, left: 35 };
            const chartWidth = width - chartPadding.left - chartPadding.right;
            const chartHeight = height - chartPadding.top - chartPadding.bottom;
            const xStep = trendLabels.length > 1 ? chartWidth / (trendLabels.length - 1) : chartWidth;

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

            // Axes
            ctx.strokeStyle = '#ced4da';
            ctx.beginPath();
            ctx.moveTo(chartPadding.left, chartPadding.top);
            ctx.lineTo(chartPadding.left, chartPadding.top + chartHeight);
            ctx.lineTo(chartPadding.left + chartWidth, chartPadding.top + chartHeight);
            ctx.stroke();

            function drawLine(data, color) {
                ctx.strokeStyle = color;
                ctx.lineWidth = 2;
                ctx.beginPath();
                data.forEach((value, index) => {
                    const x = chartPadding.left + xStep * index;
                    const y = chartPadding.top + chartHeight - (value / maxDataValue) * chartHeight;
                    if (index === 0) ctx.moveTo(x, y);
                    else ctx.lineTo(x, y);
                });
                ctx.stroke();

                ctx.fillStyle = color;
                data.forEach((value, index) => {
                    const x = chartPadding.left + xStep * index;
                    const y = chartPadding.top + chartHeight - (value / maxDataValue) * chartHeight;
                    ctx.beginPath();
                    ctx.arc(x, y, 3, 0, Math.PI * 2);
                    ctx.fill();
                });
            }

            drawLine(trendInquiries, '#667eea');
            drawLine(trendAppointments, '#17a2b8');

            // X-axis labels
            ctx.fillStyle = '#6c757d';
            ctx.font = '11px Poppins';
            ctx.textAlign = 'center';
            trendLabels.forEach((label, index) => {
                const x = chartPadding.left + xStep * index;
                ctx.fillText(label.split(' ')[0], x, height - 12);
            });
        }

        function drawBarChart(canvasId, labels, data, color) {
            const canvas = document.getElementById(canvasId);
            if (!canvas) return;

            const width = canvas.clientWidth || 360;
            const height = canvas.clientHeight || 210;
            canvas.width = width;
            canvas.height = height;

            const ctx = canvas.getContext('2d');
            if (!ctx) return;

            ctx.clearRect(0, 0, width, height);

            const cleanLabels = Array.isArray(labels) ? labels : [];
            const cleanData = Array.isArray(data) ? data : [];
            const count = Math.max(1, cleanLabels.length, cleanData.length);
            const maxValue = Math.max(1, ...cleanData, 1);

            const padding = { top: 18, right: 12, bottom: 40, left: 28 };
            const chartWidth = width - padding.left - padding.right;
            const chartHeight = height - padding.top - padding.bottom;
            const barGap = 8;
            const barWidth = Math.max(8, (chartWidth - (count - 1) * barGap) / count);

            // Grid
            ctx.strokeStyle = '#e9ecef';
            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();
            }

            // Bars
            for (let i = 0; i < count; i++) {
                const value = cleanData[i] || 0;
                const x = padding.left + i * (barWidth + barGap);
                const h = (value / maxValue) * chartHeight;
                const y = padding.top + chartHeight - h;

                ctx.fillStyle = color;
                ctx.fillRect(x, y, barWidth, h);

                ctx.fillStyle = '#495057';
                ctx.font = '10px Poppins';
                ctx.textAlign = 'center';
                const label = (cleanLabels[i] || '').toString();
                ctx.fillText(label.length > 8 ? label.slice(0, 8) + '.' : label, x + barWidth / 2, height - 18);
            }
        }

        function drawResponsiveAppointmentStatusChart() {
            const canvas = document.getElementById('appointmentStatusCanvas');
            if (!canvas) return;

            // Keep only statuses that have data for better readability.
            const filtered = appointmentStatusLabels
                .map((label, index) => ({ label, value: Number(appointmentStatusCounts[index] || 0) }))
                .filter(item => item.value > 0);

            const labels = filtered.length ? filtered.map(item => item.label) : ['No Data'];
            const values = filtered.length ? filtered.map(item => item.value) : [0];

            const width = canvas.clientWidth || 360;
            const useHorizontal = width <= 520 || labels.length > 5;

            if (!useHorizontal) {
                canvas.style.height = '210px';
                drawBarChart('appointmentStatusCanvas', labels, values, '#5a67d8');
                return;
            }

            // Horizontal layout for small screens / many categories.
            const rowHeight = 26;
            const minHeight = 210;
            const dynamicHeight = Math.max(minHeight, labels.length * rowHeight + 60);
            canvas.style.height = dynamicHeight + 'px';
            canvas.width = width;
            canvas.height = dynamicHeight;

            const ctx = canvas.getContext('2d');
            if (!ctx) return;

            ctx.clearRect(0, 0, width, dynamicHeight);

            const maxValue = Math.max(1, ...values);
            const padding = { top: 18, right: 18, bottom: 18, left: 105 };
            const chartWidth = width - padding.left - padding.right;

            // Subtle horizontal guides.
            ctx.strokeStyle = '#eef1f4';
            ctx.lineWidth = 1;
            for (let i = 0; i <= 4; i++) {
                const x = padding.left + (chartWidth * i / 4);
                ctx.beginPath();
                ctx.moveTo(x, padding.top);
                ctx.lineTo(x, dynamicHeight - padding.bottom);
                ctx.stroke();
            }

            values.forEach((value, index) => {
                const y = padding.top + index * rowHeight;
                const barHeight = 16;
                const barWidth = (value / maxValue) * chartWidth;

                ctx.fillStyle = '#5a67d8';
                ctx.fillRect(padding.left, y, barWidth, barHeight);

                ctx.fillStyle = '#495057';
                ctx.font = '11px Poppins';
                ctx.textAlign = 'right';
                const label = labels[index].length > 14 ? labels[index].slice(0, 14) + '.' : labels[index];
                ctx.fillText(label, padding.left - 8, y + 12);

                ctx.textAlign = 'left';
                ctx.fillText(String(value), padding.left + barWidth + 6, y + 12);
            });
        }

        function renderAnalyticsCharts() {
            renderTrendChart();
            drawResponsiveAppointmentStatusChart();
            drawBarChart('propertyListingTrendCanvas', propertyListingTrendLabels.map(label => label.split(' ')[0]), propertyListingTrendCounts, '#17a2b8');
            drawBarChart('topListingCitiesCanvas', topListingCityLabels, topListingCityCounts, '#28a745');
            drawBarChart('brokerWorkflowCanvas', ['Pending', 'Approval', 'Finished'], brokerWorkflowCounts, '#f59e0b');
        }
        
        // Tab Navigation
        document.addEventListener('DOMContentLoaded', function() {
            activateSection(currentSection);
            
            // Setup section links
            document.querySelectorAll('.sidebar-menu a').forEach(link => {
                link.addEventListener('click', function(e) {
                    const section = this.href.split('section=')[1];
                    if (section) {
                        e.preventDefault();
                        window.history.pushState({}, '', '?section=' + section);
                        activateSection(section);
                    }
                });
            });

            const propertyImageFile = document.getElementById('propertyImageFile');
            if (propertyImageFile) {
                propertyImageFile.addEventListener('change', function() {
                    if (this.files && this.files[0]) {
                        const fileUrl = URL.createObjectURL(this.files[0]);
                        const preview = document.getElementById('propertyImagePreview');
                        preview.src = fileUrl;
                        preview.style.display = 'block';
                    }
                });
            }

            const propertyImageUrl = document.getElementById('propertyImageUrl');
            if (propertyImageUrl) {
                propertyImageUrl.addEventListener('input', function() {
                    if (!document.getElementById('propertyImageFile').files.length) {
                        setPropertyPreview(this.value.trim());
                    }
                });
            }

            const addPropertyForm = document.getElementById('addPropertyForm');
            if (addPropertyForm) {
                addPropertyForm.addEventListener('click', function(e) {
                    if (e.target === addPropertyForm) {
                        closeAddPropertyModal();
                    }
                });
            }

            const addServiceForm = document.getElementById('addServiceForm');
            if (addServiceForm) {
                addServiceForm.addEventListener('click', function(e) {
                    if (e.target === addServiceForm) {
                        closeAddServiceModal();
                    }
                });
            }

            const editUserForm = document.getElementById('editUserForm');
            if (editUserForm) {
                editUserForm.addEventListener('click', function(e) {
                    if (e.target === editUserForm) {
                        hideEditUserForm();
                    }
                });
            }
        });

        function activateSection(section) {
            currentSection = section || 'overview';

            // Hide all panels
            document.querySelectorAll('.panel').forEach(panel => panel.style.display = 'none');
            document.querySelectorAll('.stat-card').forEach(card => card.style.display = 'none');
            
            // Update sidebar
            document.querySelectorAll('.sidebar-menu a').forEach(link => link.classList.remove('active'));
            const activeLink = document.querySelector(`.sidebar-menu a[href="?section=${section}"]`);
            if (activeLink) activeLink.classList.add('active');
            
            switch(section) {
                case 'users':
                    document.getElementById('usersPanel').style.display = 'block';
                    break;
                case 'customers':
                    document.getElementById('customersPanel').style.display = 'block';
                    break;
                case 'brokers':
                    document.getElementById('brokersPanel').style.display = 'block';
                    break;
                case 'staff':
                    document.getElementById('staffPanel').style.display = 'block';
                    break;
                case 'properties':
                    document.getElementById('propertiesPanel').style.display = 'block';
                    loadProperties();
                    loadPropertyApprovals();
                    loadDocumentApprovals();
                    break;
                case 'assignments':
                    document.getElementById('assignmentsPanel').style.display = 'block';
                    loadPropertyAssignments();
                    break;
                case 'feedback':
                    document.getElementById('feedbackPanel').style.display = 'block';
                    loadCustomerFeedback();
                    break;
                case 'services':
                    document.getElementById('servicesPanel').style.display = 'block';
                    loadServices();
                    break;
                case 'heroSliderPanel':
                    document.getElementById('heroSliderPanel').style.display = 'block';
                    loadHeroSliders();
                    break;
                case 'analytics':
                    document.getElementById('analyticsPanel').style.display = 'block';
                    if (!analyticsChartRendered) {
                        renderAnalyticsCharts();
                        analyticsChartRendered = true;
                    }
                    break;
                case 'settings':
                    document.getElementById('settingsPanel').style.display = 'block';
                    break;
                case 'overview':
                default:
                    document.getElementById('overviewPanel').style.display = 'block';
                    document.querySelectorAll('.stat-card').forEach(card => card.style.display = 'block');
            }
        }

        // Properties Management
        let currentPropertyPage = 1;
        let totalPropertyPages = 1;
        let editingPropertyId = null;
        let pendingPropertyApprovals = [];
        let pendingDocumentApprovals = [];
        let propertyAssignmentCache = [];
        let brokerAssignmentCache = [];
        let assignmentStatusFilter = 'all';
        const propertyApprovalPriceDrafts = {};

        async function loadProperties(page = 1) {
            try {
                const response = await fetch(`../api/get-properties.php?page=${page}&per_page=10`);
                const data = await response.json();
                
                console.log('Properties API response:', data);
                
                if (data.success && data.properties && Array.isArray(data.properties)) {
                    renderProperties(data.properties, data.page, data.total_pages);
                    currentPropertyPage = page;
                    totalPropertyPages = data.total_pages;
                } else if (!data.success) {
                    console.error('API error:', data.message || 'Unknown error');
                    document.getElementById('propertiesContent').innerHTML = `<p style="color: red;">Error: ${data.message || 'Failed to load properties'}</p>`;
                } else {
                    console.error('Invalid response format:', data);
                    document.getElementById('propertiesContent').innerHTML = '<p>Invalid data format received</p>';
                }
            } catch (error) {
                console.error('Error loading properties:', error);
                document.getElementById('propertiesContent').innerHTML = `<p style="color: red;">Error: ${error.message}</p>`;
            }
        }

        function renderProperties(properties, page, totalPages) {
            let html = '<div class="property-grid">';
            
            if (properties.length === 0) {
                html = '<p style="grid-column: 1/-1; text-align: center; padding: 40px;">No properties found.</p>';
            } else {
                properties.forEach(prop => {
                    const isAbsoluteImage = prop.image_url && /^https?:\/\//i.test(prop.image_url);
                    const imageUrl = prop.image_url
                        ? (isAbsoluteImage ? prop.image_url : '../' + String(prop.image_url).replace(/^\/+/, ''))
                        : 'https://via.placeholder.com/400x300?text=No+Image';

                    const placeholder = !prop.image_url;
                    html += `
                        <div class="property-card">
                            ${placeholder ? 
                                `<div class="property-image-placeholder"><i class="fas fa-home"></i></div>` :
                                `<img src="${imageUrl}" 
                                    alt="${prop.title}" 
                                    class="property-image"
                                    onerror="this.src='https://via.placeholder.com/400x300?text=No+Image'">`
                            }
                            <div class="card-header">
                                <div class="card-title">${prop.title}</div>
                                <span style="font-size: 11px; background: #667eea; color: white; padding: 4px 8px; border-radius: 3px; text-transform: uppercase;">${prop.type}</span>
                            </div>
                            <div class="card-meta"> ${prop.address}, ${prop.city}</div>
                            <div class="card-meta"><strong> $${Number(prop.price).toLocaleString()}</strong></div>
                            <div class="card-meta"> ${prop.bedrooms} Beds |  ${prop.bathrooms} Baths</div>
                            <div class="card-meta">Broker: ${escapeAdminHtml(prop.broker_name || 'Unassigned')}</div>
                            <div style="margin: 12px 0; padding: 8px; background: #f8f9fa; border-radius: 5px; display: inline-block;">
                                <span class="status-badge status-${prop.status}">${prop.status.toUpperCase()}</span>
                            </div>
                            <div class="card-actions">
                                <button class="btn-edit" onclick="editProperty(${prop.id})"><i class="fas fa-edit"></i> Edit</button>
                                <button class="btn-delete" onclick="deleteProperty(${prop.id})"><i class="fas fa-trash"></i> Delete</button>
                            </div>
                        </div>
                    `;
                });
            }
            
            html += '</div>';
            
            // Add pagination
            if (totalPages > 1) {
                html += '<div class="pagination">';
                for (let i = 1; i <= totalPages; i++) {
                    html += `<button class="pagination-btn ${i === page ? 'active' : ''}" onclick="loadProperties(${i})">${i}</button>`;
                }
                html += '</div>';
            }
            
            document.getElementById('propertiesContent').innerHTML = html;
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            let html = '<table><thead><tr><th>ID</th><th>Image</th><th>Property</th><th>Location</th><th>Listing Status</th><th>Work Status</th><th>Current Broker</th><th>Admin Action</th></tr></thead><tbody>';
            properties.forEach((prop) => {
                const workflowStatus = normalizeAssignmentStatus(prop.assignment_status);
                const reviewStatus = normalizeAssignmentStatus(prop.assignment_review_status);
                const canApprove = workflowStatus === 'finished_pending_admin';
                const reviewText = canApprove ? 'Waiting for admin review' : `Review: ${getAssignmentStatusLabel(reviewStatus)}`;
                const imageUrl = normalizeDashboardImagePath(prop.image_url || '');
                const imageCell = imageUrl
                    ? `<img src="${escapeAdminHtml(imageUrl)}" alt="Property image" class="assign-thumb" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';"><div class="assign-thumb-fallback" style="display:none;"><i class="fas fa-home"></i></div>`
                    : '<div class="assign-thumb-fallback"><i class="fas fa-home"></i></div>';
                html += `
                    <tr>
                        <td>#${Number(prop.id)}</td>
                        <td>${imageCell}</td>
                        <td>${escapeAdminHtml(prop.title || ('Property #' + prop.id))}</td>
                        <td>${escapeAdminHtml(prop.address || '')}${prop.city ? ', ' + escapeAdminHtml(prop.city) : ''}</td>
                        <td><span class="assign-status">${escapeAdminHtml(prop.status || 'unknown')}</span></td>
                        <td>
                            <span class="assign-status ${escapeAdminHtml(workflowStatus)}">${escapeAdminHtml(getAssignmentStatusLabel(workflowStatus))}</span>
                            <div style="font-size:11px; color:#6b7280; margin-top:6px;">${escapeAdminHtml(reviewText)}</div>
                        </td>
                        <td>${escapeAdminHtml(prop.broker_name || 'Unassigned')}</td>
                        <td>
                            ${canApprove
                                ? `<button class="btn btn-sm" onclick="reviewFinishedAssignment(${Number(prop.id)}, 'approve')">Approve Finish</button>
                                   <button class="btn btn-sm btn-secondary" onclick="reviewFinishedAssignment(${Number(prop.id)}, 'reopen')">Reopen</button>`
                                : '<span style="font-size:12px; color:#6b7280;">No action</span>'}
                        </td>
                    </tr>
                `;
            });
            html += '</tbody></table>';
            tableWrap.innerHTML = html;
        }

        async function reviewFinishedAssignment(propertyId, action) {
            const normalizedAction = action === 'approve' ? 'approve' : 'reopen';
            try {
                const response = await fetch('../api/admin/review-assignment-finish.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) {
                    alert('Error: ' + (data.message || 'Could not review assignment'));
                    return;
                }
                alert(data.message || 'Assignment reviewed');
                await Promise.all([loadPropertyAssignments(), loadProperties(currentPropertyPage)]);
            } catch (error) {
                alert('Error reviewing assignment: ' + error.message);
            }
        }

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

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

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

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

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

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

                alert(data.message || 'Assignment updated');
                await Promise.all([loadPropertyAssignments(), loadProperties(currentPropertyPage)]);
            } catch (error) {
                alert('Error assigning property: ' + error.message);
            }
        }

        let currentReviewFilter = 'pending';

        async function loadPendingReviews() {
            const container = document.getElementById('feedbackContent');
            if (!container) return;

            container.innerHTML = '<div style="text-align: center; padding: 40px;"><i class="fas fa-spinner fa-spin" style="font-size: 24px; margin-bottom: 10px; display: block;"></i>Loading reviews...</div>';

            try {
                const response = await fetch(`../api/reviews-manage.php?action=get-pending&status=${currentReviewFilter}`);
                const data = await response.json();
                
                if (!data.success) {
                    container.innerHTML = `<div style="padding: 20px; color:#b91c1c; text-align: center;">Error: ${escapeAdminHtml(data.message || 'Failed to load reviews')}</div>`;
                    return;
                }

                // Update counts
                if (data.counts) {
                    document.getElementById('pendingCount').textContent = data.counts.pending || 0;
                    document.getElementById('approvedCount').textContent = data.counts.approved || 0;
                    document.getElementById('rejectedCount').textContent = data.counts.rejected || 0;
                }

                const reviews = Array.isArray(data.reviews) ? data.reviews : [];
                if (reviews.length === 0) {
                    container.innerHTML = '<div style="padding: 40px; text-align: center; color:#6b7280;"><i class="fas fa-check-circle" style="font-size: 48px; margin-bottom: 10px; display: block; color: #20c997;"></i>No reviews to display</div>';
                    return;
                }

                let html = '<div style="display: grid; gap: 20px;">';
                reviews.forEach((review) => {
                    const createdAt = review.created_at
                        ? new Date(review.created_at).toLocaleString('en-US', { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })
                        : 'N/A';
                    const rating = Number(review.rating || 0);
                    const stars = rating > 0 ? '★'.repeat(rating) + '☆'.repeat(5 - rating) : '★★★★★';
                    const statusClass = review.status === 'pending' ? 'pending' : review.status === 'approved' ? 'approved' : 'rejected';
                    const statusBgColor = review.status === 'pending' ? '#fef3c7' : review.status === 'approved' ? '#dcfce7' : '#fee2e2';
                    const statusTextColor = review.status === 'pending' ? '#92400e' : review.status === 'approved' ? '#166534' : '#991b1b';

                    html += `
                        <div style="background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 8px; padding: 20px; transition: all 0.3s ease;">
                            <div style="display: flex; flex-wrap: wrap; justify-content: space-between; align-items: start; margin-bottom: 15px; gap: 10px;">
                                <div style="flex: 1; min-width: 200px;">
                                    <h4 style="margin: 0 0 5px 0; color: #1f2937; word-break: break-word;">${escapeAdminHtml(review.customer_name || 'Customer')}</h4>
                                    <p style="margin: 5px 0; font-size: 13px; color: #6b7280;">Submitted: ${escapeAdminHtml(createdAt)}</p>
                                </div>
                                <span style="padding: 6px 12px; border-radius: 20px; background: ${statusBgColor}; color: ${statusTextColor}; font-size: 12px; font-weight: 600; white-space: nowrap;">
                                    ${review.status.charAt(0).toUpperCase() + review.status.slice(1)}
                                </span>
                            </div>
                            <div style="margin-bottom: 15px; color: #f39c12; font-size: 16px; letter-spacing: 2px;">${stars}</div>
                            <div style="background: white; padding: 12px; border-radius: 5px; margin-bottom: 15px; color: #374151; line-height: 1.6; border-left: 3px solid #667eea; word-break: break-word;">
                                "${escapeAdminHtml(review.comment)}"
                            </div>
                            ${review.status === 'pending' ? `
                                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; grid-auto-flow: row;">
                                    <button onclick="approveReview(${review.id})" style="padding: 10px; background: #10b981; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: 600; transition: all 0.3s; display: flex; align-items: center; justify-content: center; gap: 6px; font-size: 14px;">
                                        <i class="fas fa-check"></i> <span>Approve</span>
                                    </button>
                                    <button onclick="rejectReview(${review.id})" style="padding: 10px; background: #ef4444; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: 600; transition: all 0.3s; display: flex; align-items: center; justify-content: center; gap: 6px; font-size: 14px;">
                                        <i class="fas fa-times"></i> <span>Reject</span>
                                    </button>
                                </div>
                            ` : `
                                <button onclick="removeReview(${review.id})" style="width: 100%; padding: 10px; background: #8b5cf6; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: 600; transition: all 0.3s; display: flex; align-items: center; justify-content: center; gap: 6px; font-size: 14px;">
                                    <i class="fas fa-trash"></i> <span>Remove Review</span>
                                </button>
                            `}
                        </div>
                    `;
                });
                html += '</div>';
                container.innerHTML = html;
            } catch (error) {
                console.error('Error loading reviews:', error);
                container.innerHTML = `<div style="padding: 20px; color:#b91c1c; text-align: center;">Error: ${escapeAdminHtml(error.message)}</div>`;
            }
        }

        function filterReviews(status) {
            currentReviewFilter = status;
            
            // Update button styling
            document.querySelectorAll('.filter-btn').forEach(btn => {
                btn.style.color = '#999';
                btn.style.borderBottom = '3px solid transparent';
            });
            
            event.target.closest('.filter-btn').style.color = '#667eea';
            event.target.closest('.filter-btn').style.borderBottom = '3px solid #667eea';
            
            loadPendingReviews();
        }

        async function approveReview(reviewId) {
            if (!confirm('Approve this review? It will be displayed on the about page.')) {
                return;
            }

            try {
                const response = await fetch('../api/reviews-manage.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: `action=approve&id=${reviewId}`
                });
                const data = await response.json();
                
                if (data.success) {
                    alert('Review approved successfully!');
                    loadPendingReviews();
                } else {
                    alert('Error: ' + (data.message || 'Failed to approve review'));
                }
            } catch (error) {
                console.error('Error approving review:', error);
                alert('Error approving review');
            }
        }

        async function rejectReview(reviewId) {
            if (!confirm('Reject this review? It will not be displayed on the about page.')) {
                return;
            }

            try {
                const response = await fetch('../api/reviews-manage.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: `action=reject&id=${reviewId}`
                });
                const data = await response.json();
                
                if (data.success) {
                    alert('Review rejected successfully!');
                    loadPendingReviews();
                } else {
                    alert('Error: ' + (data.message || 'Failed to reject review'));
                }
            } catch (error) {
                console.error('Error rejecting review:', error);
                alert('Error rejecting review');
            }
        }

        async function removeReview(reviewId) {
            if (!confirm('Remove this review permanently? This action cannot be undone.')) {
                return;
            }

            try {
                const response = await fetch('../api/reviews-manage.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: `action=remove&id=${reviewId}`
                });
                const data = await response.json();
                
                if (data.success) {
                    alert('Review removed successfully!');
                    loadPendingReviews();
                } else {
                    alert('Error: ' + (data.message || 'Failed to remove review'));
                }
            } catch (error) {
                console.error('Error removing review:', error);
                alert('Error removing review');
            }
        }

        async function loadCustomerFeedback() {
            loadPendingReviews();
        }

        function openAddPropertyModal() {
            editingPropertyId = null;
            document.getElementById('propertyFormTitle').textContent = 'Add New Property';
            resetPropertyForm();
            setPropertyPreview('');
            document.getElementById('addPropertyForm').classList.add('active');
        }

        function closeAddPropertyModal() {
            document.getElementById('addPropertyForm').classList.remove('active');
            resetPropertyForm();
            editingPropertyId = null;
        }

        function resetPropertyForm() {
            document.getElementById('propertyTitle').value = '';
            document.getElementById('propertyType').value = 'house';
            document.getElementById('propertyPrice').value = '';
            document.getElementById('propertyStatus').value = 'active';
            document.getElementById('propertyBrokerId').value = '0';
            document.getElementById('propertyAddress').value = '';
            document.getElementById('propertyCity').value = '';
            document.getElementById('propertyState').value = '';
            document.getElementById('propertyBedrooms').value = 0;
            document.getElementById('propertyBathrooms').value = 0;
            document.getElementById('propertyImageUrl').value = '';
            document.getElementById('propertyImageFile').value = '';
            document.getElementById('propertyDescription').value = '';
        }

        function setPropertyPreview(imagePath) {
            const preview = document.getElementById('propertyImagePreview');
            if (!preview) return;

            if (!imagePath) {
                preview.style.display = 'none';
                preview.removeAttribute('src');
                return;
            }

            const isAbsolute = /^https?:\/\//i.test(imagePath);
            preview.src = isAbsolute ? imagePath : `../${imagePath.replace(/^\/+/, '')}`;
            preview.style.display = 'block';
            preview.onerror = () => {
                preview.style.display = 'none';
            };
        }

        async function uploadPropertyImageIfNeeded() {
            const fileInput = document.getElementById('propertyImageFile');
            if (!fileInput || !fileInput.files || fileInput.files.length === 0) {
                return document.getElementById('propertyImageUrl').value.trim();
            }

            const formData = new FormData();
            formData.append('image', fileInput.files[0]);

            const uploadResponse = await fetch('../api/property-upload-image.php', {
                method: 'POST',
                body: formData
            });

            const uploadData = await uploadResponse.json();
            if (!uploadData.success) {
                throw new Error(uploadData.message || 'Image upload failed');
            }

            document.getElementById('propertyImageUrl').value = uploadData.image_url || '';
            return uploadData.image_url || '';
        }

        async function saveProperty() {
            const wasEditing = Boolean(editingPropertyId);
            const payload = {
                title: document.getElementById('propertyTitle').value.trim(),
                type: document.getElementById('propertyType').value,
                price: document.getElementById('propertyPrice').value,
                status: document.getElementById('propertyStatus').value,
                broker_id: Number(document.getElementById('propertyBrokerId').value || 0),
                address: document.getElementById('propertyAddress').value.trim(),
                city: document.getElementById('propertyCity').value.trim(),
                state: document.getElementById('propertyState').value.trim(),
                bedrooms: document.getElementById('propertyBedrooms').value || 0,
                bathrooms: document.getElementById('propertyBathrooms').value || 0,
                image_url: '',
                description: document.getElementById('propertyDescription').value.trim()
            };

            if (!payload.title || !payload.type || !payload.price || !payload.address || !payload.city) {
                alert('Please fill required fields: title, type, price, address, and city.');
                return;
            }

            if (wasEditing) {
                payload.property_id = editingPropertyId;
            }

            const endpoint = wasEditing ? '../api/property-update.php' : '../api/property-add.php';

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

                if (data.success) {
                    alert(wasEditing ? 'Property updated successfully' : 'Property added successfully');
                    closeAddPropertyModal();
                    loadProperties(wasEditing ? currentPropertyPage : 1);
                    loadPropertyAssignments();
                } else {
                    alert('Error: ' + (data.message || 'Could not save property'));
                }
            } catch (error) {
                console.error('Error saving property:', error);
                alert('Error saving property: ' + error.message);
            }
        }

        async function editProperty(id) {
            try {
                const response = await fetch(`../api/get-property.php?id=${id}`);
                const data = await response.json();

                if (!data.success || !data.property) {
                    alert('Error: ' + (data.message || 'Property not found'));
                    return;
                }

                const prop = data.property;
                editingPropertyId = id;
                document.getElementById('propertyFormTitle').textContent = 'Edit Property';
                document.getElementById('propertyTitle').value = prop.title || '';
                document.getElementById('propertyType').value = prop.type || 'house';
                document.getElementById('propertyPrice').value = prop.price || '';
                document.getElementById('propertyStatus').value = prop.status || 'active';
                document.getElementById('propertyBrokerId').value = Number(prop.broker_id || 0).toString();
                document.getElementById('propertyAddress').value = prop.address || '';
                document.getElementById('propertyCity').value = prop.city || '';
                document.getElementById('propertyState').value = prop.state || '';
                document.getElementById('propertyBedrooms').value = prop.bedrooms || 0;
                document.getElementById('propertyBathrooms').value = prop.bathrooms || 0;
                document.getElementById('propertyImageUrl').value = prop.image_url || '';
                document.getElementById('propertyImageFile').value = '';
                document.getElementById('propertyDescription').value = prop.description || '';
                setPropertyPreview(prop.image_url || '');
                document.getElementById('addPropertyForm').classList.add('active');
            } catch (error) {
                console.error('Error loading property:', error);
                alert('Error loading property details: ' + error.message);
            }
        }

        function deleteProperty(id) {
            if (confirm('Are you sure you want to delete this property? This action cannot be undone.')) {
                fetch(`../api/property-delete.php`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ property_id: id })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('Property deleted successfully');
                        loadProperties(1);
                        loadPropertyAssignments();
                    } else {
                        alert('Error: ' + (data.message || 'Could not delete property'));
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error deleting property: ' + error.message);
                });
            }
        }

        // Services Management
        let currentServicePage = 1;
        let totalServicePages = 1;
        let editingServiceId = null;

        async function loadServices(page = 1) {
            try {
                const response = await fetch(`../api/get-services.php?page=${page}&per_page=12`);
                const data = await response.json();
                
                console.log('Services API response:', data);
                
                if (data.success && data.services && Array.isArray(data.services)) {
                    renderServices(data.services, data.page, data.total_pages);
                    currentServicePage = page;
                    totalServicePages = data.total_pages;
                } else if (!data.success) {
                    console.error('API error:', data.message || 'Unknown error');
                    document.getElementById('servicesContent').innerHTML = `<p style="color: red;">Error: ${data.message || 'Failed to load services'}</p>`;
                } else {
                    console.error('Invalid response format:', data);
                    document.getElementById('servicesContent').innerHTML = '<p>Invalid data format received</p>';
                }
            } catch (error) {
                console.error('Error loading services:', error);
                document.getElementById('servicesContent').innerHTML = `<p style="color: red;">Error: ${error.message}</p>`;
            }
        }

        function renderServices(services, page, totalPages) {
            let html = '<div class="service-grid">';
            
            if (services.length === 0) {
                html = '<p style="grid-column: 1/-1; text-align: center; padding: 40px;">No services found.</p>';
            } else {
                services.forEach(service => {
                    html += `
                        <div class="service-card">
                            <div style="font-size: 40px; margin-bottom: 15px; text-align: center;">
                                <i class="${service.icon || 'fas fa-cogs'}" style="color: #667eea;"></i>
                            </div>
                            <div class="card-header">
                                <div class="card-title">${service.title}</div>
                            </div>
                            <div class="card-meta" style="margin-bottom: 10px; min-height: 40px; line-height: 1.4;">
                                ${service.description || '<em>No description provided</em>'}
                            </div>
                            ${service.price ? `
                                <div class="card-meta"><strong style="font-size: 14px; color: #667eea;"> $${Number(service.price).toLocaleString()}</strong></div>
                            ` : ''}
                            <div style="margin: 12px 0; padding: 8px; background: #f8f9fa; border-radius: 5px; display: inline-block;">
                                <span class="status-badge status-${(service.status || 'active').toLowerCase()}">${(service.status || 'active').toUpperCase()}</span>
                            </div>
                            <div class="card-actions">
                                <button class="btn-edit" onclick="editService(${service.id})"><i class="fas fa-edit"></i> Edit</button>
                                <button class="btn-delete" onclick="deleteService(${service.id})"><i class="fas fa-trash"></i> Delete</button>
                            </div>
                        </div>
                    `;
                });
            }
            
            html += '</div>';
            
            // Add pagination
            if (totalPages > 1) {
                html += '<div class="pagination">';
                for (let i = 1; i <= totalPages; i++) {
                    html += `<button class="pagination-btn ${i === page ? 'active' : ''}" onclick="loadServices(${i})">${i}</button>`;
                }
                html += '</div>';
            }
            
            document.getElementById('servicesContent').innerHTML = html;
        }

        function openAddServiceModal() {
            editingServiceId = null;
            document.getElementById('serviceFormTitle').textContent = 'Add New Service';
            resetServiceForm();
            document.getElementById('addServiceForm').classList.add('active');
        }

        async function loadPropertyApprovals() {
            try {
                const response = await fetch('../api/admin/get-property-approvals.php');
                const data = await response.json();

                if (!data.success) {
                    document.getElementById('propertyApprovalsContent').innerHTML = `<p style="color:red;">Error: ${data.message || 'Failed to load requests'}</p>`;
                    return;
                }

                pendingPropertyApprovals = data.requests || [];
                syncPropertyApprovalPriceDrafts(pendingPropertyApprovals);
                renderPropertyApprovals(pendingPropertyApprovals);
            } catch (error) {
                console.error('Error loading property approvals:', error);
                document.getElementById('propertyApprovalsContent').innerHTML = `<p style="color:red;">Error: ${error.message}</p>`;
            }
        }

        async function loadDocumentApprovals() {
            try {
                const response = await fetch('../api/admin/get-document-approvals.php');
                const data = await response.json();

                if (!data.success) {
                    document.getElementById('documentApprovalsContent').innerHTML = `<p style="color:red;">Error: ${data.message || 'Failed to load documents'}</p>`;
                    return;
                }

                pendingDocumentApprovals = data.documents || [];
                renderDocumentApprovals(pendingDocumentApprovals);
            } catch (error) {
                console.error('Error loading document approvals:', error);
                document.getElementById('documentApprovalsContent').innerHTML = `<p style="color:red;">Error: ${error.message}</p>`;
            }
        }

        function normalizeAdminMediaPath(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 isImageMediaPath(filePath) {
            const path = String(filePath || '').toLowerCase();
            return /\.(jpg|jpeg|png|webp|gif|bmp|svg)$/.test(path);
        }

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

        function formatAdminDateTime(dateString) {
            if (!dateString) return 'N/A';
            const date = new Date(dateString);
            if (Number.isNaN(date.getTime())) return String(dateString);
            return date.toLocaleString('en-US', { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
        }

        function closeApprovalDetailsModal(event) {
            if (event && event.target && event.target.id !== 'approvalDetailsModal') {
                return;
            }
            const modal = document.getElementById('approvalDetailsModal');
            if (modal) modal.classList.remove('active');
        }

        function openApprovalDetailsModal(title, contentHtml) {
            const modal = document.getElementById('approvalDetailsModal');
            const titleEl = document.getElementById('approvalDetailsTitle');
            const bodyEl = document.getElementById('approvalDetailsBody');
            if (!modal || !titleEl || !bodyEl) return;
            titleEl.textContent = title;
            bodyEl.innerHTML = contentHtml;
            modal.classList.add('active');
        }

        function openPropertyApprovalDetails(requestId) {
            const request = (pendingPropertyApprovals || []).find((item) => Number(item.id) === Number(requestId));
            if (!request) return;

            const imageUrl = normalizeAdminMediaPath(request.image_url || '');
            const preview = imageUrl
                ? `<a href="${imageUrl}" target="_blank" rel="noopener"><img src="${imageUrl}" alt="${escapeAdminHtml(request.title || 'Property')}" class="approval-media" style="width:120px;height:86px;"></a>`
                : '<div class="approval-media-placeholder" style="width:120px;height:86px;">No Image</div>';
            const requestType = request.request_type === 'new_listing' ? 'New Listing' : 'Update';

            const html = `
                <div class="approval-details-grid">
                    <div class="approval-details-item approval-details-wide">
                        <div class="approval-media-wrap">${preview}</div>
                    </div>
                    <div class="approval-details-item"><div class="approval-details-label">Request ID</div><div class="approval-details-value">#${request.id}</div></div>
                    <div class="approval-details-item"><div class="approval-details-label">Type</div><div class="approval-details-value">${escapeAdminHtml(requestType)}</div></div>
                    <div class="approval-details-item"><div class="approval-details-label">Broker</div><div class="approval-details-value">${escapeAdminHtml(request.broker_name || ('Broker #' + request.broker_id))}</div></div>
                    <div class="approval-details-item"><div class="approval-details-label">Title</div><div class="approval-details-value">${escapeAdminHtml(request.title || request.existing_property_title || 'Untitled')}</div></div>
                    <div class="approval-details-item"><div class="approval-details-label">Category</div><div class="approval-details-value">${escapeAdminHtml(request.type || 'N/A')}</div></div>
                    <div class="approval-details-item"><div class="approval-details-label">Submitted Price</div><div class="approval-details-value">${request.price ? ('$' + Number(request.price).toLocaleString()) : 'N/A'}</div></div>
                    <div class="approval-details-item"><div class="approval-details-label">Address</div><div class="approval-details-value">${escapeAdminHtml(request.address || 'N/A')}</div></div>
                    <div class="approval-details-item"><div class="approval-details-label">City / State</div><div class="approval-details-value">${escapeAdminHtml((request.city || 'N/A') + (request.state ? ', ' + request.state : ''))}</div></div>
                    <div class="approval-details-item"><div class="approval-details-label">Bedrooms</div><div class="approval-details-value">${escapeAdminHtml(request.bedrooms ?? 'N/A')}</div></div>
                    <div class="approval-details-item"><div class="approval-details-label">Bathrooms</div><div class="approval-details-value">${escapeAdminHtml(request.bathrooms ?? 'N/A')}</div></div>
                    <div class="approval-details-item"><div class="approval-details-label">Submitted</div><div class="approval-details-value">${escapeAdminHtml(formatAdminDateTime(request.created_at))}</div></div>
                    <div class="approval-details-item approval-details-wide"><div class="approval-details-label">Description</div><div class="approval-details-value">${escapeAdminHtml(request.description || 'N/A')}</div></div>
                </div>
            `;
            openApprovalDetailsModal('Property Request Details', html);
        }

        function openDocumentApprovalDetails(documentId) {
            const doc = (pendingDocumentApprovals || []).find((item) => Number(item.id) === Number(documentId));
            if (!doc) return;

            const docUrl = normalizeAdminMediaPath(doc.file_path || '');
            const isImage = isImageMediaPath(doc.file_path || doc.document_name || '');
            const preview = isImage
                ? `<a href="${docUrl}" target="_blank" rel="noopener"><img src="${docUrl}" alt="${escapeAdminHtml(doc.document_name || 'Document')}" class="approval-media" style="width:120px;height:86px;"></a>`
                : '<div class="approval-media-placeholder" style="width:120px;height:86px;">Document</div>';
            const sizeText = doc.file_size ? `${(Number(doc.file_size) / 1024).toFixed(1)} KB` : 'N/A';

            const html = `
                <div class="approval-details-grid">
                    <div class="approval-details-item approval-details-wide">
                        <div class="approval-media-wrap">${preview}
                            <a href="${docUrl}" target="_blank" rel="noopener" style="font-size:13px;">Open File</a>
                        </div>
                    </div>
                    <div class="approval-details-item"><div class="approval-details-label">Document ID</div><div class="approval-details-value">#${doc.id}</div></div>
                    <div class="approval-details-item"><div class="approval-details-label">Broker</div><div class="approval-details-value">${escapeAdminHtml(doc.broker_name || ('Broker #' + doc.broker_id))}</div></div>
                    <div class="approval-details-item"><div class="approval-details-label">Property</div><div class="approval-details-value">${escapeAdminHtml(doc.property_title || 'N/A')}</div></div>
                    <div class="approval-details-item"><div class="approval-details-label">Document Name</div><div class="approval-details-value">${escapeAdminHtml(doc.document_name || 'N/A')}</div></div>
                    <div class="approval-details-item"><div class="approval-details-label">Type</div><div class="approval-details-value">${escapeAdminHtml(doc.document_type || 'N/A')}</div></div>
                    <div class="approval-details-item"><div class="approval-details-label">Size</div><div class="approval-details-value">${escapeAdminHtml(sizeText)}</div></div>
                    <div class="approval-details-item"><div class="approval-details-label">Uploaded</div><div class="approval-details-value">${escapeAdminHtml(formatAdminDateTime(doc.uploaded_at))}</div></div>
                    <div class="approval-details-item"><div class="approval-details-label">Current Status</div><div class="approval-details-value">${escapeAdminHtml(doc.approval_status || 'pending')}</div></div>
                </div>
            `;
            openApprovalDetailsModal('Document Details', html);
        }

        function renderDocumentApprovals(documents) {
            if (!Array.isArray(documents) || documents.length === 0) {
                document.getElementById('documentApprovalsContent').innerHTML = '<div style="padding: 15px; color:#777;">No pending documents.</div>';
                return;
            }

            let html = '<div class="table-responsive"><table class="approval-table"><thead><tr><th>ID</th><th>Broker</th><th>Property</th><th>Preview</th><th>Document</th><th>Type</th><th>Size</th><th>Notes</th><th>Actions</th></tr></thead><tbody>';

            documents.forEach((doc) => {
                const kb = doc.file_size ? `${(Number(doc.file_size) / 1024).toFixed(1)} KB` : '-';
                const docUrl = normalizeAdminMediaPath(doc.file_path || '');
                const imagePreview = isImageMediaPath(doc.file_path || doc.document_name || '');
                const previewHtml = imagePreview
                    ? `<a href="${docUrl}" target="_blank" rel="noopener"><img src="${docUrl}" alt="Document preview" class="approval-media"></a>`
                    : '<div class="approval-media-placeholder"><i class="fas fa-file-alt"></i></div>';
                html += `
                    <tr>
                        <td>#${doc.id}</td>
                        <td>${doc.broker_name || ('Broker #' + doc.broker_id)}</td>
                        <td>${doc.property_title || 'N/A'}</td>
                        <td><div class="approval-media-wrap">${previewHtml}</div></td>
                        <td>
                            <div style="font-weight:600;">${doc.document_name || 'Document'}</div>
                            <a href="${docUrl}" target="_blank" rel="noopener">View File</a>
                        </td>
                        <td>${doc.document_type || '-'}</td>
                        <td>${kb}</td>
                        <td><input type="text" id="docNote_${doc.id}" placeholder="Admin notes" style="width: 100%; min-width: 170px; padding:6px; border:1px solid #ddd; border-radius:4px;"></td>
                        <td>
                            <div class="approval-actions">
                            <button class="btn btn-sm btn-secondary" onclick="openDocumentApprovalDetails(${doc.id})">View Details</button>
                            <button class="btn btn-sm" onclick="reviewDocumentApproval(${doc.id}, 'approve')">Approve</button>
                            <button class="btn btn-sm btn-secondary" onclick="reviewDocumentApproval(${doc.id}, 'reject')">Reject</button>
                            </div>
                        </td>
                    </tr>
                `;
            });

            html += '</tbody></table></div>';
            document.getElementById('documentApprovalsContent').innerHTML = html;
        }

        async function reviewDocumentApproval(documentId, action) {
            const noteInput = document.getElementById(`docNote_${documentId}`);
            const admin_notes = noteInput ? noteInput.value.trim() : '';

            try {
                const response = await fetch('../api/admin/review-document-approval.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ document_id: documentId, action, admin_notes })
                });
                const data = await response.json();
                if (!data.success) {
                    alert('Error: ' + (data.message || 'Action failed'));
                    return;
                }

                alert(data.message || 'Document reviewed');
                loadDocumentApprovals();
            } catch (error) {
                console.error('Error reviewing document:', error);
                alert('Error: ' + error.message);
            }
        }

        function renderPropertyApprovals(requests) {
            if (!Array.isArray(requests) || requests.length === 0) {
                document.getElementById('propertyApprovalsContent').innerHTML = '<div style="padding: 15px; color:#777;">No pending listing/update requests.</div>';
                return;
            }

            let html = '<div class="table-responsive"><table class="approval-table"><thead><tr><th>ID</th><th>Broker</th><th>Type</th><th>Preview</th><th>Property</th><th>Submitted Price</th><th>Admin Final Price</th><th>Actions</th></tr></thead><tbody>';

            requests.forEach((req) => {
                const requestType = req.request_type === 'new_listing' ? 'New Listing' : 'Update';
                const label = req.title || req.existing_property_title || 'Untitled';
                const inputValue = Object.prototype.hasOwnProperty.call(propertyApprovalPriceDrafts, req.id)
                    ? propertyApprovalPriceDrafts[req.id]
                    : (req.price || '');
                const imageUrl = normalizeAdminMediaPath(req.image_url || '');
                const previewHtml = imageUrl
                    ? `<a href="${imageUrl}" target="_blank" rel="noopener"><img src="${imageUrl}" alt="${label}" class="approval-media"></a>`
                    : '<div class="approval-media-placeholder"><i class="fas fa-home"></i></div>';
                html += `
                    <tr>
                        <td>#${req.id}</td>
                        <td>${req.broker_name || ('Broker #' + req.broker_id)}</td>
                        <td>${requestType}</td>
                        <td><div class="approval-media-wrap">${previewHtml}</div></td>
                        <td class="approval-property-cell">
                            <div style="font-weight:600;">${label}</div>
                            <div style="font-size:12px;color:#777;">${req.address || ''} ${req.city ? ', ' + req.city : ''}</div>
                            ${imageUrl ? `<a href="${imageUrl}" target="_blank" rel="noopener" style="font-size:12px;">View Image</a>` : ''}
                        </td>
                        <td>${req.price ? '$' + Number(req.price).toLocaleString() : '-'}</td>
                        <td><input type="number" id="approvalPrice_${req.id}" value="${inputValue}" min="0" step="0.01" oninput="setPropertyApprovalPriceDraft(${req.id}, this.value)" class="approval-price-input" placeholder="Required"></td>
                        <td>
                            <div class="approval-actions">
                            <button class="btn btn-sm btn-secondary" onclick="openPropertyApprovalDetails(${req.id})">View Details</button>
                            <button class="btn btn-sm" onclick="reviewPropertyApproval(${req.id}, 'approve')">Approve</button>
                            <button class="btn btn-sm btn-secondary" onclick="reviewPropertyApproval(${req.id}, 'reject')">Reject</button>
                            </div>
                        </td>
                    </tr>
                `;
            });

            html += '</tbody></table></div>';
            document.getElementById('propertyApprovalsContent').innerHTML = html;
        }

        async function reviewPropertyApproval(requestId, action) {
            const priceInput = document.getElementById(`approvalPrice_${requestId}`);
            const admin_price = priceInput ? Number(priceInput.value || 0) : Number(propertyApprovalPriceDrafts[requestId] || 0);

            if (action === 'approve' && admin_price <= 0) {
                alert('Please set admin final price before approving.');
                return;
            }

            try {
                const response = await fetch('../api/admin/review-property-approval.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ request_id: requestId, action, admin_price })
                });
                const data = await response.json();
                if (!data.success) {
                    alert('Error: ' + (data.message || 'Action failed'));
                    return;
                }

                delete propertyApprovalPriceDrafts[requestId];
                alert(data.message || 'Request processed');
                loadPropertyApprovals();
                loadProperties(currentPropertyPage);
                loadPropertyAssignments();
            } catch (error) {
                console.error('Error reviewing request:', error);
                alert('Error processing request: ' + error.message);
            }
        }

        function setPropertyApprovalPriceDraft(requestId, value) {
            propertyApprovalPriceDrafts[requestId] = value;
        }

        function syncPropertyApprovalPriceDrafts(requests) {
            const activeIds = new Set((requests || []).map((req) => String(req.id)));
            Object.keys(propertyApprovalPriceDrafts).forEach((id) => {
                if (!activeIds.has(id)) {
                    delete propertyApprovalPriceDrafts[id];
                }
            });
        }

        function closeAddServiceModal() {
            document.getElementById('addServiceForm').classList.remove('active');
            resetServiceForm();
            editingServiceId = null;
        }

        function resetServiceForm() {
            document.getElementById('serviceTitle').value = '';
            document.getElementById('serviceDescription').value = '';
            document.getElementById('serviceIcon').value = 'fas fa-cogs';
            document.getElementById('servicePrice').value = '';
            document.getElementById('serviceStatus').value = 'active';
        }

        async function saveService() {
            const wasEditing = Boolean(editingServiceId);
            const payload = {
                title: document.getElementById('serviceTitle').value.trim(),
                description: document.getElementById('serviceDescription').value.trim(),
                icon: document.getElementById('serviceIcon').value.trim() || 'fas fa-cogs',
                price: document.getElementById('servicePrice').value || 0,
                status: document.getElementById('serviceStatus').value || 'active'
            };

            if (!payload.title) {
                alert('Please enter a service title');
                return;
            }

            if (wasEditing) {
                payload.service_id = editingServiceId;
            }

            const endpoint = wasEditing ? '../api/service-update.php' : '../api/service-add.php';

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

                const data = await response.json();
                if (data.success) {
                    alert(wasEditing ? 'Service updated successfully!' : 'Service added successfully!');
                    closeAddServiceModal();
                    loadServices(wasEditing ? currentServicePage : 1);
                } else {
                    alert('Error: ' + (data.message || 'Could not save service'));
                }
            } catch (error) {
                console.error('Error saving service:', error);
                alert('Error saving service: ' + error.message);
            }
        }

        async function editService(id) {
            try {
                const response = await fetch(`../api/get-service.php?id=${id}`);
                const data = await response.json();

                if (!data.success || !data.service) {
                    alert('Error: ' + (data.message || 'Service not found'));
                    return;
                }

                const service = data.service;
                editingServiceId = id;
                document.getElementById('serviceFormTitle').textContent = 'Edit Service';
                document.getElementById('serviceTitle').value = service.title || '';
                document.getElementById('serviceDescription').value = service.description || '';
                document.getElementById('serviceIcon').value = service.icon || 'fas fa-cogs';
                document.getElementById('servicePrice').value = service.price || '';
                document.getElementById('serviceStatus').value = service.status || 'active';
                document.getElementById('addServiceForm').classList.add('active');
            } catch (error) {
                console.error('Error loading service:', error);
                alert('Error loading service details: ' + error.message);
            }
        }

        function deleteService(id) {
            if (confirm('Are you sure you want to delete this service? This action cannot be undone.')) {
                fetch(`../api/service-delete.php`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ service_id: id })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('Service deleted successfully');
                        loadServices(1);
                    } else {
                        alert('Error: ' + (data.message || 'Could not delete service'));
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error deleting service: ' + error.message);
                });
            }
        }

        // User Management
        function setModalBodyScrollLock(isLocked) {
            document.body.style.overflow = isLocked ? 'hidden' : '';
        }

        function showAddUserForm() {
            document.getElementById('addUserForm').classList.add('active');
            setModalBodyScrollLock(true);
        }
        
        function hideAddUserForm() {
            document.getElementById('addUserForm').classList.remove('active');
            if (!document.getElementById('editUserForm').classList.contains('active')) {
                setModalBodyScrollLock(false);
            }
        }

        function hideEditUserForm() {
            document.getElementById('editUserForm').classList.remove('active');
            if (!document.getElementById('addUserForm').classList.contains('active')) {
                setModalBodyScrollLock(false);
            }
        }

        function handleUserModalOverlayClick(event, modalId) {
            if (event.target.id !== modalId) {
                return;
            }
            if (modalId === 'addUserForm') {
                hideAddUserForm();
                return;
            }
            hideEditUserForm();
        }

        function updateUserRowsInTables(userData) {
            const rows = document.querySelectorAll(`tr[data-user-id="${userData.id}"]`);
            rows.forEach((row) => {
                const panel = row.closest('.panel');
                if (panel && panel.id === 'brokersPanel' && userData.role !== 'broker') {
                    row.remove();
                    return;
                }
                if (panel && panel.id === 'staffPanel' && userData.role !== 'staff') {
                    row.remove();
                    return;
                }

                row.setAttribute('data-user-role', userData.role || 'customer');
                const cells = row.querySelectorAll('td');
                if (cells.length < 6) return;

                // Name, email, status, and role badge update for Users/Brokers/Staff tables
                if (cells[0]) cells[0].textContent = userData.full_name || '';
                if (cells[1]) cells[1].textContent = userData.email || '';

                // Users table has role in column index 2
                const roleBadge = row.querySelector('.role-badge');
                if (roleBadge) {
                    roleBadge.textContent = (userData.role || '').charAt(0).toUpperCase() + (userData.role || '').slice(1);
                    roleBadge.className = `role-badge role-${userData.role || 'customer'}`;
                }

                const statusBadge = row.querySelector('.status-badge');
                if (statusBadge) {
                    statusBadge.textContent = (userData.status || '').charAt(0).toUpperCase() + (userData.status || '').slice(1);
                    statusBadge.className = `status-badge status-${userData.status || 'inactive'}`;
                }

                const suspendBtn = row.querySelector('.btn-secondary');
                if (suspendBtn) {
                    suspendBtn.textContent = userData.status === 'active' ? 'Suspend' : 'Activate';
                }
            });
        }

        async function editUser(id) {
            try {
                const response = await fetch(`../api/get-user.php?id=${id}`);
                const data = await response.json();
                if (!data.success || !data.user) {
                    alert('Error: ' + (data.message || 'User not found'));
                    return;
                }

                const user = data.user;
                document.getElementById('editUserId').value = user.id;
                document.getElementById('editUserName').value = user.full_name || '';
                document.getElementById('editUserEmail').value = user.email || '';
                document.getElementById('editUserPhone').value = user.phone || '';
                document.getElementById('editUserRole').value = user.role || 'customer';
                document.getElementById('editUserStatus').value = user.status || 'active';
                document.getElementById('editUserForm').classList.add('active');
                setModalBodyScrollLock(true);
            } catch (error) {
                console.error('Error loading user:', error);
                alert('Error loading user: ' + error.message);
            }
        }

        document.addEventListener('keydown', (event) => {
            if (event.key !== 'Escape') return;
            if (document.getElementById('addUserForm').classList.contains('active')) {
                hideAddUserForm();
                return;
            }
            if (document.getElementById('editUserForm').classList.contains('active')) {
                hideEditUserForm();
            }
        });

        async function saveUserEdit() {
            const payload = {
                user_id: Number(document.getElementById('editUserId').value || 0),
                full_name: document.getElementById('editUserName').value.trim(),
                email: document.getElementById('editUserEmail').value.trim(),
                phone: document.getElementById('editUserPhone').value.trim(),
                role: document.getElementById('editUserRole').value,
                status: document.getElementById('editUserStatus').value
            };

            if (!payload.user_id || !payload.full_name || !payload.email || !payload.role) {
                alert('Please fill all required fields.');
                return;
            }

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

                if (!data.success) {
                    alert('Error: ' + (data.message || 'Could not update user'));
                    return;
                }

                hideEditUserForm();
                updateUserRowsInTables(payload);
                alert('User updated successfully');
            } catch (error) {
                console.error('Error updating user:', error);
                alert('Error updating user: ' + error.message);
            }
        }

        async function suspendUser(id) {
            try {
                const response = await fetch('../api/user-toggle-status.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ user_id: id })
                });
                const data = await response.json();

                if (!data.success) {
                    alert('Error: ' + (data.message || 'Could not change user status'));
                    return;
                }

                updateUserRowsInTables({
                    id,
                    full_name: data.user?.full_name || '',
                    email: data.user?.email || '',
                    role: data.user?.role || 'customer',
                    status: data.user?.status || 'inactive'
                });
                alert(data.message || 'User status updated');
            } catch (error) {
                console.error('Error changing user status:', error);
                alert('Error changing user status: ' + error.message);
            }
        }

        function updateCustomerRowsInTable(customerData) {
            const rows = document.querySelectorAll(`tr[data-customer-id="${customerData.id}"]`);
            rows.forEach((row) => {
                const statusBadge = row.querySelector('.status-badge');
                if (statusBadge) {
                    statusBadge.className = `status-badge status-${customerData.status}`;
                    statusBadge.textContent = customerData.status.charAt(0).toUpperCase() + customerData.status.slice(1);
                }
                const toggleBtn = row.querySelector('button[onclick^="toggleCustomerStatus("]');
                if (toggleBtn) {
                    toggleBtn.textContent = customerData.status === 'active' ? 'Suspend' : 'Activate';
                }
            });
        }

        async function toggleCustomerStatus(id) {
            try {
                const response = await fetch('../api/customer-toggle-status.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ customer_id: id })
                });
                const data = await response.json();
                if (!data.success) {
                    alert('Error: ' + (data.message || 'Could not change customer status'));
                    return;
                }

                updateCustomerRowsInTable({
                    id,
                    status: data.customer?.status || 'inactive'
                });
                alert(data.message || 'Customer status updated');
            } catch (error) {
                console.error('Error changing customer status:', error);
                alert('Error changing customer status: ' + error.message);
            }
        }

        async function updateAnalyticsRealtime() {
            try {
                const response = await fetch('../api/admin/get-analytics-live.php');
                const data = await response.json();
                if (!data.success || !data.analytics) return;

                const pendingEl = document.getElementById('analyticsBrokerPending');
                const approvalPendingEl = document.getElementById('analyticsBrokerApprovalPending');
                const finishedEl = document.getElementById('analyticsBrokerFinished');
                if (pendingEl) pendingEl.textContent = Number(data.analytics.broker_pending_properties || 0).toLocaleString();
                if (approvalPendingEl) approvalPendingEl.textContent = Number(data.analytics.broker_approval_pending_properties || 0).toLocaleString();
                if (finishedEl) finishedEl.textContent = Number(data.analytics.broker_finished_properties || 0).toLocaleString();

                brokerWorkflowCounts = [
                    Number(data.analytics.broker_pending_properties || 0),
                    Number(data.analytics.broker_approval_pending_properties || 0),
                    Number(data.analytics.broker_finished_properties || 0)
                ];
                renderAnalyticsCharts();
            } catch (error) {
                console.error('Error updating analytics realtime:', error);
            }
        }

        // Real-time Updates - Check for changes every 5 seconds
        setInterval(() => {
            if (currentSection === 'properties') {
                loadProperties(currentPropertyPage);
                loadPropertyApprovals();
                loadDocumentApprovals();
            } else if (currentSection === 'assignments') {
                loadPropertyAssignments();
            } else if (currentSection === 'feedback') {
                loadCustomerFeedback();
            } else if (currentSection === 'analytics') {
                updateAnalyticsRealtime();
            } else if (currentSection === 'services') {
                loadServices(currentServicePage);
            }
        }, 5000);
        
        // Refresh when tab regains focus
        window.addEventListener('focus', () => {
            if (currentSection === 'properties') {
                loadProperties(currentPropertyPage);
                loadPropertyApprovals();
                loadDocumentApprovals();
            } else if (currentSection === 'assignments') {
                loadPropertyAssignments();
            } else if (currentSection === 'feedback') {
                loadCustomerFeedback();
            } else if (currentSection === 'analytics') {
                updateAnalyticsRealtime();
            } else if (currentSection === 'services') {
                loadServices(currentServicePage);
            }
        });

        window.addEventListener('resize', () => {
            const analyticsPanel = document.getElementById('analyticsPanel');
            if (analyticsPanel && analyticsPanel.style.display === 'block') {
                renderAnalyticsCharts();
            }
        });

        // Mobile menu toggle functionality
        function toggleSidebar() {
            const sidebar = document.querySelector('.sidebar');
            const overlay = document.getElementById('sidebarOverlay');
            if (!sidebar || !overlay) return;
            const isOpen = sidebar.classList.contains('mobile-open');
            if (isOpen) {
                closeSidebar();
            } else {
                sidebar.classList.add('mobile-open');
                overlay.classList.add('active');
            }
        }

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

        document.addEventListener('DOMContentLoaded', () => {
            const toggleButton = document.getElementById('mobileMenuToggle');
            const overlay = document.getElementById('sidebarOverlay');
            const menuLinks = document.querySelectorAll('.sidebar-menu a');
            const heroImageUrlInput = document.getElementById('heroSliderImageUrl');

            if (toggleButton) {
                toggleButton.addEventListener('click', toggleSidebar);
            }

            if (overlay) {
                overlay.addEventListener('click', closeSidebar);
            }

            menuLinks.forEach(link => {
                link.addEventListener('click', () => {
                    if (window.innerWidth <= 768) {
                        closeSidebar();
                    }
                });
            });

            window.addEventListener('resize', () => {
                if (window.innerWidth > 768) {
                    closeSidebar();
                }
            });

            if (heroImageUrlInput) {
                heroImageUrlInput.addEventListener('change', () => {
                    const fileInput = document.getElementById('heroSliderImageFile');
                    if (fileInput && fileInput.files && fileInput.files.length > 0) return;
                    setHeroSliderPreview(heroImageUrlInput.value || '');
                });
            }
        });

        // Hero Slider Management Functions
        let allHeroSliders = [];
        const HERO_PAGE_OPTIONS = ['about.php', 'properties.php', 'service.php', 'contact.php', 'appointment.php'];

        async function loadHeroSliders() {
            try {
                const response = await fetch('../api/hero-slider.php?action=get_all');
                const data = await response.json();
                
                if (data.success) {
                    allHeroSliders = data.sliders;
                    renderHeroSliders();
                }
            } catch (error) {
                console.error('Error loading hero sliders:', error);
            }
        }

        function renderHeroSliders() {
            const container = document.getElementById('heroSliderList');
            if (!container) return;

            if (allHeroSliders.length === 0) {
                container.innerHTML = '<div style="grid-column: 1/-1; text-align: center; padding: 40px; color: #999;"><p>No hero sliders found. Create your first one!</p></div>';
                return;
            }

            container.innerHTML = allHeroSliders.map(slider => {
                const subtitleText = String(slider.subtitle || '');
                return `
                <div class="hero-slider-card">
                    ${slider.image_url ? `<img src="${escapeHtml(normalizeDashboardImagePath(slider.image_url))}" alt="${escapeHtml(slider.title || 'Hero image')}" class="hero-slider-thumb" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">` : ''}
                    <div class="hero-slider-thumb-placeholder" style="${slider.image_url ? 'display:none;' : ''}"><i class="fas fa-image"></i></div>
                    <div style="padding: 20px;">
                        <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 15px;">
                            <div style="flex: 1;">
                                <h4 style="margin: 0 0 5px 0; color: #333;">${escapeHtml(slider.title)}</h4>
                                <p style="margin: 0; color: #999; font-size: 12px;">Category: ${escapeHtml(slider.tag)}</p>
                            </div>
                            <span style="background: ${slider.status === 'active' ? '#d4edda' : '#f8d7da'}; color: ${slider.status === 'active' ? '#155724' : '#721c24'}; padding: 5px 10px; border-radius: 20px; font-size: 11px; font-weight: 600; white-space: nowrap; margin-left: 10px;">
                                ${slider.status.charAt(0).toUpperCase() + slider.status.slice(1)}
                            </span>
                        </div>
                        
                        <p style="margin: 10px 0; color: #666; font-size: 13px; line-height: 1.4;">${escapeHtml(subtitleText.substring(0, 80))}${subtitleText.length > 80 ? '...' : ''}</p>
                        
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin: 15px 0; font-size: 12px;">
                            <div>
                                <strong style="color: #667eea;">Button 1:</strong>
                                <p style="margin: 3px 0 0 0; color: #666;">${escapeHtml(slider.button1_text || 'N/A')} ${slider.button1_url ? `• ${escapeHtml(slider.button1_url)}` : ''}</p>
                            </div>
                            <div>
                                <strong style="color: #667eea;">Button 2:</strong>
                                <p style="margin: 3px 0 0 0; color: #666;">${escapeHtml(slider.button2_text || 'N/A')} ${slider.button2_url ? `• ${escapeHtml(slider.button2_url)}` : ''}</p>
                            </div>
                        </div>

                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin: 15px 0; font-size: 12px;">
                            <div>
                                <strong style="color: #667eea;">Stats:</strong>
                                <p style="margin: 3px 0 0 0; color: #666;">${escapeHtml(slider.stat1_text || 'N/A')}</p>
                            </div>
                            <div>
                                <p style="margin: 3px 0 0 0; color: #666;">${escapeHtml(slider.stat2_text || 'N/A')}</p>
                            </div>
                        </div>

                        <p style="margin: 10px 0 0 0; font-size: 11px; color: #999;">Order: #${slider.display_order} | Created: ${new Date(slider.created_at).toLocaleDateString()}</p>

                        <div class="hero-slider-card-buttons" style="margin-top: 15px;">
                            <button type="button" class="btn" style="padding: 8px; border: none; border-radius: 5px; background: #667eea; color: white; font-size: 12px; cursor: pointer;" onclick="editHeroSlider(${parseInt(slider.id, 10)})">
                                <i class="fas fa-edit"></i> Edit
                            </button>
                            <button type="button" class="btn" style="padding: 8px; border: none; border-radius: 5px; background: #dc3545; color: white; font-size: 12px; cursor: pointer;" onclick="deleteHeroSlider(${slider.id})">
                                <i class="fas fa-trash"></i> Delete
                            </button>
                        </div>
                    </div>
                </div>
            `;
            }).join('');
        }

        function openHeroSliderModal() {
            document.getElementById('heroSliderId').value = '';
            document.getElementById('heroSliderForm').reset();
            setHeroSliderPreview('');
            setHeroUrlFieldValue('heroSliderButton1Url', 'heroSliderButton1Custom', '');
            setHeroUrlFieldValue('heroSliderButton2Url', 'heroSliderButton2Custom', '');
            document.getElementById('heroSliderModalTitle').textContent = 'Add Hero Slider';
            document.getElementById('heroSliderModal').style.display = 'block';
            document.getElementById('heroSliderModalOverlay').style.display = 'block';
            document.body.style.overflow = 'hidden';
        }

        function closeHeroSliderModal() {
            document.getElementById('heroSliderModal').style.display = 'none';
            document.getElementById('heroSliderModalOverlay').style.display = 'none';
            document.getElementById('heroSliderForm').reset();
            setHeroSliderPreview('');
            setHeroUrlFieldValue('heroSliderButton1Url', 'heroSliderButton1Custom', '');
            setHeroUrlFieldValue('heroSliderButton2Url', 'heroSliderButton2Custom', '');
            document.body.style.overflow = '';
        }

        function editHeroSlider(id) {
            const sliderId = parseInt(id, 10);
            const slider = allHeroSliders.find(s => parseInt(s.id, 10) === sliderId);
            if (!slider) {
                console.error('Slider not found with ID:', sliderId);
                alert('Error: Slider not found');
                return;
            }

            document.getElementById('heroSliderId').value = slider.id;
            document.getElementById('heroSliderTag').value = slider.tag || '';
            document.getElementById('heroSliderTitle').value = slider.title || '';
            document.getElementById('heroSliderSubtitle').value = slider.subtitle || '';
            document.getElementById('heroSliderButton1Text').value = slider.button1_text || '';
            setHeroUrlFieldValue('heroSliderButton1Url', 'heroSliderButton1Custom', slider.button1_url || '');
            document.getElementById('heroSliderButton2Text').value = slider.button2_text || '';
            setHeroUrlFieldValue('heroSliderButton2Url', 'heroSliderButton2Custom', slider.button2_url || '');
            document.getElementById('heroSliderImageUrl').value = slider.image_url || '';
            setHeroSliderPreview(slider.image_url || '');
            document.getElementById('heroSliderStat1Icon').value = slider.stat1_icon || '';
            document.getElementById('heroSliderStat1Text').value = slider.stat1_text || '';
            document.getElementById('heroSliderStat2Icon').value = slider.stat2_icon || '';
            document.getElementById('heroSliderStat2Text').value = slider.stat2_text || '';
            document.getElementById('heroSliderDisplayOrder').value = slider.display_order || 0;
            document.getElementById('heroSliderStatus').value = slider.status || 'active';

            document.getElementById('heroSliderModalTitle').textContent = 'Edit Hero Slider';
            document.getElementById('heroSliderModal').style.display = 'block';
            document.getElementById('heroSliderModalOverlay').style.display = 'block';
            document.body.style.overflow = 'hidden';
        }

        async function saveHeroSlider() {
            const id = document.getElementById('heroSliderId').value;
            try {
                const formData = new FormData();
                const button1Url = getHeroUrlFieldValue('heroSliderButton1Url', 'heroSliderButton1Custom');
                const button2Url = getHeroUrlFieldValue('heroSliderButton2Url', 'heroSliderButton2Custom');
                const uploadedHeroImage = await uploadHeroSliderImageIfNeeded();
                const imageUrlValue = uploadedHeroImage || document.getElementById('heroSliderImageUrl').value.trim();

                formData.append('action', id ? 'update' : 'add');
                if (id) formData.append('id', id);
                formData.append('tag', document.getElementById('heroSliderTag').value);
                formData.append('title', document.getElementById('heroSliderTitle').value);
                formData.append('subtitle', document.getElementById('heroSliderSubtitle').value);
                formData.append('button1_text', document.getElementById('heroSliderButton1Text').value);
                formData.append('button1_url', button1Url);
                formData.append('button2_text', document.getElementById('heroSliderButton2Text').value);
                formData.append('button2_url', button2Url);
                formData.append('image_url', imageUrlValue);
                formData.append('stat1_icon', document.getElementById('heroSliderStat1Icon').value);
                formData.append('stat1_text', document.getElementById('heroSliderStat1Text').value);
                formData.append('stat2_icon', document.getElementById('heroSliderStat2Icon').value);
                formData.append('stat2_text', document.getElementById('heroSliderStat2Text').value);
                formData.append('display_order', document.getElementById('heroSliderDisplayOrder').value);
                formData.append('status', document.getElementById('heroSliderStatus').value);

                const response = await fetch('../api/hero-slider.php', {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();

                if (data.success) {
                    showNotification(data.message, 'success');
                    closeHeroSliderModal();
                    loadHeroSliders();
                } else {
                    showNotification(data.message || 'Error saving hero slider', 'error');
                }
            } catch (error) {
                console.error('Error saving hero slider:', error);
                showNotification('Error saving hero slider: ' + error.message, 'error');
            }
        }

        function handleHeroUrlSelectChange(selectId, customInputId) {
            const selectEl = document.getElementById(selectId);
            const customEl = document.getElementById(customInputId);
            if (!selectEl || !customEl) return;
            const isCustom = selectEl.value === '__custom__';
            customEl.style.display = isCustom ? 'block' : 'none';
            if (!isCustom) customEl.value = '';
        }

        function setHeroUrlFieldValue(selectId, customInputId, urlValue) {
            const selectEl = document.getElementById(selectId);
            const customEl = document.getElementById(customInputId);
            if (!selectEl || !customEl) return;
            const safeValue = String(urlValue || '').trim();
            if (!safeValue) {
                selectEl.value = '';
                customEl.value = '';
                customEl.style.display = 'none';
                return;
            }
            if (HERO_PAGE_OPTIONS.includes(safeValue)) {
                selectEl.value = safeValue;
                customEl.value = '';
                customEl.style.display = 'none';
                return;
            }
            selectEl.value = '__custom__';
            customEl.value = safeValue;
            customEl.style.display = 'block';
        }

        function getHeroUrlFieldValue(selectId, customInputId) {
            const selectEl = document.getElementById(selectId);
            const customEl = document.getElementById(customInputId);
            if (!selectEl || !customEl) return '';
            if (selectEl.value === '__custom__') {
                return String(customEl.value || '').trim();
            }
            return String(selectEl.value || '').trim();
        }

        function setHeroSliderPreview(imagePath) {
            const preview = document.getElementById('heroSliderImagePreview');
            if (!preview) return;
            const resolvedPath = normalizeDashboardImagePath(imagePath || '');
            if (!resolvedPath) {
                preview.style.display = 'none';
                preview.removeAttribute('src');
                return;
            }
            preview.src = resolvedPath;
            preview.style.display = 'block';
        }

        function previewHeroSliderImage(event) {
            const file = event?.target?.files?.[0];
            if (!file) {
                setHeroSliderPreview(document.getElementById('heroSliderImageUrl').value || '');
                return;
            }
            const preview = document.getElementById('heroSliderImagePreview');
            if (!preview) return;
            const objectUrl = URL.createObjectURL(file);
            preview.src = objectUrl;
            preview.style.display = 'block';
            preview.onload = () => URL.revokeObjectURL(objectUrl);
        }

        async function uploadHeroSliderImageIfNeeded() {
            const fileInput = document.getElementById('heroSliderImageFile');
            if (!fileInput || !fileInput.files || !fileInput.files[0]) {
                return '';
            }
            const uploadData = new FormData();
            uploadData.append('image', fileInput.files[0]);

            const uploadResponse = await fetch('../api/hero-slider-upload-image.php', {
                method: 'POST',
                body: uploadData
            });
            const uploadJson = await uploadResponse.json();
            if (!uploadResponse.ok || !uploadJson.success) {
                throw new Error(uploadJson.message || 'Failed to upload hero image');
            }
            document.getElementById('heroSliderImageUrl').value = uploadJson.image_url || '';
            setHeroSliderPreview(uploadJson.image_url || '');
            return uploadJson.image_url || '';
        }

        async function deleteHeroSlider(id) {
            if (!confirm('Are you sure you want to delete this hero slider? This action cannot be undone.')) {
                return;
            }

            try {
                const formData = new FormData();
                formData.append('action', 'delete');
                formData.append('id', id);

                const response = await fetch('../api/hero-slider.php', {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();

                if (data.success) {
                    showNotification(data.message, 'success');
                    loadHeroSliders();
                } else {
                    showNotification(data.message || 'Error deleting hero slider', 'error');
                }
            } catch (error) {
                console.error('Error deleting hero slider:', error);
                showNotification('Error deleting hero slider: ' + error.message, 'error');
            }
        }

        function escapeHtml(text) {
            if (!text) return '';
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        function showNotification(message, type = 'info') {
            const notification = document.createElement('div');
            notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                padding: 15px 20px;
                border-radius: 5px;
                background: ${type === 'success' ? '#d4edda' : type === 'error' ? '#f8d7da' : '#d1ecf1'};
                color: ${type === 'success' ? '#155724' : type === 'error' ? '#721c24' : '#0c5460'};
                border: 1px solid ${type === 'success' ? '#c3e6cb' : type === 'error' ? '#f5c6cb' : '#bee5eb'};
                z-index: 1000;
                animation: slideIn 0.3s ease;
            `;
            notification.textContent = message;
            document.body.appendChild(notification);

            setTimeout(() => {
                notification.style.animation = 'slideOut 0.3s ease';
                setTimeout(() => notification.remove(), 300);
            }, 3000);
        }

        // Add CSS animation for notifications
        const style = document.createElement('style');
        style.textContent = `
            @keyframes slideIn {
                from { transform: translateX(400px); opacity: 0; }
                to { transform: translateX(0); opacity: 1; }
            }
            @keyframes slideOut {
                from { transform: translateX(0); opacity: 1; }
                to { transform: translateX(400px); opacity: 0; }
            }
        `;
        document.head.appendChild(style);

        // Initialize hero sliders when hero slider panel is shown
        const originalShowPanel = window.showPanel;
        window.showPanel = function(panelId) {
            originalShowPanel(panelId);
            if (panelId === 'heroSliderPanel') {
                loadHeroSliders();
            }
        };

        // Load hero sliders on page load
        document.addEventListener('DOMContentLoaded', () => {
            if (currentSection === 'heroSliderPanel') {
                loadHeroSliders();
            }
        });
    </script>

</body>
</html>
