<?php
session_start();

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

$host = 'localhost';
$db = 'zemaraim_interior';
$user = 'zemaraim';
$password = '8wwxk]-X3Kx]CJ]5';

$connection = new mysqli($host, $user, $password, $db);

if ($connection->connect_error) {
    die('Connection failed: ' . $connection->connect_error);
}

$user_id = $_SESSION['user_id'];

$stmt = $connection->prepare("SELECT id, name, email, phone FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user_result = $stmt->get_result();
$user = $user_result->fetch_assoc();
// Add address as empty if not in database
if (!isset($user['address'])) {
    $user['address'] = '';
}
// Add avatar as empty if not in database
if (!isset($user['avatar']) || empty($user['avatar'])) {
    $user['avatar'] = '';
}

// Fetch orders with proper details
$orders_stmt = $connection->prepare("
    SELECT id, total, status, created_at 
    FROM orders 
    WHERE user_id = ? 
    ORDER BY created_at DESC
");
$orders_stmt->bind_param("i", $user_id);
$orders_stmt->execute();
$orders_result = $orders_stmt->get_result();
$orders = [];
while ($row = $orders_result->fetch_assoc()) {
    $orders[] = $row;
}

// Calculate statistics
$stats_stmt = $connection->prepare("
    SELECT 
        COUNT(*) as total_orders,
        SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) as completed_orders,
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_orders,
        SUM(total) as total_spent
    FROM orders 
    WHERE user_id = ?
");
$stats_stmt->bind_param("i", $user_id);
$stats_stmt->execute();
$stats_result = $stats_stmt->get_result();
$stats = $stats_result->fetch_assoc();

// Fetch user consultations
$consultations_stmt = $connection->prepare("
    SELECT id, consultation_type, preferred_date, budget_range, status, created_at
    FROM consultations 
    WHERE email = ?
    ORDER BY created_at DESC
    LIMIT 5
");
$consultations_stmt->bind_param("s", $user['email']);
$consultations_stmt->execute();
$consultations_result = $consultations_stmt->get_result();
$consultations = [];
while ($row = $consultations_result->fetch_assoc()) {
    $consultations[] = $row;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Customer Dashboard - Interior Design Solutions</title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/fontawesome.min.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="">
    <link href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,100..1000;1,9..40,100..1000&display=swap" rel="stylesheet">
    <script src="assets/js/auth-ui-global.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            background-color: #f8f9fa;
            font-family: 'DM Sans', sans-serif;
            color: #333;
        }

        .dashboard-wrapper {
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            margin-top: 170px;
        }

        .dashboard-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 40px 20px;
            width: 100%;
            flex: 1;
            padding-top: 100px; /* space for header on smaller screens */
            box-sizing: border-box;
        }

        .dashboard-header {
            background:#d4a33a;
            color: white;
            padding: 10px;
            border-radius: 20px;
            margin-bottom: 30px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
        }

        .dashboard-header h1 {
            font-size: 32px;
            margin-bottom: 10px;
            font-weight: 700;
        }

        .dashboard-header p {
            font-size: 16px;
            opacity: 0.95;
            margin: 0;
        }

        .dashboard-header-info {
            margin-top: 20px;
            font-size: 14px;
            opacity: 0.9;
        }

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

        .stat-card {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            text-align: center;
            border-left: 4px solid #d4a574;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.12);
        }

        .stat-icon {
            font-size: 32px;
            margin-bottom: 15px;
        }

        .stat-number {
            font-size: 32px;
            font-weight: 700;
            color: #d4a574;
            margin: 10px 0;
        }

        .stat-label {
            color: #666;
            font-size: 14px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 30px;
            border-bottom: 2px solid #e0e0e0;
            overflow-x: auto;
            padding-bottom: 0;
        }

        .tab-button {
            padding: 15px 25px;
            border: none;
            background: transparent;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            color: #666;
            border-bottom: 3px solid transparent;
            transition: all 0.3s ease;
            white-space: nowrap;
        }

        .tab-button.active {
            color: #d4a574;
            border-bottom-color: #d4a574;
        }

        .tab-button:hover:not(.active) {
            color: #999;
        }

        .tab-content {
            display: none;
            animation: fadeIn 0.3s ease;
        }

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

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

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

        .alert {
            padding: 15px 20px;
            border-radius: 6px;
            margin-bottom: 20px;
            font-weight: 500;
            border-left: 4px solid;
            animation: slideDown 0.3s ease;
        }

        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .alert.success {
            background-color: #d4edda;
            color: #155724;
            border-color: #c3e6cb;
        }

        .alert.error {
            background-color: #f8d7da;
            color: #721c24;
            border-color: #f5c6cb;
        }

        .section-title {
            font-size: 22px;
            font-weight: 700;
            color: #333;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 2px solid #e0e0e0;
        }

        .orders-table {
            width: 100%;
            overflow-x: auto; /* allow horizontal scroll on small screens */
        }

        table {
            width: 100%;
            border-collapse: collapse;
            min-width: 720px; /* keep columns readable on narrow screens */
        }

        thead {
            background-color: #f8f9fa;
        }

        th {
            padding: 15px;
            text-align: left;
            font-weight: 700;
            color: #333;
            font-size: 13px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            border-bottom: 2px solid #e0e0e0;
        }

        td {
            padding: 15px;
            border-bottom: 1px solid #f0f0f0;
            color: #666;
        }

        tr:hover {
            background-color: #f9f9f9;
        }

        .status-badge {
            display: inline-block;
            padding: 6px 14px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .status-badge.pending {
            background-color: #fff3cd;
            color: #856404;
        }

        .status-badge.processing {
            background-color: #cfe2ff;
            color: #084298;
        }

        .status-badge.delivered {
            background-color: #d4edda;
            color: #155724;
        }

        .status-badge.cancelled {
            background-color: #f8d7da;
            color: #842029;
        }

        /* Consultation status badges */
        .status-badge.badge-pending {
            background-color: #fff3cd;
            color: #856404;
        }

        .status-badge.badge-approved {
            background-color: #d4edda;
            color: #155724;
        }

        .status-badge.badge-declined {
            background-color: #f8d7da;
            color: #842029;
        }

        .status-badge.badge-scheduled {
            background-color: #cfe2ff;
            color: #084298;
        }

        .status-badge.badge-completed {
            background-color: #d4edda;
            color: #155724;
        }

        .profile-form {
            max-width: 600px;
        }

        .profile-avatar-wrapper {
            display: flex;
            align-items: center;
            gap: 20px;
            margin-bottom: 20px;
        }

        .avatar-preview {
            position: relative;
            width: 96px;
            height: 96px;
            flex: 0 0 96px;
        }

        .avatar-preview img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 50%;
            border: 3px solid #fff;
            box-shadow: 0 6px 18px rgba(0,0,0,0.12);
            background: #f0f0f0;
        }

        .avatar-edit-btn {
            position: absolute;
            right: -6px;
            bottom: -6px;
            background: #d4a574;
            color: #fff;
            padding: 8px 12px;
            border: none;
            border-radius: 20px;
            font-size: 12px;
            cursor: pointer;
            box-shadow: 0 6px 18px rgba(0,0,0,0.12);
            z-index: 10;
            display: inline-flex;
            align-items: center;
            gap: 4px;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .avatar-edit-btn:hover {
            background: #c89b6f;
            box-shadow: 0 8px 22px rgba(0,0,0,0.15);
            transform: translateY(-2px);
        }

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

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
            font-size: 14px;
        }

        input[type="text"],
        input[type="email"],
        input[type="tel"],
        input[type="password"],
        input[type="date"],
        select,
        textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-family: inherit;
            font-size: 14px;
            transition: border-color 0.3s ease;
            background: white;
            color: #333;
        }

        input[type="text"]:focus,
        input[type="email"]:focus,
        input[type="tel"]:focus,
        input[type="password"]:focus,
        input[type="date"]:focus,
        select:focus,
        textarea:focus {
            outline: none;
            border-color: #d4a574;
            box-shadow: 0 0 0 3px rgba(212, 165, 116, 0.1);
        }

        textarea {
            resize: vertical;
            min-height: 100px;
        }

        .form-section {
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #e0e0e0;
        }

        .form-section:last-child {
            border-bottom: none;
        }

        .form-section-title {
            font-size: 16px;
            font-weight: 700;
            margin-bottom: 15px;
            color: #333;
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .btn {
            padding: 12px 30px;
            border: none;
            border-radius: 5px;
            font-size: 14px;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .btn-primary {
            background-color: #d4a574;
            color: white;
        }

        .btn-primary:hover {
            background-color: #b8905a;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(212, 165, 116, 0.4);
        }

        .btn-secondary {
            background-color: #e0e0e0;
            color: #333;
            margin-left: 10px;
        }

        .btn-secondary:hover {
            background-color: #d0d0d0;
        }

        .alert {
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
            font-size: 14px;
        }

        .alert.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .no-data {
            background: #f9f9f9;
            padding: 40px;
            text-align: center;
            border-radius: 10px;
            border: 2px dashed #ddd;
        }

        .no-data h3 {
            color: #999;
            margin-bottom: 15px;
            font-size: 18px;
        }

        .no-data p {
            color: #bbb;
            margin-bottom: 20px;
        }

        .consultation-card {
            background: linear-gradient(135deg, #f8f9fa 0%, #f0f0f0 100%);
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 15px;
            border-left: 4px solid #d4a574;
        }

        .consultation-card h4 {
            color: #333;
            margin-bottom: 10px;
            font-weight: 700;
        }

        .consultation-card p {
            color: #666;
            font-size: 14px;
            margin: 5px 0;
        }

        .footer-wrapper {
            margin-top: auto;
        }

        @media (max-width: 1024px) {
            .dashboard-wrapper {
                margin-top: 120px;
            }

            .dashboard-container {
                padding: 30px 15px;
            }

            .stats-container {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        @media (max-width: 768px) {
            .dashboard-wrapper {
                margin-top: 80px;
            }

            .dashboard-header {
                padding: 30px;
            }

            .dashboard-header h1 {
                font-size: 24px;
            }

            .stats-container {
                grid-template-columns: 1fr;
            }

            .stat-card {
                padding: 20px;
            }

            .stat-number {
                font-size: 24px;
            }

            .tabs {
                flex-wrap: wrap;
                gap: 5px;
            }

            .tab-button {
                padding: 12px 15px;
                font-size: 14px;
            }

            .form-row {
                grid-template-columns: 1fr;
            }

            .content-wrapper {
                padding: 20px;
            }

            table {
                font-size: 12px;
            }

            th, td {
                padding: 10px;
            }

            .btn {
                padding: 10px 20px;
                font-size: 12px;
            }

            .btn-secondary {
                margin-left: 0;
                margin-top: 10px;
            }
        }

        @media (max-width: 576px) {
            .dashboard-wrapper {
                margin-top: 0;
            }

            .dashboard-container {
                padding: 15px;
                padding-top: 15px;
            }

            .dashboard-header {
                padding: 20px;
                margin-bottom: 20px;
            }

            .dashboard-header h1 {
                font-size: 20px;
            }

            .dashboard-header p {
                font-size: 13px;
            }

            .dashboard-header-info {
                font-size: 12px;
                margin-top: 15px;
            }

            .stat-card {
                padding: 15px;
            }

            .stat-number {
                font-size: 20px;
            }

            .stat-label {
                font-size: 12px;
            }

            .section-title {
                font-size: 18px;
            }

            .tab-button {
                padding: 10px 12px;
                font-size: 12px;
            }

            table {
                font-size: 11px;
            }

            th, td {
                padding: 8px 5px;
            }

            .status-badge {
                padding: 4px 8px;
                font-size: 10px;
            }

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

            input, select, textarea {
                padding: 10px;
                font-size: 13px;
            }

            .btn {
                padding: 10px 16px;
                font-size: 11px;
                width: 100%;
            }

            .btn-secondary {
                margin-left: 0;
                margin-top: 8px;
            }

            .profile-avatar-wrapper {
                flex-direction: column;
                align-items: center;
                text-align: center;
            }

            .avatar-preview {
                width: 80px;
                height: 80px;
                flex: 0 0 80px;
            }

            .consultation-card {
                padding: 15px;
            }

            .consultation-card h4 {
                font-size: 14px;
            }

            .consultation-card div[style*="display: grid"] {
                grid-template-columns: 1fr !important;
                gap: 8px !important;
            }
        }
    </style>
</head>
<body>
    <div class="dashboard-wrapper">
        <!-- Navigation Header -->
        <?php include 'header-section.html'; ?>

        <div class="dashboard-container">
            <div class="dashboard-header">
                <h1>📊 Welcome, <?php echo htmlspecialchars($user['name'] ?? 'Guest'); ?>!</h1>
                <p>Manage your orders, profile, and track your interior design projects</p>
                <div class="dashboard-header-info">
                    <i class="fas fa-envelope"></i> <?php echo htmlspecialchars($user['email'] ?? 'No email'); ?> 
                    <span style="margin: 0 10px;">|</span>
                    <i class="fas fa-phone"></i> <?php echo htmlspecialchars($user['phone'] ?? 'No phone'); ?>
                </div>
            </div>

            <!-- Statistics Cards -->
            <div class="stats-container">
                <div class="stat-card">
                    <div class="stat-icon">📦</div>
                    <div class="stat-number"><?php echo $stats['total_orders'] ?? 0; ?></div>
                    <div class="stat-label">Total Orders</div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">✅</div>
                    <div class="stat-number"><?php echo $stats['completed_orders'] ?? 0; ?></div>
                    <div class="stat-label">Completed</div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">⏳</div>
                    <div class="stat-number"><?php echo $stats['pending_orders'] ?? 0; ?></div>
                    <div class="stat-label">Pending</div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">💰</div>
                    <div class="stat-number">₹<?php echo number_format($stats['total_spent'] ?? 0, 0); ?></div>
                    <div class="stat-label">Total Spent</div>
                </div>
            </div>

            <!-- Tabs Navigation -->
            <div class="tabs" style="border-bottom: 2px solid #e0e0e0; margin-bottom: 30px; display: flex; gap: 10px;">
                <button class="tab-button active" onclick="switchTab('orders', event)">
                    <i class="fas fa-shopping-bag"></i> Orders
                </button>
                <button class="tab-button" onclick="switchTab('profile', event)">
                    <i class="fas fa-user"></i> Profile
                </button>
                <button class="tab-button" onclick="switchTab('password', event)">
                    <i class="fas fa-lock"></i> Change Password
                </button>
                <button class="tab-button" onclick="switchTab('consultations', event)">
                    <i class="fas fa-calendar"></i> Consultations
                </button>
            </div>



            <!-- Orders Tab -->
            <div id="orders" class="tab-content active">
                <div class="content-wrapper">
                    <h2 class="section-title"><i class="fas fa-shopping-cart"></i> Your Orders</h2>
                    <?php if (!empty($orders)): ?>
                        <div class="orders-table">
                            <table>
                                <thead>
                                    <tr>
                                        <th>Order ID</th>
                                        <th>Date</th>
                                        <th>Amount</th>
                                        <th>Status</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($orders as $order): ?>
                                        <tr>
                                            <td><strong>#<?php echo htmlspecialchars($order['id']); ?></strong></td>
                                            <td><?php echo date('M d, Y', strtotime($order['created_at'])); ?></td>
                                            <td><strong>₹<?php echo number_format($order['total'], 0); ?></strong></td>
                                            <td>
                                                <span class="status-badge <?php echo strtolower($order['status']); ?>">
                                                    <?php echo ucfirst($order['status']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <a href="order-confirmation.php?order_id=<?php echo $order['id']; ?>" class="btn btn-primary" style="padding: 6px 12px; font-size: 12px;">View</a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="no-data">
                            <h3>No Orders Yet</h3>
                            <p>You haven't placed any orders yet. Start shopping to see them here.</p>
                            <a href="shop.html" class="btn btn-primary">Start Shopping</a>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Profile Tab -->
            <div id="profile" class="tab-content">
                <div class="content-wrapper">
                    <h2 class="section-title"><i class="fas fa-user-circle"></i> My Profile</h2>
                    <div class="profile-form">
                        <div id="messageAlert"></div>

                        <div class="profile-avatar-wrapper">
                            <div class="avatar-preview">
                                <img id="avatarImg" src="<?php echo htmlspecialchars($user['avatar'] ? 'uploads/avatars/' . $user['avatar'] : 'assets/images/avatar-placeholder.png'); ?>" alt="Profile">
                                <label class="avatar-edit-btn" for="avatarInput" title="Click to upload new photo">📷 Change</label>
                                <input type="file" id="avatarInput" name="avatar" accept="image/jpeg,image/png,image/gif,image/webp" style="display:none;" onchange="uploadAvatar(event)">
                            </div>
                            <div style="flex:1;">
                                <div style="font-weight:700; font-size:16px; color:#333;"><?php echo htmlspecialchars($user['name'] ?? ''); ?></div>
                                <div style="color:#666; font-size:13px;"><?php echo htmlspecialchars($user['email'] ?? ''); ?></div>
                                <div style="color:#999; font-size:12px; margin-top:5px;">Member since <?php echo date('M Y', strtotime($user['created_at'] ?? date('Y-m-d'))); ?></div>
                            </div>
                        </div>

                        <div class="form-section">
                            <h4 class="form-section-title">Personal Information</h4>
                            <div class="form-row">
                                <div class="form-group">
                                    <label for="name">Full Name</label>
                                    <input type="text" id="name" name="name" value="<?php echo htmlspecialchars($user['name'] ?? ''); ?>">
                                </div>
                                <div class="form-group">
                                    <label for="email">Email Address</label>
                                    <input type="email" id="email" name="email" value="<?php echo htmlspecialchars($user['email'] ?? ''); ?>" readonly style="background-color: #f5f5f5;">
                                </div>
                            </div>

                            <div class="form-row">
                                <div class="form-group">
                                    <label for="phone">Phone Number</label>
                                    <input type="tel" id="phone" name="phone" value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>">
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="address">Address</label>
                                <textarea id="address" name="address"><?php echo htmlspecialchars($user['address'] ?? ''); ?></textarea>
                            </div>
                        </div>

                        <div style="margin-top: 30px;">
                            <button type="button" class="btn btn-primary" onclick="updateProfile()">Save Changes</button>
                            <button type="button" class="btn btn-secondary">Cancel</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Change Password Tab -->
            <div id="password" class="tab-content">
                <div class="content-wrapper">
                    <h2 class="section-title"><i class="fas fa-lock"></i> Change Password</h2>
                    <div class="profile-form">
                        <div id="passwordMessageAlert"></div>

                        <div class="form-section">
                            <h4 class="form-section-title">Update Your Password</h4>
                            
                            <div class="form-group">
                                <label for="currentPassword">Current Password *</label>
                                <input type="password" id="currentPassword" name="currentPassword" placeholder="Enter your current password" required>
                                <span id="error-currentPassword" style="color: #d32f2f; font-size: 12px;"></span>
                            </div>

                            <div class="form-group">
                                <label for="newPassword">New Password *</label>
                                <input type="password" id="newPassword" name="newPassword" placeholder="Enter your new password (min 6 characters)" required>
                                <span id="error-newPassword" style="color: #d32f2f; font-size: 12px;"></span>
                            </div>

                            <div class="form-group">
                                <label for="confirmPassword">Confirm Password *</label>
                                <input type="password" id="confirmPassword" name="confirmPassword" placeholder="Re-enter your new password" required>
                                <span id="error-confirmPassword" style="color: #d32f2f; font-size: 12px;"></span>
                            </div>

                            <div style="background: #f5f5f5; padding: 15px; border-radius: 5px; margin: 20px 0; font-size: 13px; color: #666;">
                                <strong>Password Requirements:</strong>
                                <ul style="margin: 10px 0 0 20px;">
                                    <li>Minimum 6 characters</li>
                                    <li>Must be different from current password</li>
                                    <li>Both password fields must match</li>
                                </ul>
                            </div>
                        </div>

                        <div style="margin-top: 30px;">
                            <button type="button" class="btn btn-primary" onclick="changePassword()">Update Password</button>
                            <button type="button" class="btn btn-secondary" onclick="resetPasswordForm()">Cancel</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Consultations Tab -->
            <div id="consultations" class="tab-content">
                <div class="content-wrapper">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px;">
                        <h2 class="section-title" style="margin: 0; padding-bottom: 0; border: none;"><i class="fas fa-calendar-alt"></i> Your Consultations</h2>
                        <button type="button" class="btn btn-primary" onclick="openConsultationModal()" style="padding: 10px 20px; font-size: 14px;">
                            <i class="fas fa-plus"></i> Request New Consultation
                        </button>
                    </div>
                    
                    <div id="consultationAlert"></div>
                    <div id="consultations-container">
                        <?php if (!empty($consultations)): ?>
                            <div>
                                <?php foreach ($consultations as $cons): ?>
                                    <div class="consultation-card" style="background: white; padding: 20px; margin-bottom: 15px; border-left: 4px solid #d4a574; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.05);">
                                        <h4 style="margin-bottom: 10px; color: #333;">
                                            <i class="fas fa-check-circle" style="color: #d4a574; margin-right: 8px;"></i>
                                            <?php echo ucfirst(str_replace('_', ' ', htmlspecialchars($cons['consultation_type']))) ; ?>
                                        </h4>
                                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; font-size: 14px; color: #666;">
                                            <div><strong>📅 Date:</strong> <?php echo date('M d, Y', strtotime($cons['preferred_date'])); ?></div>
                                            <div><strong>💰 Budget:</strong> ₹<?php echo htmlspecialchars($cons['budget_range']); ?></div>
                                        </div>
                                        <div style="margin-top: 10px;">
                                            <strong>Status:</strong> 
                                            <span class="status-badge badge-<?php echo htmlspecialchars(str_replace('_', '-', $cons['status'])); ?>" 
                                                  data-consultation-id="<?php echo htmlspecialchars($cons['id']); ?>"
                                                  data-status="<?php echo htmlspecialchars($cons['status']); ?>"
                                                  style="font-size: 12px;">
                                                <?php echo ucfirst(str_replace('_', ' ', htmlspecialchars($cons['status']))); ?>
                                            </span>
                                        </div>
                                        <p style="font-size: 12px; color: #999; margin-top: 10px;">
                                            <i class="fas fa-clock"></i> Requested on <?php echo date('M d, Y', strtotime($cons['created_at'])); ?>
                                        </p>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            <div class="no-data">
                                <h3>No Consultations Yet</h3>
                                <p>You haven't scheduled any consultations yet. Schedule one with our design experts.</p>
                                <button type="button" class="btn btn-primary" onclick="openConsultationModal()">Schedule Consultation</button>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- New Consultation Modal -->
            <div id="consultationModal" style="
                display: none;
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.5);
                z-index: 1000;
                justify-content: center;
                align-items: center;
                animation: fadeIn 0.3s ease;
                overflow-y: auto;
                padding: 20px 0;
            ">
                <div style="
                    background: white;
                    padding: 30px;
                    border-radius: 10px;
                    max-width: 700px;
                    width: 90%;
                    max-height: 95vh;
                    overflow-y: auto;
                    box-shadow: 0 10px 40px rgba(0,0,0,0.3);
                    margin: auto;
                ">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px;">
                        <h3 style="margin: 0; color: #333; font-size: 24px; font-weight: 600;">Request New Consultation</h3>
                        <button type="button" onclick="closeConsultationModal()" style="background: none; border: none; font-size: 28px; cursor: pointer; color: #999; line-height: 1;">×</button>
                    </div>

                    <div id="consultationFormAlert"></div>

                    <form id="newConsultationForm">
                        <!-- Personal Information Section -->
                        <div style="margin-bottom: 25px; padding-bottom: 20px; border-bottom: 1px solid #eee;">
                            <h4 style="color: #d4a574; font-size: 16px; font-weight: 600; margin-bottom: 15px;">Personal Information</h4>
                            
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                                <div class="form-group">
                                    <label for="consFirstName" style="font-weight: 500; color: #333; margin-bottom: 8px; display: block;">First Name <span style="color: #d4a574;">*</span></label>
                                    <input type="text" id="consFirstName" name="first_name" required value="<?php echo htmlspecialchars(explode(' ', $user['name'] ?? '')[0]); ?>" style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px; font-family: inherit;">
                                </div>
                                <div class="form-group">
                                    <label for="consLastName" style="font-weight: 500; color: #333; margin-bottom: 8px; display: block;">Last Name <span style="color: #d4a574;">*</span></label>
                                    <input type="text" id="consLastName" name="last_name" required value="<?php echo htmlspecialchars(implode(' ', array_slice(explode(' ', $user['name'] ?? ''), 1))); ?>" style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px; font-family: inherit;">
                                </div>
                            </div>

                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                                <div class="form-group">
                                    <label for="consEmail" style="font-weight: 500; color: #333; margin-bottom: 8px; display: block;">Email Address <span style="color: #d4a574;">*</span></label>
                                    <input type="email" id="consEmail" name="email" required value="<?php echo htmlspecialchars($user['email'] ?? ''); ?>" style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px; font-family: inherit;">
                                </div>
                                <div class="form-group">
                                    <label for="consPhone" style="font-weight: 500; color: #333; margin-bottom: 8px; display: block;">Phone Number <span style="color: #d4a574;">*</span></label>
                                    <input type="tel" id="consPhone" name="phone" required value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>" style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px; font-family: inherit;">
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="consAddress" style="font-weight: 500; color: #333; margin-bottom: 8px; display: block;">Address <span style="color: #d4a574;">*</span></label>
                                <textarea id="consAddress" name="address" required style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px; font-family: inherit; min-height: 70px; resize: vertical;"><?php echo htmlspecialchars($user['address'] ?? ''); ?></textarea>
                            </div>
                        </div>

                        <!-- Consultation Details Section -->
                        <div style="margin-bottom: 25px; padding-bottom: 20px; border-bottom: 1px solid #eee;">
                            <h4 style="color: #d4a574; font-size: 16px; font-weight: 600; margin-bottom: 15px;">Consultation Details</h4>
                            
                            <div class="form-group" style="margin-bottom: 15px;">
                                <label for="consType" style="font-weight: 500; color: #333; margin-bottom: 8px; display: block;">Type of Consultation <span style="color: #d4a574;">*</span></label>
                                <select id="consType" name="consultation_type" required style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px; font-family: inherit;">
                                    <option value="">Select a consultation type</option>
                                    <option value="residential">Residential Interior Design</option>
                                    <option value="commercial">Commercial Interior Design</option>
                                    <option value="renovation">Home Renovation</option>
                                    <option value="furniture">Furniture Selection</option>
                                    <option value="colors">Color & Style Consultation</option>
                                </select>
                            </div>

                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                                <div class="form-group">
                                    <label for="consDate" style="font-weight: 500; color: #333; margin-bottom: 8px; display: block;">Preferred Date <span style="color: #d4a574;">*</span></label>
                                    <input type="date" id="consDate" name="preferred_date" min="<?php echo date('Y-m-d'); ?>" required style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px; font-family: inherit;">
                                </div>
                                <div class="form-group">
                                    <label for="consTime" style="font-weight: 500; color: #333; margin-bottom: 8px; display: block;">Preferred Time <span style="color: #d4a574;">*</span></label>
                                    <select id="consTime" name="preferred_time" required style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px; font-family: inherit;">
                                        <option value="">Select a time</option>
                                        <option value="09:00">9:00 AM</option>
                                        <option value="10:00">10:00 AM</option>
                                        <option value="11:00">11:00 AM</option>
                                        <option value="12:00">12:00 PM</option>
                                        <option value="13:00">1:00 PM</option>
                                        <option value="14:00">2:00 PM</option>
                                        <option value="15:00">3:00 PM</option>
                                        <option value="16:00">4:00 PM</option>
                                        <option value="17:00">5:00 PM</option>
                                    </select>
                                </div>
                            </div>

                            <div class="form-group" style="margin-bottom: 15px;">
                                <label for="consDescription" style="font-weight: 500; color: #333; margin-bottom: 8px; display: block;">Project Description <span style="color: #d4a574;">*</span></label>
                                <textarea id="consDescription" name="project_description" placeholder="Tell us about your project, style preferences, and any specific requirements..." required style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px; font-family: inherit; min-height: 100px; resize: vertical;"></textarea>
                            </div>

                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                                <div class="form-group">
                                    <label for="consBudget" style="font-weight: 500; color: #333; margin-bottom: 8px; display: block;">Budget Range <span style="color: #d4a574;">*</span></label>
                                    <select id="consBudget" name="budget_range" required style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px; font-family: inherit;">
                                        <option value="">Select budget range</option>
                                        <option value="10k-50k">₹10,000 - ₹50,000</option>
                                        <option value="50k-100k">₹50,000 - ₹100,000</option>
                                        <option value="100k-200k">₹100,000 - ₹200,000</option>
                                        <option value="200k-500k">₹200,000 - ₹500,000</option>
                                        <option value="500k+">₹500,000+</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="consSource" style="font-weight: 500; color: #333; margin-bottom: 8px; display: block;">How did you hear about us?</label>
                                    <select id="consSource" name="source" style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px; font-family: inherit;">
                                        <option value="">Select option</option>
                                        <option value="social-media">Social Media</option>
                                        <option value="google">Google Search</option>
                                        <option value="friend">Friend Referral</option>
                                        <option value="website">Our Website</option>
                                        <option value="advertisement">Advertisement</option>
                                        <option value="other">Other</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div style="display: flex; gap: 15px;">
                            <button type="submit" class="btn btn-primary" style="flex: 1; padding: 12px; background: #d4a574; color: white; border: none; border-radius: 5px; font-weight: 600; cursor: pointer; font-size: 14px; transition: all 0.3s;">Submit Consultation Request</button>
                            <button type="button" onclick="closeConsultationModal()" class="btn btn-secondary" style="flex: 1; padding: 12px; background: #f0f0f0; color: #333; border: none; border-radius: 5px; font-weight: 600; cursor: pointer; font-size: 14px; transition: all 0.3s;">Cancel</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Footer -->
        <!-- <footer class="footer-wrapper" style="background: #1a1a1a; color: white; padding: 40px 20px; text-align: center; margin-top: 40px;">
            <p style="margin: 0; font-size: 14px;">Copyright © 2025 Faren Design. All Rights Reserved.</p>
        </footer> -->
        <!-- Footer -->
        <?php include 'footer-section.html'; ?>
    </div>

    <script>
        function switchTab(tabName, e) {
            // Hide all tabs
            const tabContents = document.querySelectorAll('.tab-content');
            tabContents.forEach(tab => tab.classList.remove('active'));

            // Remove active class from all buttons
            const buttons = document.querySelectorAll('.tab-button');
            buttons.forEach(btn => btn.classList.remove('active'));

            // Show selected tab
            const selectedTab = document.getElementById(tabName);
            if (selectedTab) {
                selectedTab.classList.add('active');
            }

            // Add active class to clicked button (safely find the button)
            const clickedBtn = e ? (e.currentTarget || e.target.closest('.tab-button')) : null;
            if (clickedBtn) clickedBtn.classList.add('active');
        }

        // ========== PROFILE PHOTO UPLOAD ==========
        async function uploadAvatar(event) {
            const file = event.target.files[0];
            if (!file) return;

            // Validate file size (5MB max)
            if (file.size > 5 * 1024 * 1024) {
                showMessage('messageAlert', 'File size exceeds 5MB limit', 'error');
                event.target.value = '';
                return;
            }

            // Validate file type
            if (!['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(file.type)) {
                showMessage('messageAlert', 'Only image files allowed (JPG, PNG, GIF, WebP)', 'error');
                event.target.value = '';
                return;
            }

            // Show loading state
            const avatarImg = document.getElementById('avatarImg');
            const originalSrc = avatarImg.src;
            avatarImg.style.opacity = '0.5';

            // Create FormData
            const formData = new FormData();
            formData.append('avatar', file);

            try {
                const response = await fetch('auth-system/upload-avatar.php', {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();

                if (data.success) {
                    // Update avatar image with cache buster
                    const imageUrl = data.avatarUrl + '?t=' + new Date().getTime();
                    avatarImg.src = imageUrl;
                    avatarImg.style.opacity = '1';

                    // Update header avatar in real-time
                    const headerAvatar = document.getElementById('user-avatar-img');
                    const headerAvatarSpan = document.getElementById('user-avatar');
                    if (headerAvatar) {
                        headerAvatar.src = imageUrl;
                        headerAvatar.style.display = 'block';
                        if (headerAvatarSpan) headerAvatarSpan.style.display = 'none';
                    }

                    // Update localStorage for other pages
                    localStorage.setItem('userAvatarUrl', imageUrl);

                    // Show success message
                    showMessage('messageAlert', '✅ Profile photo updated successfully! Changes visible everywhere.', 'success');

                    // Reset file input
                    event.target.value = '';
                } else {
                    avatarImg.src = originalSrc;
                    avatarImg.style.opacity = '1';
                    showMessage('messageAlert', '❌ ' + (data.message || 'Failed to upload photo'), 'error');
                    event.target.value = '';
                }
            } catch (error) {
                console.error('Upload error:', error);
                avatarImg.src = originalSrc;
                avatarImg.style.opacity = '1';
                showMessage('messageAlert', '❌ Error uploading photo. Please try again.', 'error');
                event.target.value = '';
            }
        }

        function previewAvatar(event) {
            const file = event.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    document.getElementById('avatarImg').src = e.target.result;
                };
                reader.readAsDataURL(file);
            }
        }

        function showMessage(elementId, message, type) {
            const element = document.getElementById(elementId);
            if (element) {
                element.innerHTML = `<div class="alert ${type}">${message}</div>`;
            }
        }

        // ========== PROFILE UPDATE ==========
        function updateProfile() {
            const name = document.getElementById('name').value.trim();
            const phone = document.getElementById('phone').value.trim();
            const address = document.getElementById('address').value.trim();

            // Clear previous errors
            document.getElementById('error-name') && (document.getElementById('error-name').textContent = '');
            document.getElementById('error-phone') && (document.getElementById('error-phone').textContent = '');
            document.getElementById('error-address') && (document.getElementById('error-address').textContent = '');

            // Validation
            let hasError = false;
            if (!name || name.length < 2) {
                document.getElementById('messageAlert').innerHTML = '<div class="alert error">Please enter a valid name (at least 2 characters)</div>';
                hasError = true;
            }
            if (!phone || phone.replace(/\D/g, '').length < 10) {
                document.getElementById('messageAlert').innerHTML = '<div class="alert error">Please enter a valid phone number</div>';
                hasError = true;
            }

            if (hasError) return;

            // Send to server
            fetch('api/update-profile.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    name: name,
                    phone: phone,
                    address: address
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    document.getElementById('messageAlert').innerHTML = '<div class="alert success">✅ Profile updated successfully!</div>';
                    
                    // Update header display with new name
                    const updatedName = document.getElementById('name').value;
                    if (document.getElementById('user-name-display')) {
                        document.getElementById('user-name-display').textContent = updatedName;
                        localStorage.setItem('userName', updatedName);
                    }
                    
                    // Update avatar initial in header
                    const initial = updatedName.charAt(0).toUpperCase();
                    if (document.getElementById('user-avatar')) {
                        document.getElementById('user-avatar').textContent = initial;
                    }
                    
                    // Update localStorage for mobile header
                    localStorage.setItem('userName', updatedName);
                    
                    // Update mobile welcome name if it exists
                    const mobileWelcomeName = document.getElementById('mobile-welcome-name');
                    if (mobileWelcomeName) {
                        mobileWelcomeName.textContent = updatedName;
                    }
                    
                    setTimeout(() => {
                        document.getElementById('messageAlert').innerHTML = '';
                    }, 3000);
                } else {
                    document.getElementById('messageAlert').innerHTML = '<div class="alert error">❌ ' + (data.message || 'Failed to update profile') + '</div>';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('messageAlert').innerHTML = '<div class="alert error">❌ An error occurred. Please try again.</div>';
            });
        }

        function changePassword() {
            const currentPassword = document.getElementById('currentPassword').value;
            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;

            // Clear previous errors
            document.getElementById('error-currentPassword').textContent = '';
            document.getElementById('error-newPassword').textContent = '';
            document.getElementById('error-confirmPassword').textContent = '';

            // Validation
            let isValid = true;

            if (!currentPassword) {
                document.getElementById('error-currentPassword').textContent = 'Current password is required';
                isValid = false;
            }

            if (!newPassword || newPassword.length < 6) {
                document.getElementById('error-newPassword').textContent = 'New password must be at least 6 characters';
                isValid = false;
            }

            if (newPassword !== confirmPassword) {
                document.getElementById('error-confirmPassword').textContent = 'Passwords do not match';
                isValid = false;
            }

            if (currentPassword === newPassword) {
                document.getElementById('error-newPassword').textContent = 'New password must be different from current password';
                isValid = false;
            }

            if (!isValid) return;

            // Send to server
            fetch('api/change-password.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    currentPassword: currentPassword,
                    newPassword: newPassword
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    document.getElementById('passwordMessageAlert').innerHTML = '<div class="alert success">✅ Password changed successfully!</div>';
                    resetPasswordForm();
                    setTimeout(() => {
                        document.getElementById('passwordMessageAlert').innerHTML = '';
                    }, 3000);
                } else {
                    document.getElementById('passwordMessageAlert').innerHTML = '<div class="alert error">❌ ' + (data.message || 'Failed to change password') + '</div>';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('passwordMessageAlert').innerHTML = '<div class="alert error">❌ An error occurred. Please try again.</div>';
            });
        }

        function resetPasswordForm() {
            document.getElementById('currentPassword').value = '';
            document.getElementById('newPassword').value = '';
            document.getElementById('confirmPassword').value = '';
            document.getElementById('error-currentPassword').textContent = '';
            document.getElementById('error-newPassword').textContent = '';
            document.getElementById('error-confirmPassword').textContent = '';
        }

        function previewAvatar(e) {
            const file = e.target.files && e.target.files[0];
            if (!file) return;
            if (!file.type.startsWith('image/')) {
                document.getElementById('messageAlert').innerHTML = '<div class="alert error">Please select a valid image file.</div>';
                return;
            }
            const url = URL.createObjectURL(file);
            const img = document.getElementById('avatarImg');
            img.src = url;
            document.getElementById('messageAlert').innerHTML = '<div class="alert success">Avatar preview updated. Saving to server not implemented here.</div>';
            setTimeout(() => { document.getElementById('messageAlert').innerHTML = ''; }, 3000);
        }

        // Consultation Modal Functions
        function openConsultationModal() {
            const modal = document.getElementById('consultationModal');
            if (modal) {
                modal.style.display = 'flex';
                document.body.style.overflow = 'hidden';
            }
        }

        function closeConsultationModal() {
            const modal = document.getElementById('consultationModal');
            if (modal) {
                modal.style.display = 'none';
                document.body.style.overflow = 'auto';
                document.getElementById('newConsultationForm').reset();
                document.getElementById('consultationFormAlert').innerHTML = '';
            }
        }

        // Close modal when clicking outside
        document.addEventListener('click', function(event) {
            const modal = document.getElementById('consultationModal');
            if (modal && event.target === modal) {
                closeConsultationModal();
            }
        });

        // Handle consultation form submission
        document.getElementById('newConsultationForm').addEventListener('submit', function(e) {
            e.preventDefault();

            // Get all form values
            const firstName = document.getElementById('consFirstName').value.trim();
            const lastName = document.getElementById('consLastName').value.trim();
            const email = document.getElementById('consEmail').value.trim();
            const phone = document.getElementById('consPhone').value.trim();
            const address = document.getElementById('consAddress').value.trim();
            const consultationType = document.getElementById('consType').value;
            const preferredDate = document.getElementById('consDate').value;
            const preferredTime = document.getElementById('consTime').value;
            const projectDescription = document.getElementById('consDescription').value.trim();
            const budgetRange = document.getElementById('consBudget').value;
            const source = document.getElementById('consSource').value;

            // Validation
            let isValid = true;
            let errorMsg = '';

            if (!firstName || !lastName || !email || !phone || !address) {
                errorMsg = '❌ Please fill in all personal information fields';
                isValid = false;
            } else if (!consultationType || !preferredDate || !preferredTime || !budgetRange) {
                errorMsg = '❌ Please fill in all consultation details';
                isValid = false;
            } else if (!projectDescription) {
                errorMsg = '❌ Please provide a project description';
                isValid = false;
            }

            // Validate email format
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(email)) {
                errorMsg = '❌ Please enter a valid email address';
                isValid = false;
            }

            // Validate phone format
            const phoneRegex = /^[0-9\-\+\(\)\s]{10,}$/;
            if (!phoneRegex.test(phone)) {
                errorMsg = '❌ Please enter a valid phone number';
                isValid = false;
            }

            // Validate date is in future
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            const selectedDate = new Date(preferredDate);
            selectedDate.setHours(0, 0, 0, 0);
            if (selectedDate < today) {
                errorMsg = '❌ Please select a future date';
                isValid = false;
            }

            if (!isValid) {
                document.getElementById('consultationFormAlert').innerHTML = '<div class="alert error" style="padding: 12px; background: #ffe6e6; color: #d32f2f; border-radius: 5px; margin-bottom: 15px; font-size: 14px;">' + errorMsg + '</div>';
                return;
            }

            // Send to server
            fetch('auth-system/submit-consultation.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    first_name: firstName,
                    last_name: lastName,
                    email: email,
                    phone: phone,
                    address: address,
                    consultation_type: consultationType,
                    preferred_date: preferredDate,
                    preferred_time: preferredTime,
                    project_description: projectDescription,
                    budget_range: budgetRange,
                    source: source
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    document.getElementById('consultationAlert').innerHTML = '<div class="alert success">✅ Consultation request submitted successfully! Our team will contact you soon.</div>';
                    closeConsultationModal();
                    
                    // Reload consultations after a short delay
                    setTimeout(() => {
                        location.reload();
                    }, 2000);
                } else {
                    document.getElementById('consultationFormAlert').innerHTML = '<div class="alert error">❌ ' + (data.message || 'Failed to submit consultation request') + '</div>';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('consultationFormAlert').innerHTML = '<div class="alert error">❌ An error occurred. Please try again.</div>';
            });
        });

        // Dropdown close on document click
        document.addEventListener('click', function(event) {
            const dropdown = document.getElementById('userDropdown');
            const profileSection = document.querySelector('[onclick*="userDropdown"]');
            
            if (dropdown && !dropdown.contains(event.target) && !profileSection.contains(event.target)) {
                dropdown.style.display = 'none';
            }
        });

        // Initialize dashboard on page load
        window.addEventListener('DOMContentLoaded', function() {
            // Ensure auth state is properly set
            const userName = '<?php echo htmlspecialchars($user["name"] ?? "User"); ?>';
            localStorage.setItem('userLoggedIn', 'true');
            localStorage.setItem('userName', userName);
            localStorage.setItem('userRole', 'customer');
            
            // Initialize avatar upload button
            const avatarEditBtn = document.querySelector('.avatar-edit-btn');
            const avatarInput = document.getElementById('avatarInput');
            
            if (avatarEditBtn && avatarInput) {
                // Make sure the button is clickable
                avatarEditBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    avatarInput.click();
                });
                
                // Verify input change listener
                avatarInput.addEventListener('change', function(e) {
                    console.log('File selected:', e.target.files[0]?.name);
                    uploadAvatar(e);
                });
                
                console.log('Avatar upload initialized successfully');
            } else {
                console.warn('Avatar elements not found');
            }
            
            // Start real-time consultation updates
            startConsultationPolling();
        });

        // Real-time consultation status polling
        let consultationPollingInterval = null;

        function startConsultationPolling() {
            console.log('Starting consultation polling...');
            
            // Fetch immediately on start
            fetchConsultationUpdates();
            
            // Then poll every 5 seconds
            consultationPollingInterval = setInterval(function() {
                console.log('Polling consultations...');
                fetchConsultationUpdates();
            }, 5000);
            
            console.log('Consultation polling started (interval: 5000ms)');
        }

        function stopConsultationPolling() {
            if (consultationPollingInterval) {
                clearInterval(consultationPollingInterval);
            }
        }

        function fetchConsultationUpdates() {
            fetch('api/get-consultation-status.php', {
                method: 'GET',
                credentials: 'same-origin',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            })
                .then(response => {
                    if (!response.ok) {
                        console.log('API Response not OK:', response.status);
                        throw new Error('Failed to fetch consultations - Status: ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success && Array.isArray(data.consultations)) {
                        console.log('Consultation data received:', data.consultations.length, 'consultations');
                        updateConsultationDisplay(data.consultations);
                    } else {
                        console.log('API response not successful:', data);
                    }
                })
                .catch(error => {
                    console.log('Consultation polling error:', error);
                    // Silently fail - don't interrupt user experience
                });
        }

        function updateConsultationDisplay(consultations) {
            if (!consultations.length) {
                console.log('No consultations in response');
                return;
            }

            console.log('Updating', consultations.length, 'consultation cards');

            // Update each consultation card
            consultations.forEach(function(consultation) {
                // Try multiple selectors to find the badge
                let badgeElement = document.querySelector(`span[data-consultation-id="${consultation.id}"]`);
                
                if (!badgeElement) {
                    console.log('Badge not found for consultation ID:', consultation.id);
                    return;
                }
                
                const oldStatus = badgeElement.getAttribute('data-status');
                const newStatus = consultation.status;
                
                console.log(`Consultation ${consultation.id}: ${oldStatus} → ${newStatus}`);
                
                // Only update if status changed
                if (oldStatus !== newStatus) {
                    console.log('Status changed! Updating display...');
                    
                    // Update the badge class
                    badgeElement.className = `status-badge badge-${newStatus.replace(/_/g, '-')}`;
                    badgeElement.textContent = capitalizeWords(newStatus.replace(/_/g, ' '));
                    badgeElement.setAttribute('data-status', newStatus);
                    
                    // Add animation
                    badgeElement.style.animation = 'none';
                    setTimeout(() => {
                        badgeElement.style.animation = 'pulse 0.6s ease-out';
                    }, 10);
                    
                    // Show notification
                    showStatusChangeNotification(consultation);
                }
            });
        }

        function showStatusChangeNotification(consultation) {
            const alertDiv = document.getElementById('consultationAlert');
            if (alertDiv) {
                const statusText = capitalizeWords(consultation.status.replace(/_/g, ' '));
                const message = `<div class="alert success" style="animation: slideIn 0.3s ease-out;">✨ Your ${consultation.consultation_type} consultation is now <strong>${statusText}</strong>!</div>`;
                alertDiv.innerHTML = message;
                
                // Auto-remove notification after 5 seconds
                setTimeout(() => {
                    if (alertDiv.innerHTML === message) {
                        alertDiv.innerHTML = '';
                    }
                }, 5000);
            }
        }

        function capitalizeWords(str) {
            return str
                .split(' ')
                .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
                .join(' ');
        }

        // Add CSS animation styles
        const style = document.createElement('style');
        style.textContent = `
            @keyframes pulse {
                0% { transform: scale(1); }
                50% { transform: scale(1.1); }
                100% { transform: scale(1); }
            }
            @keyframes slideIn {
                from { opacity: 0; transform: translateY(-10px); }
                to { opacity: 1; transform: translateY(0); }
            }
            .alert {
                animation: slideIn 0.3s ease-out;
            }
        `;
        document.head.appendChild(style);
    </script>
</body>
</html>