<?php
session_start();

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

require_once __DIR__ . '/config/db.php';


$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;
}

// Fetch user service bookings
$service_bookings = [];
$service_bookings_count = 0;
$pending_service_bookings = 0;

$service_bookings_table_check = $connection->query("SHOW TABLES LIKE 'service_bookings'");
if ($service_bookings_table_check && $service_bookings_table_check->num_rows > 0) {
    $service_bookings_stmt = $connection->prepare("
        SELECT id, service_name, service_id, customer_name, customer_email, customer_phone, address, city, pincode,
               area_sqft, preferred_date, preferred_time, selected_products, estimated_total, status, created_at
        FROM service_bookings
        WHERE user_id = ? OR customer_email = ?
        ORDER BY created_at DESC
        LIMIT 10
    ");

    if ($service_bookings_stmt) {
        $service_bookings_stmt->bind_param("is", $user_id, $user['email']);
        $service_bookings_stmt->execute();
        $service_bookings_result = $service_bookings_stmt->get_result();
        while ($row = $service_bookings_result->fetch_assoc()) {
            $service_bookings[] = $row;
        }
        $service_bookings_stmt->close();
    }

    $service_bookings_count = count($service_bookings);
    foreach ($service_bookings as $booking_row) {
        $booking_status = strtolower(trim((string)($booking_row['status'] ?? 'pending')));
        if (in_array($booking_status, ['pending', 'confirmed', 'approved', 'scheduled', 'in_progress'], true)) {
            $pending_service_bookings++;
        }
    }
}
?>
<!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>
        :root {
            --dash-bg: #f4efe8;
            --dash-surface: #ffffff;
            --dash-ink: #1f1b17;
            --dash-muted: #6c6359;
            --dash-border: #e6d9ca;
            --dash-accent: #b58a5a;
            --dash-accent-dark: #8a643f;
            --dash-danger: #be4f4f;
        }

        * { box-sizing: border-box; }

        body {
            margin: 0;
            background:
                radial-gradient(circle at 9% 10%, rgba(181, 138, 90, 0.14), transparent 32%),
                radial-gradient(circle at 92% 88%, rgba(131, 98, 66, 0.12), transparent 36%),
                linear-gradient(180deg, #f8f4ee 0%, #f1eae0 100%);
            color: var(--dash-ink);
            font-family: 'DM Sans', sans-serif;
        }

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

        .dashboard-container {
            width: 100%;
            margin: 0 auto;
            padding: 8px 0 46px;
            flex: 1;
        }

        .dashboard-header {
            background: linear-gradient(135deg, #1d1814 0%, #2f251c 48%, #4a3928 100%);
            color: #fff;
            padding: clamp(20px, 3vw, 32px);
            border-radius: 18px;
            margin-bottom: 20px;
            box-shadow: 0 18px 38px rgba(20, 14, 10, 0.22);
            border: 1px solid rgba(255, 255, 255, 0.08);
            display: none;
        }

        .dashboard-header h1 {
            margin: 0;
            font-size: clamp(24px, 4vw, 38px);
            line-height: 1.1;
            font-weight: 700;
        }

        .dashboard-header p {
            margin: 10px 0 0;
            color: rgba(255, 255, 255, 0.88);
            font-size: clamp(14px, 2vw, 17px);
        }

        .dashboard-header-info {
            margin-top: 16px;
            display: flex;
            gap: 14px;
            flex-wrap: wrap;
            font-size: 13px;
            color: rgba(255, 255, 255, 0.82);
        }

        .stats-container {
            display: grid;
            grid-template-columns: repeat(4, minmax(0, 1fr));
            gap: 14px;
            margin-bottom: 20px;
        }

        .stat-card {
            background: var(--dash-surface);
            border: 1px solid var(--dash-border);
            border-radius: 14px;
            padding: 18px;
            box-shadow: 0 10px 24px rgba(30, 23, 16, 0.08);
            display: flex;
            gap: 14px;
            align-items: center;
        }

        .stat-icon {
            width: 44px;
            height: 44px;
            display: grid;
            place-items: center;
            border-radius: 11px;
            color: #fff;
            background: linear-gradient(135deg, var(--dash-accent), var(--dash-accent-dark));
            font-size: 18px;
            flex: 0 0 44px;
        }

        .stat-number {
            margin: 0;
            color: var(--dash-ink);
            font-weight: 700;
            font-size: clamp(20px, 3vw, 30px);
            line-height: 1;
        }

        .stat-label {
            margin-top: 6px;
            color: var(--dash-muted);
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.06em;
            font-weight: 700;
        }

        .dashboard-layout {
            display: grid;
            grid-template-columns: 260px minmax(0, 1fr);
            gap: 18px;
            align-items: start;
        }

        .dashboard-sidebar {
            height: 100%;
            position: static;
            top: 108px;
            background: var(--dash-surface);
            border: 1px solid var(--dash-border);
            border-radius: 14px;
            box-shadow: 0 12px 26px rgba(30, 23, 16, 0.08);
            padding: 12px;
            z-index: 300;
        }

        .dashboard-main-content { min-width: 0; }

        .sidebar-toggle {
            display: none;
            border: none;
            background: linear-gradient(135deg, var(--dash-accent), var(--dash-accent-dark));
            color: #fff;
            border-radius: 10px;
            padding: 11px 14px;
            font-weight: 700;
            font-size: 14px;
            margin-bottom: 12px;
            box-shadow: 0 8px 20px rgba(181, 138, 90, 0.34);
        }

        .dashboard-sidebar-overlay {
            display: none;
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, 0.38);
            z-index: 250;
        }

        .tabs {
            display: flex;
            flex-direction: column;
            gap: 8px;
            margin-bottom: 0;
        }

        .tab-button {
            border: 1px solid #efe2d3;
            background: #faf5ee;
            color: #5e564e;
            border-radius: 10px;
            padding: 11px 12px;
            text-align: left;
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
        }

        .tab-button.active {
            color: #fff;
            border-color: transparent;
            background: linear-gradient(135deg, var(--dash-accent), var(--dash-accent-dark));
        }

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

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

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

        .content-wrapper {
            background: var(--dash-surface);
            border: 1px solid var(--dash-border);
            border-radius: 14px;
            padding: clamp(16px, 3vw, 24px);
            box-shadow: 0 12px 24px rgba(30, 23, 16, 0.08);
        }

        .section-title {
            margin: 0 0 18px;
            padding-bottom: 12px;
            border-bottom: 1px solid #ece4db;
            font-size: clamp(20px, 3vw, 27px);
            font-weight: 700;
            color: var(--dash-ink);
        }

        .welcome-section {
            background: linear-gradient(33deg, #8d7461 0%, #a1978e 48%, #62584e 100%);
            color: #fff;
            padding: clamp(20px, 4vw, 32px);
            border-radius: 16px;
            margin-bottom: 24px;
            box-shadow: 0 12px 32px rgba(20, 14, 10, 0.18);
            border: 1px solid rgba(255, 255, 255, 0.08);
        }

        .welcome-header {
            display: flex;
            flex-direction: column;
            gap: 12px;
            margin-bottom: 18px;
        }

        .welcome-title {
            margin: 0;
            font-size: clamp(24px, 5vw, 36px);
            line-height: 1.2;
            font-weight: 700;
        }

        .welcome-subtitle {
            margin: 0;
            color: rgba(255, 255, 255, 0.88);
            font-size: clamp(13px, 2vw, 16px);
            font-weight: 500;
            line-height: 1.5;
        }

        .welcome-info {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            margin-top: 12px;
            padding-top: 12px;
            border-top: 1px solid rgba(255, 255, 255, 0.12);
        }

        .welcome-info-item {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: clamp(12px, 1.5vw, 14px);
            color: rgba(255, 255, 255, 0.82);
        }

        .welcome-info-item i {
            font-size: clamp(14px, 2vw, 16px);
        }

        .orders-table { overflow-x: auto; }

        table {
            width: 100%;
            border-collapse: collapse;
            min-width: 680px;
            background: #fff;
            border-radius: 10px;
            overflow: hidden;
        }

        th {
            padding: 12px;
            text-align: left;
            background: #f5efe8;
            color: #5f554b;
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            border-bottom: 1px solid #ebdfd1;
        }

        td {
            padding: 12px;
            border-bottom: 1px solid #f1e8dd;
            color: #4f473f;
            font-size: 14px;
        }

        tr:hover { background: #fdfaf6; }

        .status-badge {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border-radius: 999px;
            padding: 5px 10px;
            font-size: 11px;
            font-weight: 700;
            letter-spacing: 0.04em;
            text-transform: uppercase;
        }

        .status-badge.pending, .status-badge.badge-pending { background: #fff3cd; color: #856404; }
        .status-badge.processing, .status-badge.badge-scheduled { background: #cfe2ff; color: #084298; }
        .status-badge.delivered, .status-badge.badge-approved, .status-badge.badge-completed { background: #d4edda; color: #155724; }
        .status-badge.cancelled, .status-badge.badge-declined { background: #f8d7da; color: #842029; }

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

        .profile-avatar-wrapper {
            display: flex;
            gap: 16px;
            align-items: center;
            margin-bottom: 18px;
            padding: 14px;
            border: 1px solid #efe2d3;
            border-radius: 12px;
            background: #fcf8f2;
        }

        .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 16px rgba(0,0,0,0.14); background: #f0f0f0;
        }

        .avatar-edit-btn {
            position: absolute; right: -4px; bottom: -4px;
            background: var(--dash-accent); color: #fff;
            padding: 7px 10px; border: none; border-radius: 16px;
            font-size: 11px; cursor: pointer; font-weight: 700;
        }

        .form-group { margin-bottom: 14px; }
        label { display: block; margin-bottom: 7px; font-weight: 600; color: #3e352d; font-size: 13px; }

        input[type="text"], input[type="email"], input[type="tel"], input[type="password"], input[type="date"], select, textarea {
            width: 100%;
            padding: 11px 12px;
            border: 1px solid #ddd2c4;
            border-radius: 8px;
            font-family: inherit;
            font-size: 14px;
            background: #fff;
            color: #2e2721;
        }

        input:focus, select:focus, textarea:focus {
            outline: none;
            border-color: var(--dash-accent);
            box-shadow: 0 0 0 3px rgba(181, 138, 90, 0.15);
        }

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

        .form-section { margin-bottom: 18px; padding-bottom: 14px; border-bottom: 1px solid #ede4d8; }
        .form-section:last-child { border-bottom: none; }
        .form-section-title { margin: 0 0 12px; font-size: 15px; font-weight: 700; color: #3e352d; }

        .form-row {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 12px;
        }

        .btn {
            border: none;
            border-radius: 8px;
            padding: 10px 15px;
            font-size: 13px;
            font-weight: 700;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            letter-spacing: 0.03em;
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--dash-accent), var(--dash-accent-dark));
            color: #fff;
            box-shadow: 0 8px 18px rgba(181, 138, 90, 0.3);
        }

        .btn-secondary { background: #e9e0d5; color: #3e352d; margin-left: 8px; }

        .alert {
            padding: 11px 13px;
            border-radius: 8px;
            margin-bottom: 14px;
            font-size: 13px;
            border: 1px solid transparent;
        }

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

        .no-data {
            background: #fcf8f2;
            padding: 28px 18px;
            text-align: center;
            border-radius: 12px;
            border: 1px dashed #deccb8;
        }

        .no-data h3 { color: #5a5148; margin: 0 0 10px; font-size: 18px; }
        .no-data p { color: #7b7167; margin-bottom: 14px; }

        .consultation-card {
            background: #fff;
            padding: 16px;
            border-radius: 10px;
            margin-bottom: 12px;
            border: 1px solid #ecdfd1;
            box-shadow: 0 6px 18px rgba(0,0,0,0.05);
        }

        .consultation-card h4 { margin: 0 0 10px; color: #332b24; font-weight: 700; }
        .consultation-card p { margin: 4px 0; color: #665d53; font-size: 13px; }

        .booking-list {
            display: grid;
            gap: 14px;
        }

        .booking-card {
            background: #fff;
            border: 1px solid #ecdfd1;
            border-radius: 14px;
            padding: 18px;
            box-shadow: 0 8px 22px rgba(0, 0, 0, 0.05);
        }

        .booking-card-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 12px;
            margin-bottom: 14px;
        }

        .booking-card-title {
            margin: 0;
            font-size: 18px;
            color: #2f251f;
            font-weight: 700;
        }

        .booking-card-subtitle {
            margin: 6px 0 0;
            color: #6a6055;
            font-size: 13px;
        }

        .booking-card-grid {
            display: grid;
            grid-template-columns: repeat(3, minmax(0, 1fr));
            gap: 12px;
            margin-bottom: 14px;
        }

        .booking-info-block {
            border: 1px solid #ede2d4;
            border-radius: 12px;
            padding: 12px 13px;
            background: #fcf8f3;
            min-width: 0;
        }

        .booking-info-label {
            font-size: 11px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.06em;
            color: #7a6f63;
            margin-bottom: 6px;
        }

        .booking-info-value {
            font-size: 14px;
            color: #3f352d;
            font-weight: 600;
            line-height: 1.5;
            overflow-wrap: anywhere;
        }

        .booking-products {
            margin-top: 4px;
            border-top: 1px solid #efe4d8;
            padding-top: 14px;
        }

        .booking-products-title {
            margin: 0 0 10px;
            font-size: 13px;
            color: #5d5248;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            font-weight: 700;
        }

        .booking-product-item {
            display: flex;
            justify-content: space-between;
            gap: 12px;
            padding: 8px 0;
            border-bottom: 1px solid #f3ebe2;
            font-size: 13px;
            color: #564c43;
        }

        .booking-product-item:last-child {
            border-bottom: none;
        }

        .booking-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 12px;
            flex-wrap: wrap;
            margin-top: 14px;
            padding-top: 14px;
            border-top: 1px solid #efe4d8;
        }

        .booking-total {
            font-size: 18px;
            font-weight: 700;
            color: var(--dash-accent-dark);
        }

        .overview-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 12px;
        }

        .overview-stats-grid {
            display: grid;
            grid-template-columns: repeat(4, minmax(0, 1fr));
            gap: 12px;
            margin-bottom: 14px;
        }

        .overview-favorites-card {
            border: 1px solid #eadfce;
            border-radius: 12px;
            background: #fff;
            padding: 14px;
        }

        .overview-card {
            border: 1px solid #eadfce;
            border-radius: 10px;
            background: #fcf8f3;
            padding: 15px;
        }

        .overview-card h3 {
            margin: 0 0 8px;
            font-size: 16px;
            color: #332b24;
            font-weight: 700;
        }

        .overview-card p {
            margin: 0;
            color: #6a6055;
            font-size: 13px;
            line-height: 1.6;
        }

        .tab-pill {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 20px;
            height: 20px;
            border-radius: 999px;
            font-size: 11px;
            font-weight: 700;
            background: rgba(255, 255, 255, 0.7);
            color: #664828;
            margin-left: auto;
            padding: 0 6px;
        }

        .tab-button.active .tab-pill {
            background: rgba(255, 255, 255, 0.22);
            color: #fff;
        }

        .favorites-status {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
            flex-wrap: wrap;
            margin-bottom: 15px;
            color: #6a6055;
            font-size: 13px;
        }

        .favorites-live-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            display: inline-block;
            background: #1f9b56;
            margin-right: 6px;
        }

        .favorites-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 14px;
        }

        .favorite-card {
            border: 1px solid #ebdece;
            border-radius: 12px;
            background: #fff;
            overflow: hidden;
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.06);
            display: flex;
            flex-direction: column;
        }

        .favorite-image {
            aspect-ratio: 16 / 10;
            background: #eee3d7;
            overflow: hidden;
        }

        .favorite-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .favorite-body {
            padding: 13px;
            display: flex;
            flex-direction: column;
            gap: 8px;
            flex-grow: 1;
        }

        .favorite-body h4 {
            margin: 0;
            color: #2f251f;
            font-size: 19px;
            line-height: 1.2;
        }

        .favorite-body p {
            margin: 0;
            color: #6a6055;
            font-size: 13px;
            line-height: 1.55;
            flex-grow: 1;
        }

        .favorite-actions {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
            margin-top: 4px;
        }

        #consultationModal > div {
            background: #fff;
            border-radius: 12px;
            border: 1px solid #e8dccc;
       }

       @media (max-width: 1200px) {
           .stats-container { grid-template-columns: repeat(2, minmax(0, 1fr)); }
           .overview-stats-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
           .welcome-section { padding: clamp(18px, 3vw, 28px); }
       }

       @media (max-width: 991.98px) {
           .dashboard-wrapper { margin-top: 70px; }
           .dashboard-container { width: min(1320px, 100% - 18px); padding-top: 0px; }
           .dashboard-layout { display: block; }
           .sidebar-toggle { display: inline-flex; align-items: center; gap: 7px; }
           .dashboard-sidebar {
               position: fixed;
               top: 0;
               left: 0;
               width: min(86vw, 320px);
               height: 100vh;
               border-radius: 0 14px 14px 0;
               transform: translateX(-105%);
               transition: transform .3s ease;
               overflow-y: auto;
               padding-top: 72px;
               z-index: 300;
           }
           .dashboard-sidebar.open { transform: translateX(0); }
           .dashboard-sidebar-overlay.show { display: block; }
           .welcome-section { margin-bottom: 20px; }
           .welcome-info { gap: 10px; }
       }

       @media (max-width: 767.98px) {
           .stats-container { grid-template-columns: 1fr; }
           .form-row { grid-template-columns: 1fr; }
           .overview-grid { grid-template-columns: 1fr; }
           .overview-stats-grid { grid-template-columns: 1fr; }
           .favorites-grid { grid-template-columns: 1fr; }
           .booking-card-grid { grid-template-columns: 1fr; }
           .btn-secondary { margin-left: 0; margin-top: 8px; }
           .profile-avatar-wrapper { flex-direction: column; align-items: flex-start; }
           #consultationModal > div { width: 94% !important; padding: 18px !important; }
           #consultationModal [style*="grid-template-columns: 1fr 1fr"] { grid-template-columns: 1fr !important; }
           #consultationModal [style*="display: flex; gap: 15px"] { flex-direction: column; }
           .welcome-info {
               flex-direction: column;
               gap: 8px;
           }
           .welcome-info-item {
               display: flex;
               align-items: center;
               gap: 8px;
           }
       }

       @media (max-width: 575.98px) {
           .dashboard-wrapper { margin-top: 60px; }
           .dashboard-header { border-radius: 12px; }
           .dashboard-header-info { gap: 8px; }
           .content-wrapper { border-radius: 12px; }
           .btn { width: 100%; }
           .welcome-section {
               padding: clamp(16px, 3vw, 24px);
               margin-bottom: 16px;
               border-radius: 12px;
           }
           .welcome-title {
               font-size: clamp(20px, 4vw, 28px);
           }
           .welcome-subtitle {
               font-size: clamp(12px, 1.8vw, 14px);
           }
           .welcome-info { margin-top: 10px; padding-top: 10px; }
           .welcome-info-item {
               font-size: 11px;
           }
       }
   </style>
</head>
<body>
    <div class="dashboard-wrapper">
        <!-- Navigation Header -->
        <?php include 'customer-header.php'; ?>

        <div class="dashboard-container">
            <div class="dashboard-header">
                <h1><i class="fas fa-chart-line"></i> 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>

            <button class="sidebar-toggle" type="button" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i> Dashboard Menu
            </button>

            <div class="dashboard-layout">
                <aside class="dashboard-sidebar" id="dashboardSidebar">
                    <div class="tabs">
                        <button class="tab-button active" onclick="switchTab('overview', event)">
                            <i class="fas fa-chart-pie"></i> Overview
                        </button>
                        <button class="tab-button" onclick="switchTab('orders', event)">
                            <i class="fas fa-shopping-bag"></i> Orders
                            <span class="tab-pill"><?php echo count($orders); ?></span>
                        </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
                            <span class="tab-pill"><?php echo count($consultations); ?></span>
                        </button>
                        <button class="tab-button" onclick="switchTab('service-bookings', event)">
                            <i class="fas fa-couch"></i> Service Bookings
                            <span class="tab-pill"><?php echo $service_bookings_count; ?></span>
                        </button>
                        <button class="tab-button" onclick="switchTab('favorites', event)">
                            <i class="fas fa-heart"></i> Favorites
                            <span class="tab-pill" id="favoritesSidebarCount">0</span>
                        </button>
                    </div>
                </aside>

                <div class="dashboard-main-content">
            <!-- Overview Tab -->
            <div id="overview" class="tab-content active">
                <div class="welcome-section">
                    <div class="welcome-header">
                        <h1 class="welcome-title">Welcome, <?php echo htmlspecialchars($user['name'] ?? 'Guest'); ?>! 🏡</h1>
                        <p class="welcome-subtitle">Manage your orders, profile, and track your interior design projects</p>
                    </div>
                    <div class="welcome-info">
                        <div class="welcome-info-item">
                            <i class="fas fa-envelope"></i>
                            <span><?php echo htmlspecialchars($user['email'] ?? 'No email'); ?></span>
                        </div>
                        <div class="welcome-info-item">
                            <i class="fas fa-phone"></i>
                            <span><?php echo htmlspecialchars($user['phone'] ?? 'No phone'); ?></span>
                        </div>
                    </div>
                </div>
                <div class="content-wrapper">
                    <h2 class="section-title"><i class="fas fa-chart-line"></i> Dashboard Overview</h2>
                    <div class="overview-stats-grid">
                        <div class="stat-card">
                            <div class="stat-icon"><i class="fas fa-box"></i></div>
                            <div>
                                <div class="stat-number"><?php echo $stats['total_orders'] ?? 0; ?></div>
                                <div class="stat-label">Total Orders</div>
                            </div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon"><i class="fas fa-circle-check"></i></div>
                            <div>
                                <div class="stat-number"><?php echo $stats['completed_orders'] ?? 0; ?></div>
                                <div class="stat-label">Completed</div>
                            </div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon"><i class="fas fa-hourglass-half"></i></div>
                            <div>
                                <div class="stat-number"><?php echo $stats['pending_orders'] ?? 0; ?></div>
                                <div class="stat-label">Pending</div>
                            </div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon"><i class="fas fa-wallet"></i></div>
                            <div>
                                <div class="stat-number">Rs <?php echo number_format($stats['total_spent'] ?? 0, 0); ?></div>
                                <div class="stat-label">Total Spent</div>
                            </div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon"><i class="fas fa-couch"></i></div>
                            <div>
                                <div class="stat-number"><?php echo $service_bookings_count; ?></div>
                                <div class="stat-label">Service Bookings</div>
                            </div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon"><i class="fas fa-ruler-combined"></i></div>
                            <div>
                                <div class="stat-number"><?php echo $pending_service_bookings; ?></div>
                                <div class="stat-label">Active Booking Requests</div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>

            <!-- Orders Tab -->
            <div id="orders" class="tab-content">
                <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>Rs <?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"><i class="fas fa-camera"></i> 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>

            <!-- Favorites Tab -->
            <div id="favorites" class="tab-content">
                <div class="content-wrapper">
                    <h2 class="section-title"><i class="fas fa-heart"></i> Favorite Services</h2>
                    <div class="favorites-status">
                        <div>
                            <span class="favorites-live-dot"></span>
                            <span id="favoritesSyncText">Syncing favorites in real time...</span>
                        </div>
                        <button type="button" class="btn btn-secondary" onclick="fetchFavorites(true)">
                            <i class="fas fa-rotate"></i> Refresh
                        </button>
                    </div>
                    <div id="favoritesAlert"></div>
                    <div id="favoritesContainer"></div>
                </div>
            </div>

            <!-- Service Bookings Tab -->
            <div id="service-bookings" class="tab-content">
                <div class="content-wrapper">
                    <div style="display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:20px;">
                        <h2 class="section-title" style="margin:0;padding-bottom:0;border:none;"><i class="fas fa-couch"></i> Your Service Bookings</h2>
                        <a href="service.php" class="btn btn-primary"><i class="fas fa-plus"></i> Book New Service</a>
                    </div>

                    <?php if (!empty($service_bookings)): ?>
                        <div class="booking-list">
                            <?php foreach ($service_bookings as $booking): ?>
                                <?php
                                    $booking_status = strtolower(trim((string)($booking['status'] ?? 'pending')));
                                    if ($booking_status === '' || $booking_status === 'null' || $booking_status === '0') {
                                        $booking_status = 'pending';
                                    }
                                    $status_class = str_replace('_', '-', $booking_status);
                                    if ($status_class === 'confirmed' || $status_class === 'approved' || $status_class === 'scheduled' || $status_class === 'in-progress') {
                                        $status_class = 'processing';
                                    } elseif ($status_class === 'completed') {
                                        $status_class = 'delivered';
                                    }
                                    $selected_products = [];
                                    if (!empty($booking['selected_products'])) {
                                        $decoded_products = json_decode((string)$booking['selected_products'], true);
                                        if (is_array($decoded_products)) {
                                            $selected_products = $decoded_products;
                                        }
                                    }
                                    $booking_location = trim(implode(', ', array_filter([
                                        $booking['address'] ?? '',
                                        $booking['city'] ?? '',
                                        $booking['pincode'] ?? ''
                                    ])));
                                ?>
                                <article class="booking-card">
                                    <div class="booking-card-header">
                                        <div>
                                            <h3 class="booking-card-title"><?php echo htmlspecialchars($booking['service_name'] ?? 'Service Booking'); ?></h3>
                                            <p class="booking-card-subtitle">Booking #<?php echo htmlspecialchars($booking['id']); ?> placed on <?php echo !empty($booking['created_at']) ? date('M d, Y', strtotime($booking['created_at'])) : 'N/A'; ?></p>
                                        </div>
                                        <span class="status-badge <?php echo htmlspecialchars($status_class); ?>">
                                            <?php echo htmlspecialchars(ucfirst(str_replace('_', ' ', $booking_status))); ?>
                                        </span>
                                    </div>

                                    <div class="booking-card-grid">
                                        <div class="booking-info-block">
                                            <div class="booking-info-label">Preferred Visit</div>
                                            <div class="booking-info-value">
                                                <?php echo !empty($booking['preferred_date']) ? date('M d, Y', strtotime($booking['preferred_date'])) : 'Not selected'; ?><br>
                                                <span style="color:#7a6f63;font-size:13px;"><?php echo htmlspecialchars($booking['preferred_time'] ?: 'Flexible'); ?></span>
                                            </div>
                                        </div>
                                        <div class="booking-info-block">
                                            <div class="booking-info-label">Project Size</div>
                                            <div class="booking-info-value"><?php echo !empty($booking['area_sqft']) ? number_format((float)$booking['area_sqft']) . ' sqft' : 'Not shared yet'; ?></div>
                                        </div>
                                        <div class="booking-info-block">
                                            <div class="booking-info-label">Location</div>
                                            <div class="booking-info-value"><?php echo htmlspecialchars($booking_location !== '' ? $booking_location : 'Address will be confirmed later'); ?></div>
                                        </div>
                                    </div>

                                    <div class="booking-products">
                                        <h4 class="booking-products-title">Selected Products</h4>
                                        <?php if (!empty($selected_products)): ?>
                                            <?php foreach ($selected_products as $selected_product): ?>
                                                <div class="booking-product-item">
                                                    <span>
                                                        <?php echo htmlspecialchars($selected_product['name'] ?? 'Product'); ?>
                                                        <small style="color:#8a7d70;">x<?php echo htmlspecialchars(rtrim(rtrim(number_format((float)($selected_product['quantity'] ?? 1), 2, '.', ''), '0'), '.')); ?></small>
                                                    </span>
                                                    <strong>Rs <?php echo number_format((float)($selected_product['line_cost'] ?? 0), 0); ?></strong>
                                                </div>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            <div class="booking-product-item">
                                                <span>No additional products were selected.</span>
                                                <strong>Base service only</strong>
                                            </div>
                                        <?php endif; ?>
                                    </div>

                                    <div class="booking-footer">
                                        <div style="color:#6a6055;font-size:13px;">
                                            <?php if (!empty($booking['customer_phone'])): ?>
                                                <i class="fas fa-phone"></i> <?php echo htmlspecialchars($booking['customer_phone']); ?>
                                            <?php else: ?>
                                                <i class="fas fa-circle-info"></i> Our team will contact you with the next step.
                                            <?php endif; ?>
                                        </div>
                                        <div class="booking-total">Estimated total: Rs <?php echo number_format((float)($booking['estimated_total'] ?? 0), 0); ?></div>
                                    </div>
                                </article>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="no-data">
                            <h3>No Service Bookings Yet</h3>
                            <p>Your booked services will appear here with schedule, products, and estimated totals.</p>
                            <a href="service.php" class="btn btn-primary">Explore Services</a>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

                </div>
            </div>

            <div class="dashboard-sidebar-overlay" id="dashboardSidebarOverlay" onclick="closeSidebar()"></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;">&times;</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">Rs 10,000 - Rs 50,000</option>
                                        <option value="50k-100k">Rs 50,000 - Rs 100,000</option>
                                        <option value="100k-200k">Rs 100,000 - Rs 200,000</option>
                                        <option value="200k-500k">Rs 200,000 - Rs 500,000</option>
                                        <option value="500k+">Rs 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 toggleSidebar(forceOpen) {
            const sidebar = document.getElementById('dashboardSidebar');
            const overlay = document.getElementById('dashboardSidebarOverlay');
            if (!sidebar || !overlay) return;

            const shouldOpen = typeof forceOpen === 'boolean' ? forceOpen : !sidebar.classList.contains('open');
            sidebar.classList.toggle('open', shouldOpen);
            overlay.classList.toggle('show', shouldOpen);
            document.body.style.overflow = shouldOpen ? 'hidden' : '';
        }

        function closeSidebar() {
            toggleSidebar(false);
        }

        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');
            } else {
                const targetBtn = document.querySelector(`.tab-button[onclick*="'${tabName}'"]`);
                if (targetBtn) targetBtn.classList.add('active');
            }

            // Auto close mobile sidebar after selection
            if (window.innerWidth <= 991) {
                closeSidebar();
            }

            if (tabName === 'favorites') {
                fetchFavorites(false);
            }

        }

        let favoritesPollingInterval = null;
        let lastFavoritesHash = '';

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

        function renderFavorites(favorites) {
            const container = document.getElementById('favoritesContainer');
            const sidebarCount = document.getElementById('favoritesSidebarCount');
            if (!container) return;

            const count = Array.isArray(favorites) ? favorites.length : 0;
            if (sidebarCount) sidebarCount.textContent = count;

            if (!count) {
                container.innerHTML = `
                    <div class="no-data">
                        <h3>No Favorite Services Yet</h3>
                        <p>Go to the services page and click the heart icon to save services. They will appear here instantly.</p>
                        <a href="service.php" class="btn btn-primary">Browse Services</a>
                    </div>
                `;
                return;
            }

            container.innerHTML = `
                <div class="favorites-grid">
                    ${favorites.map(item => {
                        const serviceId = Number(item.service_id || 0);
                        const title = buildSafeText(item.service_title || 'Service');
                        const image = buildSafeText(item.service_image || 'assets/img/service/service_2_1.jpg');
                        const description = buildSafeText(item.service_description || '');
                        return `
                            <article class="favorite-card" id="favorite-item-${serviceId}">
                                <div class="favorite-image">
                                    <img src="${image}" alt="${title}">
                                </div>
                                <div class="favorite-body">
                                    <h4>${title}</h4>
                                    <p>${description}</p>
                                    <div class="favorite-actions">
                                        <a href="service-details.php?id=${serviceId}" class="btn btn-secondary">View Details</a>
                                        <button type="button" class="btn btn-primary" onclick="removeFavoriteService(${serviceId})">Remove</button>
                                    </div>
                                </div>
                            </article>
                        `;
                    }).join('')}
                </div>
            `;
        }

        function setFavoritesSyncStatus(message, isHealthy = true) {
            const syncText = document.getElementById('favoritesSyncText');
            const liveDot = document.querySelector('.favorites-live-dot');
            if (syncText) syncText.textContent = message;
            if (liveDot) liveDot.style.background = isHealthy ? '#1f9b56' : '#be4f4f';
        }

        function fetchFavorites(showAlert = false) {
            return fetch('api/service-favorites-api.php?action=get_all', {
                method: 'GET',
                credentials: 'same-origin',
                headers: {
                    'Accept': 'application/json'
                }
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Unable to fetch favorite services');
                    }
                    return response.json();
                })
                .then(data => {
                    if (!data.success || !Array.isArray(data.favorites)) {
                        throw new Error(data.message || 'Invalid favorites response');
                    }

                    const currentHash = JSON.stringify(data.favorites.map(item => [item.service_id, item.added_at]));
                    if (currentHash !== lastFavoritesHash) {
                        renderFavorites(data.favorites);
                        lastFavoritesHash = currentHash;
                    } else {
                        const sidebarCount = document.getElementById('favoritesSidebarCount');
                        if (sidebarCount) sidebarCount.textContent = data.favorites.length;
                    }

                    setFavoritesSyncStatus('Last synced at ' + new Date().toLocaleTimeString(), true);
                    if (showAlert) {
                        document.getElementById('favoritesAlert').innerHTML = '<div class="alert success">Favorites refreshed successfully.</div>';
                        setTimeout(() => {
                            document.getElementById('favoritesAlert').innerHTML = '';
                        }, 2500);
                    }
                })
                .catch(error => {
                    setFavoritesSyncStatus('Sync issue, retrying automatically...', false);
                    if (showAlert) {
                        document.getElementById('favoritesAlert').innerHTML = '<div class="alert error">' + buildSafeText(error.message || 'Failed to fetch favorites') + '</div>';
                    }
                });
        }

        function removeFavoriteService(serviceId) {
            fetch('api/service-favorites-api.php?action=remove', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    service_id: serviceId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    localStorage.setItem('serviceFavoritesSync', JSON.stringify({
                        source: 'customer-dashboard',
                        action: 'remove',
                        service_id: serviceId,
                        ts: Date.now()
                    }));
                    fetchFavorites(true);
                } else {
                    document.getElementById('favoritesAlert').innerHTML = '<div class="alert error">' + buildSafeText(data.message || 'Failed to remove favorite') + '</div>';
                }
            })
            .catch(() => {
                document.getElementById('favoritesAlert').innerHTML = '<div class="alert error">Network error while removing favorite.</div>';
            });
        }

        function startFavoritesPolling() {
            fetchFavorites(false);
            favoritesPollingInterval = setInterval(() => {
                fetchFavorites(false);
            }, 5000);
        }

        // ========== 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 && profileSection && !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();

            // Start favorites live sync
            startFavoritesPolling();

            // Default tab for new dashboard structure
            switchTab('overview');
        });

        // Cross-tab live refresh when favorites are changed on service page
        window.addEventListener('storage', function(event) {
            if (event.key === 'serviceFavoritesSync') {
                fetchFavorites(false);
            }
        });

        // Same-tab custom event fallback
        window.addEventListener('service-favorites-updated', function() {
            fetchFavorites(false);
        });

        window.addEventListener('resize', function () {
            if (window.innerWidth > 991) {
                closeSidebar();
            }
        });

        // 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);
            }
            if (favoritesPollingInterval) {
                clearInterval(favoritesPollingInterval);
            }
        }

        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>


