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

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

$customer_id = $_SESSION['user_id'];
$customer_name = $_SESSION['user_name'];
$customer_email = $_SESSION['user_email'] ?? '';

// CRITICAL: Ensure all required columns exist BEFORE any queries
// This must happen immediately after connection

// Fix appointments table
$check = $conn->query("SHOW COLUMNS FROM appointments LIKE 'user_id'");
if (!$check || $check->num_rows === 0) {
    @$conn->query("ALTER TABLE appointments ADD COLUMN user_id INT AFTER id");
}

$check = $conn->query("SHOW COLUMNS FROM appointments LIKE 'appointment_date'");
if (!$check || $check->num_rows === 0) {
    @$conn->query("ALTER TABLE appointments ADD COLUMN appointment_date DATE AFTER property_id");
}

// Fix inquiries table - add all required columns one by one
$inquiries_columns = ['customer_id', 'property_id', 'assigned_to', 'broker_id', 'status', 'message', 'created_at', 'updated_at'];
foreach ($inquiries_columns as $col) {
    $check = $conn->query("SHOW COLUMNS FROM inquiries LIKE '$col'");
    if (!$check || $check->num_rows === 0) {
        if ($col === 'customer_id') @$conn->query("ALTER TABLE inquiries ADD COLUMN customer_id INT AFTER id");
        elseif ($col === 'property_id') @$conn->query("ALTER TABLE inquiries ADD COLUMN property_id INT AFTER customer_id");
        elseif ($col === 'assigned_to') @$conn->query("ALTER TABLE inquiries ADD COLUMN assigned_to INT AFTER property_id");
        elseif ($col === 'broker_id') @$conn->query("ALTER TABLE inquiries ADD COLUMN broker_id INT AFTER assigned_to");
        elseif ($col === 'status') @$conn->query("ALTER TABLE inquiries ADD COLUMN status VARCHAR(50) DEFAULT 'pending' AFTER broker_id");
        elseif ($col === 'message') @$conn->query("ALTER TABLE inquiries ADD COLUMN message TEXT AFTER status");
        elseif ($col === 'created_at') @$conn->query("ALTER TABLE inquiries ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP");
        elseif ($col === 'updated_at') @$conn->query("ALTER TABLE inquiries ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP");
    }
}

// Now fetch statistics - columns should definitely exist by now
$saved_count = 0;
$visits_count = 0;
$inquiries_count = 0;
$properties = null;
$appointments = null;
$inquiries = null;

// Get saved properties count
$result = $conn->query("SELECT COUNT(*) as count FROM properties LIMIT 1");
if ($result) {
    $saved_result = $result->fetch_assoc();
    $saved_count = $saved_result['count'] ?? 0;
}

// Get appointments count for this customer
try {
    $stmt = $conn->prepare("SELECT COUNT(*) as count FROM appointments WHERE customer_id = ?");
    if ($stmt) {
        $stmt->bind_param('i', $customer_id);
        $stmt->execute();
        $visits_result = $stmt->get_result()->fetch_assoc();
        $visits_count = $visits_result['count'] ?? 0;
        $stmt->close();
    }
} catch (Exception $e) {
    $visits_count = 0;
}

// Get inquiries count for this customer
try {
    $stmt = $conn->prepare("SELECT COUNT(*) as count FROM inquiries WHERE customer_id = ?");
    if ($stmt) {
        $stmt->bind_param('i', $customer_id);
        $stmt->execute();
        $inquiries_result = $stmt->get_result()->fetch_assoc();
        $inquiries_count = $inquiries_result['count'] ?? 0;
        $stmt->close();
    }
} catch (Exception $e) {
    $inquiries_count = 0;
}

// Get recent properties for favorites
try {
    $stmt = $conn->prepare("SELECT id, title, city, price, bedrooms, bathrooms, image_url FROM properties ORDER BY created_at DESC LIMIT 5");
    if ($stmt) {
        $stmt->execute();
        $properties = $stmt->get_result();
    }
} catch (Exception $e) {
    $properties = null;
}

// Get upcoming appointments
try {
    $stmt = $conn->prepare("SELECT a.id, p.title, a.appointment_date, a.status FROM appointments a LEFT JOIN properties p ON a.property_id = p.id WHERE a.customer_id = ? AND a.appointment_date >= CURDATE() ORDER BY a.appointment_date DESC LIMIT 5");
    if ($stmt) {
        $stmt->bind_param('i', $customer_id);
        $stmt->execute();
        $appointments = $stmt->get_result();
    }
} catch (Exception $e) {
    $appointments = null;
}

// Get recent inquiries
try {
    $stmt = $conn->prepare("SELECT i.id, p.title, i.status, i.created_at FROM inquiries i LEFT JOIN properties p ON i.property_id = p.id WHERE i.customer_id = ? ORDER BY i.created_at DESC LIMIT 5");
    if ($stmt) {
        $stmt->bind_param('i', $customer_id);
        $stmt->execute();
        $inquiries = $stmt->get_result();
    }
} catch (Exception $e) {
    $inquiries = null;
}

$active_section = $_GET['section'] ?? 'overview';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Customer 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; }

        /* Layout */
        .dashboard-wrapper { display: flex; min-height: 100vh; }
        .sidebar { width: 280px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px 20px; position: fixed; left: 0; top: 0; height: 100vh; overflow-y: auto; z-index: 1001; }
        .main-content { margin-left: 280px; flex: 1; }

        /* Sidebar */
        .sidebar-logo { font-size: 22px; font-weight: 700; margin-bottom: 30px; display: flex; align-items: center; gap: 10px; }
        .sidebar-profile { background: rgba(255,255,255,0.1); padding: 20px; border-radius: 10px; margin-bottom: 30px; text-align: center; }
        .sidebar-profile-avatar { width: 60px; height: 60px; border-radius: 50%; background: rgba(255,255,255,0.3); display: flex; align-items: center; justify-content: center; font-size: 28px; margin: 0 auto 10px; }
        .sidebar-profile-name { font-weight: 600; margin-bottom: 5px; }
        .sidebar-profile-email { font-size: 12px; opacity: 0.8; }
        .sidebar-menu { list-style: none; margin-bottom: 30px; }
        .sidebar-menu li { margin-bottom: 10px; }
        .sidebar-menu a { color: white; text-decoration: none; display: flex; align-items: center; gap: 12px; padding: 12px 15px; border-radius: 8px; transition: all 0.3s; opacity: 0.8; }
        .sidebar-menu a:hover, .sidebar-menu a.active { opacity: 1; background: rgba(255,255,255,0.2); }
        .sidebar-stat { background: rgba(255,255,255,0.1); padding: 15px; border-radius: 8px; margin-bottom: 10px; }
        .sidebar-stat-label { font-size: 12px; opacity: 0.8; margin-bottom: 5px; }
        .sidebar-stat-number { font-size: 24px; font-weight: 700; }

        /* Header */
        .top-header { background: white; padding: 20px 30px; box-shadow: 0 2px 5px rgba(0,0,0,0.08); display: flex; justify-content: space-between; align-items: center; }
        .top-header h1 { font-size: 26px; color: #333; margin: 0; }
        .user-menu { display: flex; align-items: center; gap: 20px; }
        .logout-btn { background: #dc3545; color: white; border: none; padding: 8px 16px; border-radius: 5px; cursor: pointer; text-decoration: none; }

        /* Content */
        .content { padding: 30px; }
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 20px; margin-bottom: 30px; }
        .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; text-align: center; }
        .stat-card h3 { font-size: 12px; color: #999; text-transform: uppercase; margin-bottom: 10px; }
        .stat-card .number { font-size: 36px; font-weight: 700; color: #667eea; }

        /* Panels */
        .panel { background: white; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.08); padding: 25px; margin-bottom: 25px; }
        .panel h2 { font-size: 20px; color: #333; margin-bottom: 20px; }
        .panel-description { color: #999; font-size: 14px; margin-bottom: 20px; }

        /* Items */
        .item-card { background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 12px; border-left: 3px solid #667eea; }
        .item-title { font-weight: 600; color: #333; }
        .item-meta { font-size: 13px; color: #999; margin-top: 5px; }
        .item-status { display: inline-block; padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: 600; margin-top: 8px; }
        .status-pending { background: #fff3cd; color: #856404; }
        .status-confirmed { background: #d1ecf1; color: #0c5460; }
        .status-responded { background: #d4edda; color: #155724; }
        .status-new { background: #dbeafe; color: #1e40af; }
        .status-reviewed { background: #dcfce7; color: #166534; }
        .feedback-rating { font-size: 14px; color: #f59e0b; margin-top: 8px; }

        /* Forms */
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; font-weight: 600; color: #333; margin-bottom: 5px; }
        .form-group input, .form-group textarea, .form-group select { width: 100%; padding: 10px 12px; border: 1px solid #ddd; border-radius: 5px; font-family: 'Poppins', sans-serif; }
        .form-group input:focus, .form-group textarea:focus { outline: none; border-color: #667eea; box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); }

        /* Buttons */
        .btn { padding: 10px 20px; background: #667eea; color: white; border: none; border-radius: 5px; cursor: pointer; text-decoration: none; display: inline-block; transition: all 0.3s; }
        .btn:hover { background: #764ba2; transform: translateY(-2px); }
        .btn-secondary { background: #6c757d; }
        .btn-small { padding: 6px 12px; font-size: 12px; }

        /* Responsive */
        .menu-toggle { display: none; background: #667eea; color: white; border: none; padding: 12px 16px; border-radius: 5px; cursor: pointer; font-size: 18px; font-weight: 600; z-index: 1002; }
        .menu-toggle:hover { background: #764ba2; }

        /* Mobile Overlay */
        .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.5); z-index: 999; }
        .sidebar-overlay.active { display: block; }

        @media (max-width: 1024px) {
            .sidebar { transform: translateX(-100%); transition: transform 0.3s ease-in-out; }
            .sidebar.active { transform: translateX(0); }
            .main-content { margin-left: 0; }
            .menu-toggle { display: block; }
        }

        @media (max-width: 768px) {
            .dashboard-wrapper { flex-direction: column; }
            .sidebar { width: 280px; max-width: 280px; transform: translateX(-100%); transition: transform 0.3s ease-in-out; }
            .sidebar.active { transform: translateX(0); }
            .main-content { margin-left: 0; width: 100%; }
            .menu-toggle { display: block; padding: 10px 14px; font-size: 16px; }
            .top-header { padding: 15px 20px; flex-wrap: wrap; }
            .top-header h1 { font-size: 20px; flex-grow: 1; }
            .stats-grid { grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 15px; }
            .content { padding: 20px 15px; }
            .panel { padding: 20px 15px; margin-bottom: 20px; }
            .stat-card { padding: 20px 15px; }
            .stat-card h3 { font-size: 11px; }
            .stat-card .number { font-size: 28px; }
            .sidebar-profile { padding: 15px; margin-bottom: 20px; }
            .sidebar-profile-avatar { width: 50px; height: 50px; font-size: 24px; }
            .sidebar-menu li { margin-bottom: 8px; }
            .sidebar-menu a { padding: 10px 12px; font-size: 14px; }
            .item-card { padding: 12px; margin-bottom: 10px; }
            .item-title { font-size: 14px; }
            .item-meta { font-size: 12px; }
        }

        @media (max-width: 640px) {
            .top-header { padding: 12px 15px; }
            .top-header h1 { font-size: 18px; }
            .stats-grid { grid-template-columns: 1fr; gap: 12px; margin-bottom: 20px; }
            .stat-card { padding: 18px 15px; }
            .stat-card .number { font-size: 24px; }
            .content { padding: 15px 12px; }
            .panel { padding: 18px 12px; }
            .btn { padding: 9px 16px; font-size: 14px; }
            .btn-small { padding: 6px 10px; font-size: 11px; }
            .sidebar-logo { font-size: 18px; margin-bottom: 20px; }
            .sidebar-stat-number { font-size: 20px; }
        }

        @media (max-width: 480px) {
            .dashboard-wrapper { flex-direction: column; }
            .sidebar { width: 100%; max-width: auto; }
            .top-header { padding: 10px 12px; gap: 8px; }
            .top-header h1 { font-size: 16px; }
            .menu-toggle { padding: 8px 12px; font-size: 14px; }
            .stats-grid { grid-template-columns: 1fr; gap: 10px; }
            .stat-card { padding: 16px 12px; text-align: center; }
            .stat-card h3 { font-size: 10px; }
            .stat-card .number { font-size: 22px; }
            .content { padding: 12px 10px; }
            .panel { padding: 16px 12px; margin-bottom: 15px; }
            .panel h2 { font-size: 18px; margin-bottom: 15px; }
            .item-card { padding: 10px; margin-bottom: 8px; }
            .item-title { font-size: 13px; }
            .item-meta { font-size: 11px; }
            .btn { padding: 8px 14px; font-size: 13px; }
            .form-group label { font-size: 14px; margin-bottom: 4px; }
            .form-group input, .form-group textarea, .form-group select { padding: 8px 10px; font-size: 14px; }
            .sidebar-profile { padding: 12px; }
            .sidebar-profile-avatar { width: 45px; height: 45px; font-size: 20px; }
            .sidebar-logo { font-size: 16px; }
            .sidebar-menu a { padding: 9px 10px; font-size: 13px; gap: 8px; }
        }

        /* Favorites Grid */
        .favorites-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 20px; margin-top: 20px; }
        .property-card { background: white; border-radius: 10px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1); transition: all 0.3s ease; animation: fadeInCard 0.3s ease-in-out; }
        .property-card:hover { transform: translateY(-5px); box-shadow: 0 5px 15px rgba(0,0,0,0.15); }
        @keyframes fadeInCard {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        .property-image { width: 100%; height: 200px; background: #e8e8e8 url(../assets/img/logo.png) center/contain no-repeat; object-fit: cover; display: block; }
        .property-info { padding: 15px; }
        .property-title { font-weight: 600; color: #333; font-size: 15px; margin-bottom: 8px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .property-details { font-size: 12px; color: #666; line-height: 1.6; }
        .property-details-row { display: flex; justify-content: space-between; margin-bottom: 8px; }
        .property-price { font-size: 16px; font-weight: 700; color: #667eea; margin: 10px 0; }
        .property-actions { display: flex; gap: 8px; margin-top: 12px; }
        .property-actions .btn { flex: 1; font-size: 12px; padding: 8px 10px; }
        .btn-remove { background: #dc3545; }
        .btn-remove:hover { background: #c82333; }
        .btn-schedule { background: #667eea; }
        .btn-schedule:hover { background: #764ba2; }
        
        @media (max-width: 1200px) {
            .favorites-grid { grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); gap: 18px; }
            .property-image { height: 180px; }
            .property-actions .btn { font-size: 11px; padding: 7px 9px; }
        }
        
        @media (max-width: 1024px) {
            .favorites-grid { grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 15px; }
            .property-image { height: 160px; }
            .property-info { padding: 13px; }
            .property-title { font-size: 13px; }
            .property-price { font-size: 14px; }
            .property-actions { gap: 6px; }
            .property-actions .btn { font-size: 10px; padding: 6px 8px; }
        }
        
        @media (max-width: 768px) {
            .favorites-grid { grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); gap: 12px; }
            .property-image { height: 140px; }
            .property-info { padding: 11px; }
            .property-title { font-size: 12px; }
            .property-details { font-size: 10px; }
            .property-price { font-size: 13px; }
            .property-actions { gap: 5px; }
            .property-actions .btn { font-size: 9px; padding: 5px 7px; }
        }
        
        @media (max-width: 640px) {
            .favorites-grid { grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 10px; }
            .property-image { height: 120px; }
            .property-info { padding: 10px; }
            .property-title { font-size: 11px; }
            .property-details { font-size: 9px; }
            .property-price { font-size: 12px; }
            .property-details-row { margin-bottom: 5px; }
            .property-actions { gap: 4px; margin-top: 8px; }
            .property-actions .btn { font-size: 8px; padding: 4px 6px; }
        }
        
        @media (max-width: 480px) {
            .favorites-grid { grid-template-columns: repeat(auto-fill, minmax(110px, 1fr)); gap: 8px; }
            .property-image { height: 100px; }
            .property-info { padding: 8px; }
            .property-title { font-size: 10px; }
            .property-details { font-size: 8px; }
            .property-price { font-size: 11px; margin: 6px 0; }
            .property-details-row { margin-bottom: 3px; }
            .property-actions { gap: 3px; margin-top: 6px; }
            .property-actions .btn { font-size: 7px; padding: 3px 5px; }
        }

        /* Hide sections */
        .section { display: none; }
        .section.active { display: block; }
    </style>
</head>
<body>
  
    <!-- Sidebar Overlay (Mobile) -->
    <div class="sidebar-overlay" id="sidebarOverlay"></div>

    <!-- Sidebar -->
    <div class="dashboard-wrapper">
        <div class="sidebar" id="sidebar">
            <div class="sidebar-logo">
                <i class="fas fa-home"></i> Zemaraim
            </div>

            <!-- Profile Section -->
            <div class="sidebar-profile">
                <div class="sidebar-profile-avatar"><?php echo strtoupper(substr($customer_name, 0, 1)); ?></div>
                <div class="sidebar-profile-name"><?php echo htmlspecialchars($customer_name); ?></div>
                <div class="sidebar-profile-email"><?php echo htmlspecialchars($customer_email); ?></div>
            </div>

            <!-- Navigation Menu -->
            <ul class="sidebar-menu">
                <li><a href="../index.php" class="fas fa-home"> Home</a></li>
                <li><a href="?section=overview" class="<?php echo $active_section === 'overview' ? 'active' : ''; ?>"><i class="fas fa-chart-line"></i> Dashboard</a></li>
                <li><a href="?section=profile" class="<?php echo $active_section === 'profile' ? 'active' : ''; ?>"><i class="fas fa-user"></i> Profile</a></li>
                <li><a href="?section=favorites" class="<?php echo $active_section === 'favorites' ? 'active' : ''; ?>"><i class="fas fa-heart"></i> Favorites</a></li>
                <li><a href="?section=appointments" class="<?php echo $active_section === 'appointments' ? 'active' : ''; ?>"><i class="fas fa-calendar"></i> Appointments</a></li>
                <li><a href="?section=schedule" class="<?php echo $active_section === 'schedule' ? 'active' : ''; ?>"><i class="fas fa-clock"></i> Schedule Visit</a></li>
                <li><a href="?section=inquiries" class="<?php echo $active_section === 'inquiries' ? 'active' : ''; ?>"><i class="fas fa-comments"></i> Inquiries</a></li>
                <li><a href="?section=feedback" class="<?php echo $active_section === 'feedback' ? 'active' : ''; ?>"><i class="fas fa-star"></i> Feedback</a></li>
            </ul>

            <!-- Statistics Sidebar -->
            <!-- <div style="border-top: 1px solid rgba(255,255,255,0.2); padding-top: 20px;">
                <div class="sidebar-stat">
                    <div class="sidebar-stat-label">❤️ Favorites</div>
                    <div class="sidebar-stat-number"><?php echo $saved_count; ?></div>
                </div>
                <div class="sidebar-stat">
                    <div class="sidebar-stat-label">📅 Appointments</div>
                    <div class="sidebar-stat-number"><?php echo $visits_count; ?></div>
                </div>
                <div class="sidebar-stat">
                    <div class="sidebar-stat-label">💬 Inquiries</div>
                    <div class="sidebar-stat-number"><?php echo $inquiries_count; ?></div>
                </div>
            </div> -->

            <!-- Logout -->
            <a href="../logout.php" style="display: block; margin-top: 30px; color: white; text-decoration: none; text-align: center; padding: 10px; background: rgba(255,255,255,0.1); border-radius: 5px;"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>

        <!-- Main Content -->
        <div class="main-content">
            <!-- Header -->
            <div class="top-header">
                <h1>🏠 Customer Dashboard</h1>
                <button class="menu-toggle"><i class="fas fa-bars"></i> Menu</button>
            </div>

            <!-- Content -->
            <div class="content">

                <!-- OVERVIEW SECTION -->
                <div class="section <?php echo $active_section === 'overview' ? 'active' : ''; ?>">
                    <h2 style="margin-bottom: 30px;">📊 Dashboard Overview</h2>
                    
                    <!-- Stats Grid -->
                    <div class="stats-grid">
                        <div class="stat-card">
                            <h3>❤️ Favorite Properties</h3>
                            <div class="number"><?php echo $saved_count; ?></div>
                        </div>
                        <div class="stat-card">
                            <h3>📅 Scheduled Visits</h3>
                            <div class="number"><?php echo $visits_count; ?></div>
                        </div>
                        <div class="stat-card">
                            <h3>💬 Inquiries</h3>
                            <div class="number"><?php echo $inquiries_count; ?></div>
                        </div>
                    </div>

                    <!-- Recent Properties -->
                    <div class="panel">
                        <h2>🏡 Recent Properties</h2>
                        <p class="panel-description">Recently added properties you might like</p>
                        <?php if (is_object($properties) && $properties->num_rows > 0): ?>
                            <?php while ($prop = $properties->fetch_assoc()): ?>
                                <div class="item-card">
                                    <div class="item-title"><?php echo htmlspecialchars($prop['title']); ?></div>
                                    <div class="item-meta">📍 <?php echo htmlspecialchars($prop['city']); ?> • 💰 $<?php echo number_format($prop['price']); ?></div>
                                    <div class="item-meta">🛏️ <?php echo $prop['bedrooms']; ?> Bed • 🚿 <?php echo $prop['bathrooms']; ?> Bath</div>
                                    <button class="btn btn-small" style="margin-top: 10px;"><i class="fas fa-heart"></i> Add to Favorites</button>
                                </div>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <p style="color: #999;">No properties available yet.</p>
                        <?php endif; ?>
                    </div>

                    <!-- Upcoming Appointments -->
                    <div class="panel">
                        <h2>📅 Upcoming Visits</h2>
                        <p class="panel-description">Your scheduled property viewings</p>
                        <?php if (is_object($appointments) && $appointments->num_rows > 0): ?>
                            <?php while ($apt = $appointments->fetch_assoc()): ?>
                                <div class="item-card">
                                    <div class="item-title"><?php echo htmlspecialchars($apt['title'] ?? 'Property'); ?></div>
                                    <div class="item-meta">📅 <?php echo date('M d, Y', strtotime($apt['appointment_date'])); ?></div>
                                    <span class="item-status status-confirmed"><i class="fas fa-check-circle"></i> <?php echo ucfirst($apt['status']); ?></span>
                                </div>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <p style="color: #999;">No scheduled visits yet. <a href="?section=schedule">Schedule a visit</a></p>
                        <?php endif; ?>
                    </div>

                    <!-- Recent Inquiries -->
                    <div class="panel">
                        <h2>💬 Your Inquiries</h2>
                        <p class="panel-description">Track your property inquiries</p>
                        <?php if (is_object($inquiries) && $inquiries->num_rows > 0): ?>
                            <?php while ($inq = $inquiries->fetch_assoc()): ?>
                                <div class="item-card">
                                    <div class="item-title"><?php echo htmlspecialchars($inq['title'] ?? 'Inquiry'); ?></div>
                                    <div class="item-meta">📧 Sent: <?php echo date('M d, Y', strtotime($inq['created_at'])); ?></div>
                                    <span class="item-status status-responded"><i class="fas fa-check"></i> <?php echo ucfirst($inq['status']); ?></span>
                                </div>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <p style="color: #999;">You haven't sent any inquiries yet.</p>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- PROFILE SECTION -->
                <div class="section <?php echo $active_section === 'profile' ? 'active' : ''; ?>" data-section="profile">
                    <div class="panel">
                        <h2>👤 Update Profile</h2>
                        <p class="panel-description">Update your personal information</p>
                        <form method="POST" action="">
                            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px;">
                                <div class="form-group">
                                    <label for="name">Full Name</label>
                                    <input type="text" id="name" name="name" value="<?php echo htmlspecialchars($customer_name); ?>" required>
                                </div>
                                <div class="form-group">
                                    <label for="email">Email</label>
                                    <input type="email" id="email" name="email" value="<?php echo htmlspecialchars($customer_email); ?>" required>
                                </div>
                                <div class="form-group">
                                    <label for="phone">Phone</label>
                                    <input type="tel" id="phone" name="phone" placeholder="+1 (555) 123-4567">
                                </div>
                                <div class="form-group">
                                    <label for="city">City</label>
                                    <input type="text" id="city" name="city" placeholder="New York">
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="bio">Bio</label>
                                <textarea id="bio" name="bio" rows="4" placeholder="Tell us about yourself..."></textarea>
                            </div>
                            <button type="submit" class="btn"><i class="fas fa-save"></i> Save Changes</button>
                        </form>
                    </div>
                </div>

                <!-- FAVORITES SECTION -->
                <div class="section <?php echo $active_section === 'favorites' ? 'active' : ''; ?>" data-section="favorites">
                    <div class="panel">
                        <!-- Content will be loaded dynamically via JavaScript -->
                    </div>
                </div>

                <!-- APPOINTMENTS SECTION -->
                <div class="section <?php echo $active_section === 'appointments' ? 'active' : ''; ?>" data-section="appointments">
                    <div class="panel">
                        <h2>📅 My Appointments</h2>
                        <p class="panel-description">All your scheduled property visits</p>
                        <?php if (is_object($appointments) && $appointments->num_rows > 0): ?>
                            <?php while ($apt = $appointments->fetch_assoc()): ?>
                                <div class="item-card">
                                    <div class="item-title"><?php echo htmlspecialchars($apt['title'] ?? 'Property'); ?></div>
                                    <div class="item-meta">📅 <?php echo date('M d, Y h:i A', strtotime($apt['appointment_date'])); ?></div>
                                    <span class="item-status status-confirmed"><i class="fas fa-check-circle"></i> <?php echo ucfirst($apt['status']); ?></span>
                                </div>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <p style="color: #999;">No appointments scheduled.</p>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- SCHEDULE VISIT SECTION -->
                <div class="section <?php echo $active_section === 'schedule' ? 'active' : ''; ?>" data-section="schedule">
                    <div class="panel">
                        <h2>📅 Schedule New Visit</h2>
                        <p class="panel-description">Book a property viewing appointment</p>
                        <form method="POST" action="">
                            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px;">
                                <div class="form-group">
                                    <label for="property">Select Property</label>
                                    <select id="property" name="property_id" required>
                                        <option value="">-- Choose Property --</option>
                                        <?php 
                                        $conn->query("SELECT id, title FROM properties LIMIT 10")->fetch_all();
                                        $props = $conn->query("SELECT id, title FROM properties LIMIT 10");
                                        while ($p = $props->fetch_assoc()): ?>
                                            <option value="<?php echo $p['id']; ?>"><?php echo htmlspecialchars($p['title']); ?></option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="visit_date">Preferred Date</label>
                                    <input type="date" id="visit_date" name="appointment_date" required>
                                </div>
                                <div class="form-group">
                                    <label for="visit_time">Preferred Time</label>
                                    <input type="time" id="visit_time" name="appointment_time" required>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="message">Message to Broker</label>
                                <textarea id="message" name="message" rows="4" placeholder="Any special requests or questions?"></textarea>
                            </div>
                            <button type="submit" class="btn"><i class="fas fa-calendar-check"></i> Schedule Visit</button>
                        </form>
                    </div>
                </div>

                <!-- INQUIRIES SECTION -->
                <div class="section <?php echo $active_section === 'inquiries' ? 'active' : ''; ?>" data-section="inquiries">
                    <div class="panel">
                        <h2>💬 Send Inquiry</h2>
                        <p class="panel-description">Ask questions about properties</p>
                        <form method="POST" action="">
                            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px;">
                                <div class="form-group">
                                    <label for="inq_property">Property</label>
                                    <select id="inq_property" name="inq_property_id" required>
                                        <option value="">-- Choose Property --</option>
                                        <?php 
                                        $props = $conn->query("SELECT id, title FROM properties LIMIT 10");
                                        while ($p = $props->fetch_assoc()): ?>
                                            <option value="<?php echo $p['id']; ?>"><?php echo htmlspecialchars($p['title']); ?></option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="inq_phone">Your Phone</label>
                                    <input type="tel" id="inq_phone" name="phone" placeholder="+1 (555) 123-4567" required>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="inq_message">Your Inquiry</label>
                                <textarea id="inq_message" name="inq_message" rows="5" placeholder="Tell us your questions or concerns..." required></textarea>
                            </div>
                            <button type="submit" class="btn"><i class="fas fa-send"></i> Send Inquiry</button>
                        </form>
                    </div>

                    <div class="panel">
                        <h2>📧 Previous Inquiries</h2>
                        <p class="panel-description">Your inquiry history</p>
                        <div data-section="inquiries-list"></div>
                    </div>
                </div>

                <!-- FEEDBACK SECTION -->
                <div class="section <?php echo $active_section === 'feedback' ? 'active' : ''; ?>" data-section="feedback">
                    <div class="panel">
                        <h2>Customer Feedback</h2>
                        <p class="panel-description">Share your feedback with admin in real-time.</p>
                        <form id="feedbackForm" method="POST" action="">
                            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 15px;">
                                <div class="form-group">
                                    <label for="feedback_subject">Subject</label>
                                    <input type="text" id="feedback_subject" maxlength="180" placeholder="Ex: Service quality, platform issue" required>
                                </div>
                                <div class="form-group">
                                    <label for="feedback_rating">Rating</label>
                                    <select id="feedback_rating">
                                        <option value="">Select rating (optional)</option>
                                        <option value="5">5 - Excellent</option>
                                        <option value="4">4 - Good</option>
                                        <option value="3">3 - Average</option>
                                        <option value="2">2 - Poor</option>
                                        <option value="1">1 - Very Poor</option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="feedback_message">Message</label>
                                <textarea id="feedback_message" rows="5" minlength="10" placeholder="Write your feedback here..." required></textarea>
                            </div>
                            <button type="submit" class="btn"><i class="fas fa-paper-plane"></i> Submit Feedback</button>
                        </form>
                    </div>

                    <div class="panel">
                        <h2>Your Feedback History</h2>
                        <p class="panel-description">Recent feedback you have submitted</p>
                        <div data-section="feedback-list"></div>
                    </div>
                </div>

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

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

        const sidebar = document.getElementById('sidebar');
        const toggle = document.querySelector('.menu-toggle');
        const overlay = document.getElementById('sidebarOverlay');

        // Toggle sidebar on button click
        if (toggle) {
            toggle.addEventListener('click', function(e) {
                e.stopPropagation();
                sidebar.classList.toggle('active');
                overlay.classList.toggle('active');
            });
        }

        // Close sidebar when clicking overlay
        if (overlay) {
            overlay.addEventListener('click', function() {
                sidebar.classList.remove('active');
                overlay.classList.remove('active');
            });
        }

        // Close sidebar when clicking a link
        document.querySelectorAll('.sidebar-menu a').forEach(link => {
            link.addEventListener('click', function() {
                sidebar.classList.remove('active');
                overlay.classList.remove('active');
            });
        });

        // Close sidebar when clicking outside on desktop
        document.addEventListener('click', function(event) {
            const isDesktop = window.innerWidth > 768;
            if (!isDesktop) {
                if (!sidebar.contains(event.target) && !toggle.contains(event.target)) {
                    sidebar.classList.remove('active');
                    overlay.classList.remove('active');
                }
            }
        });

        // Handle window resize
        window.addEventListener('resize', function() {
            if (window.innerWidth > 768) {
                sidebar.classList.remove('active');
                overlay.classList.remove('active');
            }
        });

        // ===== REAL-TIME INTEGRATION FUNCTIONS =====
        
        // Real-time favorites update
        async function loadFavorites() {
            try {
                const response = await fetch('../api/get-favorites.php');
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const data = await response.json();
                if (data.success && data.favorites) {
                    updateFavoritesUI(data.favorites);
                } else {
                    console.warn('Error loading favorites:', data.message || 'Unknown error');
                }
            } catch (error) {
                console.error('Error loading favorites:', error);
            }
        }

        function updateFavoritesUI(favorites) {
            const favoritesSection = document.querySelector('[data-section="favorites"]');
            if (!favoritesSection) {
                console.error('Favorites section not found');
                return;
            }
            
            const panelDiv = favoritesSection.querySelector('.panel');
            if (!panelDiv) {
                console.error('Panel div not found in favorites section');
                return;
            }

            let html = '<h2>❤️ My Favorite Properties</h2><p class="panel-description">Properties you\'ve saved for later</p>';
            let validCount = 0;
            
            if (favorites && Array.isArray(favorites) && favorites.length > 0) {
                html += '<div class="favorites-grid">';
                favorites.forEach(prop => {
                    // Check for valid property data with strict null/undefined checks
                    if (typeof prop !== 'object' || prop === null) {
                        console.warn('Invalid property object:', prop);
                        return;
                    }
                    if (typeof prop.id === 'undefined' || prop.id === null) {
                        console.warn('Property has no ID:', prop);
                        return;
                    }
                    
                    const propId = parseInt(prop.id);
                    if (isNaN(propId) || propId <= 0) {
                        console.warn('Invalid property ID:', prop.id);
                        return;
                    }
                    
                    // Fix image URL path - handle both relative and absolute URLs
                    let imageUrl = '../assets/img/logo.png';
                    if (prop.image_url && String(prop.image_url).trim()) {
                        const imgPath = String(prop.image_url).trim();
                        // If it's already a full path or starts with http, use as-is
                        if (imgPath.startsWith('http') || imgPath.startsWith('/')) {
                            imageUrl = imgPath;
                        } else {
                            // For relative paths like "properties-list-1.png", prepend correct path
                            // We're in dashboards/ folder, so go up one level to assets
                            imageUrl = '../assets/img/properties/' + imgPath.replace(/^.*\//, '');
                        }
                    }
                    
                    const title = prop.title ? String(prop.title).replace(/"/g, '&quot;') : 'Property';
                    const city = prop.city ? String(prop.city) : 'Location';
                    const bedrooms = Math.max(0, parseInt(prop.bedrooms) || 0);
                    const bathrooms = Math.max(0, parseInt(prop.bathrooms) || 0);
                    const price = Math.max(0, parseInt(prop.price) || 0);
                    
                    validCount++;
                    html += `<div class="property-card" data-property-id="${propId}">
                        <img src="${imageUrl}" alt="${title}" class="property-image" onerror="this.src='../assets/img/logo.png'; this.style.objectFit='contain';">
                        <div class="property-info">
                            <div class="property-title" title="${title}">${title}</div>
                            <div class="property-details">
                                <div class="property-details-row">
                                    <span>📍</span>
                                    <span>${city}</span>
                                </div>
                                <div class="property-details-row">
                                    <span>🛏️</span>
                                    <span>${bedrooms} Bed</span>
                                </div>
                                <div class="property-details-row">
                                    <span>🚿</span>
                                    <span>${bathrooms} Bath</span>
                                </div>
                            </div>
                            <div class="property-price">$${price.toLocaleString()}</div>
                            <div class="property-actions">
                                <button class="btn btn-schedule schedule-btn" data-property-id="${propId}" type="button"><i class="fas fa-calendar"></i> Schedule</button>
                                <button class="btn btn-remove remove-favorite-btn" data-property-id="${propId}" type="button"><i class="fas fa-trash"></i> Remove</button>
                            </div>
                        </div>
                    </div>`;
                });
                html += '</div>';
                console.log('Loaded ' + validCount + ' valid favorites out of ' + favorites.length);
            }
            
            if (validCount === 0) {
                html = '<h2>❤️ My Favorite Properties</h2><p class="panel-description">Properties you\'ve saved for later</p><p style="color: #999; text-align: center; padding: 40px 20px;">❤️ No favorites yet. Start liking properties!</p>';
            }
            
            panelDiv.innerHTML = html;
            setTimeout(() => {
                addScheduleListeners();
                addRemoveFavoriteListeners();
            }, 100);
        }

        // Remove favorite function
        async function removeFavorite(propertyId) {
            propertyId = parseInt(propertyId);
            if (!propertyId || propertyId <= 0) {
                alert('Invalid property ID');
                return;
            }
            
            if (!confirm('Are you sure you want to remove this property from favorites?')) {
                return;
            }
            
            try {
                const response = await fetch('../api/favorites-toggle.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ property_id: propertyId, action: 'remove' })
                });
                
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                
                const data = await response.json();
                if (data.success) {
                    console.log('Favorite removed successfully');
                    // Fade out the removed card before refreshing
                    const cardElement = document.querySelector(`[data-property-id="${propertyId}"]`);
                    if (cardElement) {
                        cardElement.style.opacity = '0';
                        cardElement.style.transform = 'scale(0.95)';
                        cardElement.style.transition = 'all 0.3s ease';
                    }
                    // Small delay to show fade effect, then reload
                    setTimeout(() => {
                        loadFavorites();
                        updateStats();
                    }, 300);
                } else {
                    alert('Error: ' + (data.message || 'Failed to remove favorite'));
                }
            } catch (error) {
                console.error('Error removing favorite:', error);
                alert('Error removing favorite. Please try again.');
            }
        }
        
        function addRemoveFavoriteListeners() {
            const buttons = document.querySelectorAll('.remove-favorite-btn');
            console.log('Found ' + buttons.length + ' remove favorite buttons');
            
            buttons.forEach(btn => {
                btn.removeEventListener('click', removeClickHandler);
                btn.addEventListener('click', removeClickHandler);
            });
        }
        
        function removeClickHandler(e) {
            e.preventDefault();
            e.stopPropagation();
            const propertyId = this.getAttribute('data-property-id');
            removeFavorite(propertyId);
        }
        
        function addScheduleListeners() {
            const buttons = document.querySelectorAll('.schedule-btn');
            console.log('Found ' + buttons.length + ' schedule buttons');
            
            buttons.forEach(btn => {
                btn.removeEventListener('click', scheduleClickHandler);
                btn.addEventListener('click', scheduleClickHandler);
            });
        }
        
        function scheduleClickHandler(e) {
            e.preventDefault();
            e.stopPropagation();
            const propertyId = this.getAttribute('data-property-id');
            if (propertyId) {
                window.location.href = '?section=schedule&property=' + propertyId;
            }
        }

        // Real-time appointments update
        async function loadAppointments() {
            try {
                const response = await fetch('../api/get-appointments.php');
                const data = await response.json();
                if (data.success) {
                    updateAppointmentsUI(data.appointments);
                }
            } catch (error) {
                console.error('Error loading appointments:', error);
            }
        }

        function updateAppointmentsUI(appointments) {
            const appointmentsSection = document.querySelector('[data-section="appointments"]');
            if (!appointmentsSection) return;
            
            const panelDiv = appointmentsSection.querySelector('.panel');
            if (!panelDiv) return;

            let html = '<h2>📅 My Appointments</h2><p class="panel-description">All your scheduled property visits</p>';
            
            if (appointments && Array.isArray(appointments) && appointments.length > 0) {
                appointments.forEach(apt => {
                    if (!apt) return;
                    const date = apt.appointment_date ? new Date(apt.appointment_date).toLocaleDateString('en-US', {year: 'numeric', month: 'short', day: 'numeric'}) : '';
                    const time = apt.appointment_time ? String(apt.appointment_time) : '';
                    const status = apt.status ? String(apt.status) : 'pending';
                    const title = apt.title ? String(apt.title) : 'Property';
                    
                    // Determine badge color based on status
                    let badgeClass = 'status-pending';
                    let statusText = 'Pending Approval';
                    let icon = '⏳';
                    
                    if (status === 'approved') {
                        badgeClass = 'status-approved';
                        statusText = '✓ Approved';
                        icon = '✅';
                    } else if (status === 'declined') {
                        badgeClass = 'status-declined';
                        statusText = '✕ Declined';
                        icon = '❌';
                    } else if (status === 'scheduled') {
                        badgeClass = 'status-confirmed';
                        statusText = '✓ Confirmed';
                        icon = '✓';
                    } else if (status === 'completed') {
                        badgeClass = 'status-completed';
                        statusText = '✓ Completed';
                        icon = '✓';
                    }
                    
                    html += `<div class="item-card">
                        <div class="item-title">${title}</div>
                        <div class="item-meta">📅 ${date} ${time ? 'at ' + time : ''}</div>
                        <span class="item-status ${badgeClass}"><i class="fas fa-check-circle"></i> ${statusText}</span>
                    </div>`;
                });
            } else {
                html += '<p style="color: #999;">No appointments scheduled. <a href="?section=schedule">Schedule a visit</a></p>';
            }
            
            panelDiv.innerHTML = html;
        }

        // Real-time inquiries update
        async function loadInquiries() {
            try {
                const response = await fetch('../api/get-inquiries.php');
                const data = await response.json();
                if (data.success) {
                    updateInquiriesUI(data.inquiries);
                }
            } catch (error) {
                console.error('Error loading inquiries:', error);
            }
        }

        function updateInquiriesUI(inquiries) {
            const inquiriesPanel = document.querySelector('[data-section="inquiries-list"]');
            if (!inquiriesPanel) return;

            let html = '<h2>📧 Previous Inquiries</h2><p class="panel-description">Your inquiry history</p>';
            
            if (inquiries && Array.isArray(inquiries) && inquiries.length > 0) {
                inquiries.forEach(inq => {
                    if (!inq) return;
                    const date = inq.created_at ? new Date(inq.created_at).toLocaleDateString('en-US', {year: 'numeric', month: 'short', day: 'numeric'}) : '';
                    const status = inq.status ? String(inq.status) : 'pending';
                    const title = inq.title ? String(inq.title) : 'Property Inquiry';
                    
                    // Determine badge color based on status
                    let badgeClass = 'status-pending';
                    let statusText = 'Pending';
                    
                    if (status === 'approved') {
                        badgeClass = 'status-approved';
                        statusText = '✓ Approved';
                    } else if (status === 'declined') {
                        badgeClass = 'status-declined';
                        statusText = '✕ Declined';
                    } else if (status === 'responded') {
                        badgeClass = 'status-responded';
                        statusText = '✓ Responded';
                    }
                    
                    html += `<div class="item-card">
                        <div class="item-title">${title}</div>
                        <div class="item-meta">📧 Sent: ${date}</div>
                        <span class="item-status ${badgeClass}"><i class="fas fa-check"></i> ${statusText}</span>
                    </div>`;
                });
            } else {
                html += '<p style="color: #999;">No inquiries sent yet.</p>';
            }
            
            inquiriesPanel.innerHTML = html;
        }

        async function loadFeedbackHistory() {
            try {
                const response = await fetch('../api/get-customer-feedback.php');
                const data = await response.json();
                if (data.success) {
                    updateFeedbackUI(data.feedback || []);
                }
            } catch (error) {
                console.error('Error loading feedback:', error);
            }
        }

        function updateFeedbackUI(feedbackList) {
            const feedbackPanel = document.querySelector('[data-section="feedback-list"]');
            if (!feedbackPanel) return;

            if (!feedbackList || !Array.isArray(feedbackList) || feedbackList.length === 0) {
                feedbackPanel.innerHTML = '<p style="color: #999;">No feedback submitted yet.</p>';
                return;
            }

            let html = '';
            feedbackList.forEach((item) => {
                const createdAt = item.created_at
                    ? new Date(item.created_at).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' })
                    : 'N/A';
                const rating = Number(item.rating || 0);
                const stars = rating > 0 ? '★'.repeat(rating) + '☆'.repeat(5 - rating) : '';
                const status = String(item.status || 'new').toLowerCase() === 'reviewed' ? 'reviewed' : 'new';
                const statusText = status === 'reviewed' ? 'Reviewed' : 'New';

                html += `
                    <div class="item-card">
                        <div class="item-title">${escapeHtml(item.subject || 'Feedback')}</div>
                        <div class="item-meta">Submitted: ${createdAt}</div>
                        <div class="item-meta" style="margin-top:8px;">${escapeHtml(item.message || '')}</div>
                        ${stars ? `<div class="feedback-rating">${escapeHtml(stars)}</div>` : ''}
                        <span class="item-status status-${status}">${escapeHtml(statusText)}</span>
                    </div>
                `;
            });

            feedbackPanel.innerHTML = html;
        }

        // Real-time profile update
        async function loadProfile() {
            try {
                const response = await fetch('../api/get-profile.php');
                const data = await response.json();
                if (data.success && data.profile) {
                    updateProfileUI(data.profile);
                }
            } catch (error) {
                console.error('Error loading profile:', error);
            }
        }

        function updateProfileUI(profile) {
            const profileForm = document.querySelector('[data-section="profile"] form');
            if (!profileForm || !profile) return;

            const nameInput = profileForm.querySelector('#name');
            const emailInput = profileForm.querySelector('#email');
            const phoneInput = profileForm.querySelector('#phone');
            const cityInput = profileForm.querySelector('#city');
            const bioInput = profileForm.querySelector('#bio');
            
            if (nameInput && profile.user_name) nameInput.value = String(profile.user_name);
            if (emailInput && profile.email) emailInput.value = String(profile.email);
            if (phoneInput && profile.phone) phoneInput.value = String(profile.phone || '');
            if (cityInput && profile.city) cityInput.value = String(profile.city || '');
            if (bioInput && profile.bio) bioInput.value = String(profile.bio || '');
        }

        // Real-time profile sync
        async function syncProfileChanges(profile) {
            const profileForm = document.querySelector('[data-section="profile"] form');
            if (!profileForm) return;
            
            updateProfileUI(profile);
        }

        // Update stats counters
        async function updateStats() {
            const favCount = document.querySelector('.sidebar-stat:nth-child(1) .sidebar-stat-number');
            const aptCount = document.querySelector('.sidebar-stat:nth-child(2) .sidebar-stat-number');
            const inqCount = document.querySelector('.sidebar-stat:nth-child(3) .sidebar-stat-number');

            try {
                // Get favorites count
                const favResponse = await fetch('../api/get-favorites.php');
                const favData = await favResponse.json();
                if (favData.success && favCount) {
                    favCount.textContent = (favData.favorites || []).length;
                }

                // Get appointments count
                const aptResponse = await fetch('../api/get-appointments.php');
                const aptData = aptResponse.json();
                if ((await aptData).success && aptCount) {
                    aptCount.textContent = ((await aptData).appointments || []).length;
                }

                // Get inquiries count
                const inqResponse = await fetch('../api/get-inquiries.php');
                const inqData = inqResponse.json();
                if ((await inqData).success && inqCount) {
                    inqCount.textContent = ((await inqData).inquiries || []).length;
                }
            } catch (error) {
                console.error('Error updating stats:', error);
            }
        }

        // Handle form submissions with real-time updates
        function setupFormHandlers() {
            // Profile form
            const profileForm = document.querySelector('[data-section="profile"] form');
            if (profileForm) {
                profileForm.addEventListener('submit', async (e) => {
                    e.preventDefault();
                    const submitBtn = profileForm.querySelector('button[type="submit"]');
                    const originalText = submitBtn.innerHTML;
                    submitBtn.disabled = true;
                    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Updating...';
                    
                    const formData = {
                        user_name: profileForm.querySelector('#name').value,
                        email: profileForm.querySelector('#email').value,
                        phone: profileForm.querySelector('#phone').value,
                        city: profileForm.querySelector('#city').value,
                        bio: profileForm.querySelector('#bio').value
                    };

                    try {
                        const response = await fetch('../api/profile-update.php', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(formData)
                        });
                        const data = await response.json();
                        if (data.success) {
                            submitBtn.innerHTML = '<i class="fas fa-check-circle"></i> Saved!';
                            setTimeout(() => {
                                submitBtn.disabled = false;
                                submitBtn.innerHTML = originalText;
                            }, 2000);
                            loadProfile();
                        } else {
                            alert('Error: ' + (data.message || 'Failed to update profile'));
                            submitBtn.disabled = false;
                            submitBtn.innerHTML = originalText;
                        }
                    } catch (error) {
                        console.error('Error updating profile:', error);
                        alert('Error updating profile');
                        submitBtn.disabled = false;
                        submitBtn.innerHTML = originalText;
                    }
                });
                
                // Real-time field validation and auto-update display
                const inputFields = profileForm.querySelectorAll('input, textarea');
                inputFields.forEach(field => {
                    field.addEventListener('change', function() {
                        this.style.borderColor = '#28a745';
                        setTimeout(() => {
                            this.style.borderColor = '#ddd';
                        }, 1000);
                    });
                });
            }

            // Schedule visit form
            const scheduleForm = document.querySelector('[data-section="schedule"] form');
            if (scheduleForm) {
                scheduleForm.addEventListener('submit', async (e) => {
                    e.preventDefault();
                    const submitBtn = scheduleForm.querySelector('button[type="submit"]');
                    const originalText = submitBtn.innerHTML;
                    submitBtn.disabled = true;
                    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Scheduling...';
                    
                    const formData = {
                        property_id: scheduleForm.querySelector('#property').value,
                        appointment_date: scheduleForm.querySelector('#visit_date').value,
                        appointment_time: scheduleForm.querySelector('#visit_time').value,
                        message: scheduleForm.querySelector('#message').value
                    };

                    try {
                        const response = await fetch('../api/appointment-add.php', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(formData)
                        });
                        const data = await response.json();
                        if (data.success) {
                            submitBtn.innerHTML = '<i class="fas fa-check-circle"></i> Scheduled!';
                            setTimeout(() => {
                                submitBtn.disabled = false;
                                submitBtn.innerHTML = originalText;
                                scheduleForm.reset();
                            }, 2000);
                            loadAppointments();
                            updateStats();
                        } else {
                            alert('Error: ' + (data.message || 'Failed to schedule appointment'));
                            submitBtn.disabled = false;
                            submitBtn.innerHTML = originalText;
                        }
                    } catch (error) {
                        console.error('Error scheduling appointment:', error);
                        alert('Error scheduling appointment');
                        submitBtn.disabled = false;
                        submitBtn.innerHTML = originalText;
                    }
                });
            }

            // Inquiry form
            const inquiryForm = document.querySelector('[data-section="inquiries"] form');
            if (inquiryForm) {
                inquiryForm.addEventListener('submit', async (e) => {
                    e.preventDefault();
                    const submitBtn = inquiryForm.querySelector('button[type="submit"]');
                    const originalText = submitBtn.innerHTML;
                    submitBtn.disabled = true;
                    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending...';
                    
                    const formData = {
                        property_id: inquiryForm.querySelector('#inq_property').value,
                        message: inquiryForm.querySelector('#inq_message').value
                    };

                    try {
                        const response = await fetch('../api/inquiry-add.php', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(formData)
                        });
                        const data = await response.json();
                        if (data.success) {
                            submitBtn.innerHTML = '<i class="fas fa-check-circle"></i> Sent!';
                            setTimeout(() => {
                                submitBtn.disabled = false;
                                submitBtn.innerHTML = originalText;
                                inquiryForm.reset();
                            }, 2000);
                            loadInquiries();
                            updateStats();
                        } else {
                            alert('Error: ' + (data.message || 'Failed to submit inquiry'));
                            submitBtn.disabled = false;
                            submitBtn.innerHTML = originalText;
                        }
                    } catch (error) {
                        console.error('Error submitting inquiry:', error);
                        alert('Error submitting inquiry');
                        submitBtn.disabled = false;
                        submitBtn.innerHTML = originalText;
                    }
                });
            }

            const feedbackForm = document.getElementById('feedbackForm');
            if (feedbackForm) {
                feedbackForm.addEventListener('submit', async (e) => {
                    e.preventDefault();
                    const submitBtn = feedbackForm.querySelector('button[type="submit"]');
                    const originalText = submitBtn.innerHTML;
                    submitBtn.disabled = true;
                    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Submitting...';

                    const formData = {
                        subject: feedbackForm.querySelector('#feedback_subject').value,
                        message: feedbackForm.querySelector('#feedback_message').value,
                        rating: feedbackForm.querySelector('#feedback_rating').value || null
                    };

                    try {
                        const response = await fetch('../api/feedback-submit.php', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify(formData)
                        });
                        const data = await response.json();
                        if (data.success) {
                            submitBtn.innerHTML = '<i class="fas fa-check-circle"></i> Submitted!';
                            setTimeout(() => {
                                submitBtn.disabled = false;
                                submitBtn.innerHTML = originalText;
                                feedbackForm.reset();
                            }, 1500);
                            loadFeedbackHistory();
                        } else {
                            alert('Error: ' + (data.message || 'Failed to submit feedback'));
                            submitBtn.disabled = false;
                            submitBtn.innerHTML = originalText;
                        }
                    } catch (error) {
                        console.error('Error submitting feedback:', error);
                        alert('Error submitting feedback');
                        submitBtn.disabled = false;
                        submitBtn.innerHTML = originalText;
                    }
                });
            }
        }

        // Initialize on page load
        document.addEventListener('DOMContentLoaded', async function() {
            setupFormHandlers();
            loadFavorites();
            loadAppointments();
            loadInquiries();
            loadFeedbackHistory();
            loadProfile();
            
            // Pre-fill property if coming from favorites schedule button
            const urlParams = new URLSearchParams(window.location.search);
            const prefilledProperty = urlParams.get('property');
            if (prefilledProperty) {
                const propertySelect = document.querySelector('#property');
                if (propertySelect) {
                    propertySelect.value = prefilledProperty;
                }
                // Switch to schedule section
                const scheduleLink = document.querySelector('a[href*="section=schedule"]');
                if (scheduleLink) {
                    scheduleLink.click();
                }
            }
            
            // Refresh other data every 10 seconds (NOT favorites - causes flickering)
            // Favorites only refresh when user removes items to avoid UI flicker
            setInterval(() => {
                loadAppointments();
                loadInquiries();
                loadFeedbackHistory();
                loadProfile();
                updateStats();
            }, 10000);
        });
    </script>

</body>
</html>
