<?php
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
require_once(__DIR__ . '../core/init.php');

// ------------------------------------------------------------------------
// 1. CONFIGURACIÓN INICIAL Y CONSTANTES GLOBALES
// ------------------------------------------------------------------------

$businessData = $client_info;
if (!defined('BUSINESS_NAME')) define('BUSINESS_NAME', $businessData['business_name'] ?? 'FlowCRM');
if (!defined('LOGO_FILENAME')) define('LOGO_FILENAME', $businessData['logo_url'] ?? 'img/favicon.png');
if (!defined('WHATSAPP_NUMBER_CLICK')) define('WHATSAPP_NUMBER_CLICK', preg_replace('/[^0-9]/', '', $businessData['whatsapp'] ?? ''));
if (!defined('EMAIL_PRIMARY')) define('EMAIL_PRIMARY', $businessData['email'] ?? 'info@flowcrm.com');
if (!defined('PHONE_PRIMARY_CLICK')) define('PHONE_PRIMARY_CLICK', preg_replace('/[^0-9]/', '', $businessData['phone'] ?? ''));
if (!defined('BUSINESS_TIMEZONE')) define('BUSINESS_TIMEZONE', $businessData['timezone'] ?? 'America/Los_Angeles');

// Establecer la zona horaria del negocio
date_default_timezone_set(BUSINESS_TIMEZONE);

// Definir tiempo actual para toda la lógica
$currentTime = new DateTime('now');
$currentDayName = $currentTime->format('l');

// ------------------------------------------------------------------------
// 2. CONFIGURACIÓN Y CARGA DE DATOS DEL SCHEDULER (SÓLO LECTURA)
// ------------------------------------------------------------------------

$db_schedule_config = ['slot_duration' => 60, 'capacity' => 1];
$db_weekly_hours = [];
$db_blocked_dates = [];
$occupied_slots = [];
$available_services = [];
$config = null; // Inicialización de $config

try {
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // 2.1 Cargar Configuración de Agenda (Asegurando start_time, end_time para $config)
    $stmt_sched_config = $pdo->prepare("SELECT start_time, end_time, slot_duration, capacity FROM schedule_config WHERE id = 1 LIMIT 1");
    $stmt_sched_config->execute();
    $config = $stmt_sched_config->fetch(PDO::FETCH_ASSOC); 

    if ($config) {
        $db_schedule_config = $config;
        $db_schedule_config['slot_duration'] = (int)$db_schedule_config['slot_duration'];
        $db_schedule_config['capacity'] = (int)$db_schedule_config['capacity'];
    }

    // 2.2 Cargar Horarios Semanales (Completo)
    $stmt_weekly_hours = $pdo->prepare("SELECT day, is_open, open_time, close_time FROM cms_weekly_hours WHERE schedule_id = 1");
    $stmt_weekly_hours->execute();
    while ($row = $stmt_weekly_hours->fetch(PDO::FETCH_ASSOC)) {
        $db_weekly_hours[$row['day']] = [
            'is_open' => (bool)$row['is_open'],
            'open_time' => $row['open_time'],
            'close_time' => $row['close_time']
        ];
    }
    
    // 2.3 Cargar Fechas Bloqueadas
    $stmt_blocked_dates = $pdo->prepare("SELECT blocked_date FROM cms_blocked_dates");
    $stmt_blocked_dates->execute();
    $db_blocked_dates = $stmt_blocked_dates->fetchAll(PDO::FETCH_COLUMN);

    // 2.4 Cargar Slots Ocupados
    $stmt_occupied_slots = $pdo->prepare("SELECT appointment_date, appointment_time, COUNT(id) as count 
                                     FROM unique_appointments 
                                     WHERE status NOT IN ('cancelled', 'completed') 
                                     GROUP BY appointment_date, appointment_time");
    $stmt_occupied_slots->execute();
    
    $occupied_data = $stmt_occupied_slots->fetchAll(PDO::FETCH_ASSOC);
    foreach ($occupied_data as $slot) {
        $time_key = substr($slot['appointment_time'], 0, 5); 
        $key = $slot['appointment_date'] . ' ' . $time_key;
        $occupied_slots[$key] = (int)$slot['count'];
    }

    // 2.5 Cargar Servicios Disponibles
    $stmt_services = $pdo->prepare("SELECT id, name FROM services ORDER BY name ASC");
    $stmt_services->execute();
    $available_services_raw = $stmt_services->fetchAll(PDO::FETCH_ASSOC);
    foreach ($available_services_raw as $service) {
        $available_services[] = ['id' => $service['id'], 'name' => htmlspecialchars($service['name'])];
    }

} catch (PDOException $e) {
    error_log("DASHBOARD CONFIG ERROR: " . $e->getMessage());
    die("Error loading configuration. Please try again later.");
}

// ------------------------------------------------------------------------
// 3. CARGA DE LINKS DE RESEÑA
// ------------------------------------------------------------------------

$review_links_stmt = $pdo->prepare("SELECT platform_name, link_url FROM cms_review_links WHERE hero_id = 1 AND platform_name IN ('Google', 'Facebook', 'Yelp')");
$review_links_stmt->execute();
$links = $review_links_stmt->fetchAll(PDO::FETCH_KEY_PAIR);

if (!defined('REVIEW_LINK_GOOGLE')) define('REVIEW_LINK_GOOGLE', $links['Google'] ?? 'https://google.com/reviews');
if (!defined('REVIEW_LINK_FACEBOOK')) define('REVIEW_LINK_FACEBOOK', $links['Facebook'] ?? 'https://facebook.com');
if (!defined('REVIEW_LINK_YELP')) define('REVIEW_LINK_YELP', $links['Yelp'] ?? 'https://yelp.com');

// ------------------------------------------------------------------------
// 4. OBTENCIÓN DE DATOS DEL CLIENTE Y RESUMEN DE ACTIVIDAD
// ------------------------------------------------------------------------

// OBTENER DATOS PRINCIPALES DEL CLIENTE (Añadiendo profile_picture_url)
$stmt = $pdo->prepare("SELECT first_name, last_name, phone, mobile, email, street_address, city, state_province, zip_code, access_code, profile_picture_url FROM clients WHERE id = ?");
$stmt->execute([$client_id]);
$client_data = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];

// OBTENER PRÓXIMA CITA
$next_appointment = ['date' => 'N/A', 'time_slot' => 'No upcoming appointment scheduled', 'next_service_date' => null, 'status' => null];
$stmt = $pdo->prepare("SELECT appointment_date, appointment_time, status FROM unique_appointments WHERE client_id = ? AND status IN ('pending', 'confirmed') AND appointment_date >= CURDATE() ORDER BY appointment_date ASC, appointment_time ASC LIMIT 1");
$stmt->execute([$client_id]);
if ($appointment = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $next_appointment['date'] = date("D, F d, Y", strtotime($appointment['appointment_date']));
    $next_appointment['time_slot'] = date("g:i A", strtotime($appointment['appointment_time'])); 
    $next_appointment['next_service_date'] = $appointment['appointment_date'];
    $next_appointment['status'] = $appointment['status'];
}

// OBTENER FACTURA PENDIENTE
$pending_invoice = ['amount' => 0.00, 'due_date' => 'N/A', 'external_id' => null];
$stmt = $pdo->prepare("SELECT external_id, total_amount, due_date FROM invoices WHERE client_id = ? AND status IN ('pendiente', 'enviada') ORDER BY invoice_date DESC LIMIT 1");
$stmt->execute([$client_id]);
if ($invoice = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $pending_invoice['amount'] = $invoice['total_amount'];
    $pending_invoice['due_date'] = $invoice['due_date'] ? date("M d, Y", strtotime($invoice['due_date'])) : 'No Date Set';
    $pending_invoice['external_id'] = $invoice['external_id'];
}

// OBTENER ÚLTIMA QUEJA
$last_complaint = ['status' => 'No Report', 'subject' => 'No recent reports.', 'reported_on' => 'N/A'];
$stmt = $pdo->prepare("SELECT title, status, created_at FROM complaints WHERE client_id = ? ORDER BY created_at DESC LIMIT 1");
$stmt->execute([$client_id]);
if ($complaint = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $last_complaint['status'] = $complaint['status'];
    $last_complaint['subject'] = $complaint['title'];
    $last_complaint['reported_on'] = date("M d, Y", strtotime($complaint['created_at']));
}

// OBTENER LAS ÚLTIMAS 3 FACTURAS PAGADAS
$recent_paid_invoices = []; 
$stmt = $pdo->prepare("SELECT total_amount, invoice_date FROM invoices WHERE client_id = ? AND status = 'pagada' ORDER BY invoice_date DESC LIMIT 3");
$stmt->execute([$client_id]);
$recent_paid_invoices_raw = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($recent_paid_invoices_raw as $invoice) {
    $recent_paid_invoices[] = ['amount' => number_format($invoice['total_amount'], 2), 'date' => date("M d, Y", strtotime($invoice['invoice_date']))];
}

// OBTENER LOS ÚLTIMOS 3 SERVICIOS COMPLETADOS
$recent_completed_services = [];
$stmt = $pdo->prepare("SELECT ua.id, ua.appointment_date, ua.appointment_time, s.name FROM unique_appointments ua LEFT JOIN services s ON ua.service_id = s.id WHERE ua.client_id = ? AND ua.status = 'completed' ORDER BY ua.appointment_date DESC, ua.appointment_time DESC LIMIT 3");
$stmt->execute([$client_id]);
$recent_completed_services_raw = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($recent_completed_services_raw as $service) {
    $recent_completed_services[] = [
        'id' => $service['id'], 
        'date' => date("M d, Y", strtotime($service['appointment_date'])),
        'time' => date("g:i A", strtotime($service['appointment_time'])),
        'type' => htmlspecialchars($service['name'] ?: 'Cleaning Service')
    ];
}

// OBTENER TODAS LAS CITAS ACTIVAS
$active_appointments = [];
$stmt = $pdo->prepare("SELECT id, appointment_date, appointment_time, status FROM unique_appointments WHERE client_id = ? AND status IN ('pending', 'confirmed') AND appointment_date >= CURDATE() ORDER BY appointment_date ASC, appointment_time ASC");
$stmt->execute([$client_id]);
$active_appointments_raw = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($active_appointments_raw as $appointment) {
    $active_appointments[] = [
        'id' => $appointment['id'],
        'date' => date("D, F d, Y", strtotime($appointment['appointment_date'])),
        'time' => date("g:i A", strtotime($appointment['appointment_time'])),
        'status' => ucfirst($appointment['status'])
    ];
}

// GENERAR HORARIOS DE SLOTS (Dropdown)
$available_time_slots = [];
if ($config) { // $config ya está definida y cargada de la Sección 2
    $start = strtotime(date('Y-m-d') . ' ' . $config['start_time']);
    $end = strtotime(date('Y-m-d') . ' ' . $config['end_time']);
    $duration = $config['slot_duration'] * 60;
    
    $current = $start;
    while ($current < $end) {
        $start_time_24 = date('H:i:s', $current);
        $start_time_12 = date('g:i A', $current);
        $end_slot = $current + $duration;
        $end_time_12 = date('g:i A', $end_slot);
        
        if ($end_slot <= $end) {
            $available_time_slots[] = ['value' => $start_time_24, 'label' => "{$start_time_12} - {$end_time_12}"];
        }
        $current = $end_slot;
    }
}

// ------------------------------------------------------------------------
// 5. VARIABLES DE DISPLAY Y LÓGICA DE TIEMPO (Final)
// ------------------------------------------------------------------------

$clientFullName = htmlspecialchars(($client_data['first_name'] ?? '') . ' ' . ($client_data['last_name'] ?? ''));
$clientFirstName = htmlspecialchars($client_data['first_name'] ?? 'Client');
$clientAccessCode = htmlspecialchars($client_data['access_code'] ?? '');
$nextServiceDateDisplay = $next_appointment['date'] ?? 'N/A';
$nextServiceTimeDisplay = $next_appointment['time_slot'] ?? 'No upcoming appointment scheduled';
$pendingInvoiceAmountDisplay = number_format($pending_invoice['amount'] ?? 0.00, 2);
$pendingInvoiceDueDate = $pending_invoice['due_date'] ?? 'N/A';
$lastComplaintStatus = $last_complaint['status'] ?? 'No Report';
$lastComplaintSubject = $last_complaint['subject'] ?? 'No recent reports.';
$lastComplaintReportedOn = $last_complaint['reported_on'] ?? 'N/A';
// Corregido: Obteniendo la profile_picture_url directamente de $client_data
$profile_pic_url = htmlspecialchars($client_data['profile_picture_url'] ?? 'img/default-avatar.png'); 

// 5.1 Lógica de Horario Semanal (Status)
$weekly_hours_raw = [];
$stmt_hours = $pdo->prepare("SELECT day, is_open, open_time, close_time FROM cms_weekly_hours ORDER BY FIELD(day, 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')");
$stmt_hours->execute();
$weekly_hours_raw = $stmt_hours->fetchAll(PDO::FETCH_ASSOC);

$isOpen = false;
$statusMessage = "We Are Currently Closed";
$statusColorClass = "bg-red-100 text-red-800";
$dotColorClass = "bg-red-500";
$todayHours = "Closed Today";

foreach ($weekly_hours_raw as $hours) {
    if ($hours['day'] === $currentDayName) {
        if ($hours['is_open']) {
            $openTime = new DateTime($hours['open_time']);
            $closeTime = new DateTime($hours['close_time']);
            $todayHours = $openTime->format('g:i A') . ' - ' . $closeTime->format('g:i A');

            if ($currentTime >= $openTime && $currentTime < $closeTime) {
                $isOpen = true;
                $statusMessage = "Yes, We're OPEN Right Now!";
                $statusColorClass = "bg-green-100 text-green-800";
                $dotColorClass = "bg-green-500";
            }
        }
        break; 
    }
}

// 5.2 Lógica del Contador Regresivo (Consolidado)
$nextAppointmentISO = '';
$isNextAppointmentConfirmed = false;

if (!empty($next_appointment['next_service_date']) && 
    $next_appointment['time_slot'] != 'No upcoming appointment scheduled' &&
    in_array($next_appointment['status'], ['pending', 'confirmed'])) {
    
    $datePart = $next_appointment['next_service_date']; 
    $timePart = date("H:i:s", strtotime($next_appointment['time_slot'])); 
    
    try {
        $dateTime = new DateTime($datePart . ' ' . $timePart);
        $nextAppointmentISO = $dateTime->format(DateTime::ATOM);
        
        // Solo mostramos el contador si la cita es en el futuro
        if ($dateTime > $currentTime) {
             $isNextAppointmentConfirmed = true;
        }
    } catch (Exception $e) {
        // Ignorar errores de fecha
    }
}

// Limpia el buffer de salida y lo envía.
if (ob_get_level() > 0) {
    ob_end_clean();
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Client Dashboard Of <?php echo htmlspecialchars($branding['business_name']); ?> <?php echo htmlspecialchars($branding['full_title']); ?></title>
        <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($branding['favicon']); ?>">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="<?php echo htmlspecialchars($google_font_url); ?>">

    <script src="https://unpkg.com/lucide@latest"></script>
    <link rel="stylesheet" href="../style.css">

</head>
<body class="font-barlow bg-[var(--color-light)]">

<?php
if (isset($_SESSION['feedback'])) {
    $feedback = $_SESSION['feedback'];
    // Cambiado de showNotification a showToast
    echo "<script>
            document.addEventListener('DOMContentLoaded', () => {
                showToast('" . addslashes($feedback['message']) . "', '" . addslashes($feedback['type']) . "');
            });
          </script>";
    unset($_SESSION['feedback']);
}
?>

<div id="overlay" class="fixed inset-0 bg-black/60 z-30 hidden"></div>

<header class="bg-white shadow-lg sticky top-0 z-20 border-b-4 border-[var(--color-highlight)]">
    <div class="max-w-7xl mx-auto px-4 py-4">
        <div class="flex items-center justify-between">
            
            <div class="flex items-center gap-4">
                <img src="<?php echo LOGO_FILENAME; ?>" alt="<?php echo BUSINESS_NAME; ?> Logo" class="h-12 w-auto object-contain">
                <div class="hidden md:block">
                    <h1 class="text-xl font-black text-[var(--color-primary)]"><?php echo BUSINESS_NAME; ?></h1>
                    <p class="text-sm font-bold text-gray-600">Welcome, <?php echo $clientFirstName; ?>!</p>
                </div>
            </div>
            
            <div class="flex items-center gap-3">
                <?php if (!empty($client_info['whatsapp_url'])): 
                    $prefilled_message = urlencode("Hello, I need assistance.");
                ?>
                    <a href="https://wa.me/<?php echo htmlspecialchars($client_info['whatsapp_url']); ?>?text=<?php echo htmlspecialchars($prefilled_message); ?>" 
                        target="_blank" 
                        class="hidden sm:flex items-center justify-center space-x-2 bg-green-500 hover:bg-green-600 text-white font-black px-4 py-2 rounded-lg transition-colors shadow-md text-sm">
                        <i data-lucide="message-circle" class="w-5 h-5"></i>
                        <span class="hidden md:inline">WHATSAPP</span>
                    </a>
                <?php endif; ?>
                
                <button id="profile-open-btn-top" class="flex items-center gap-2 bg-[var(--color-primary)] text-white font-bold px-4 py-2 rounded-lg hover:opacity-90 transition shadow-md text-sm">
                    <i data-lucide="user-circle-2" class="w-5 h-5"></i>
                    <span class="hidden md:inline">MY PROFILE</span>
                </button>
                
                <button id="menu-toggle-btn" class="lg:hidden p-2 rounded-md bg-gray-100 hover:bg-gray-200 transition-colors text-[var(--color-primary)]">
                    <i data-lucide="menu" class="w-6 h-6"></i>
                </button>
            </div>
        </div>
    </div>
    
    <div class="hidden lg:block bg-[var(--color-primary)] shadow-inner">
        <nav id="main-nav-desktop" class="max-w-7xl mx-auto px-4">
            <ul class="flex items-center justify-start gap-1">
                <li>
                    <a href="#dashboard" class="nav-link active flex items-center gap-2 px-6 py-3 border-t-4 border-t-white bg-white text-[var(--color-primary)] font-extrabold text-sm uppercase transition-all hover:bg-gray-100">
                        <i data-lucide="layout-dashboard" class="w-4 h-4"></i>
                        <span>Dashboard</span>
                    </a>
                </li>
                <li>
                    <a href="#schedule" class="nav-link flex items-center gap-2 px-6 py-3 text-white font-extrabold text-sm uppercase transition-all hover:bg-[var(--color-secondary)]">
                        <i data-lucide="calendar-plus" class="w-4 h-4"></i>
                        <span>Appointments</span>
                    </a>
                </li>
                <li>
                    <a href="#complaints" class="nav-link flex items-center gap-2 px-6 py-3 text-white font-extrabold text-sm uppercase transition-all hover:bg-[var(--color-secondary)]">
                        <i data-lucide="message-circle-x" class="w-4 h-4"></i>
                        <span>Report Issue</span>
                    </a>
                </li>
                <li>
                    <a href="#billing" class="nav-link flex items-center gap-2 px-6 py-3 text-white font-extrabold text-sm uppercase transition-all hover:bg-[var(--color-secondary)]">
                        <i data-lucide="receipt-text" class="w-4 h-4"></i>
                        <span>Billing History</span>
                    </a>
                </li>
                <li>
                    <a href="#review" class="nav-link flex items-center gap-2 px-6 py-3 text-white font-extrabold text-sm uppercase transition-all hover:bg-[var(--color-secondary)]">
                        <i data-lucide="trophy" class="w-4 h-4"></i>
                        <span>Leave Review</span>
                    </a>
                </li>
                <li>
                    <a href="#updates" class="nav-link flex items-center gap-2 px-6 py-3 text-white font-extrabold text-sm uppercase transition-all hover:bg-[var(--color-secondary)]">
                        <i data-lucide="clock" class="w-4 h-4"></i>
                        <span>Business Hours</span>
                    </a>
                </li>
                <li class="ml-auto">
                    <a href="logout.php" class="nav-link flex items-center gap-2 px-6 py-3 bg-red-600 text-white font-extrabold text-sm uppercase shadow-md transition-all hover:bg-red-700">
                        <i data-lucide="log-out" class="w-4 h-4"></i>
                        <span>Logout</span>
                    </a>
                </li>
            </ul>
        </nav>
    </div>
</header>

<div id="mobile-nav-panel" class="fixed top-0 left-0 h-full w-full max-w-sm bg-[var(--color-primary)] z-40 shadow-2xl transform -translate-x-full transition-transform duration-300 ease-in-out flex flex-col lg:hidden">
    
    <div class="p-8 pb-10 flex flex-col items-center justify-center border-b border-white/10 relative">
         <button id="menu-close-btn" class="absolute top-4 right-4 text-white/70 hover:text-white rounded-full hover:bg-white/10 p-1 transition-colors">
            <i data-lucide="x" class="w-7 h-7"></i>
        </button>
        
        <div class="relative w-28 h-28 rounded-full border-4 border-white/50 shadow-lg ring-2 ring-[var(--color-highlight)] overflow-hidden mb-4
            <?php if ($profile_pic_url === 'img/default-avatar.png'): ?>
                bg-gray-100 text-[var(--color-primary)] flex items-center justify-center
            <?php endif; ?>">
            
            <?php if ($profile_pic_url === 'img/default-avatar.png'): ?>
                <i data-lucide="user-circle" class="w-20 h-20 opacity-60"></i>
            <?php else: ?>
                <img src="<?php echo $profile_pic_url; ?>" alt="Profile Picture" class="w-full h-full object-cover rounded-full">
            <?php endif; ?>
        </div>

        <h4 class="text-xl font-medium text-white/80">Welcome,</h4>
        <h3 class="text-3xl font-black text-white"><?php echo $clientFirstName; ?>!</h3>
    </div>
    
    <nav class="p-4 flex-1 overflow-y-auto">
        <ul class="flex flex-col gap-1">
            <li><a href="#dashboard" class="mobile-nav-link flex items-center gap-4 px-4 py-3 rounded-lg text-white font-extrabold text-lg uppercase transition-colors active:bg-white/10">
                <i data-lucide="layout-dashboard" class="w-6 h-6 text-[var(--color-highlight)]"></i><span>Dashboard</span>
            </a></li>
            <li><a href="#schedule" class="mobile-nav-link flex items-center gap-4 px-4 py-3 rounded-lg text-white hover:bg-white/5 font-extrabold text-lg uppercase transition-colors">
                <i data-lucide="calendar-plus" class="w-6 h-6 text-white/70"></i><span>Appointments</span>
            </a></li>
            <li><a href="#complaints" class="mobile-nav-link flex items-center gap-4 px-4 py-3 rounded-lg text-white hover:bg-white/5 font-extrabold text-lg uppercase transition-colors">
                <i data-lucide="message-circle-x" class="w-6 h-6 text-white/70"></i><span>Report an Issue</span>
            </a></li>
            <li><a href="#billing" class="mobile-nav-link flex items-center gap-4 px-4 py-3 rounded-lg text-white hover:bg-white/5 font-extrabold text-lg uppercase transition-colors">
                <i data-lucide="receipt-text" class="w-6 h-6 text-white/70"></i><span>Billing History</span>
            </a></li>
            <li><a href="#review" class="mobile-nav-link flex items-center gap-4 px-4 py-3 rounded-lg text-white hover:bg-white/5 font-extrabold text-lg uppercase transition-colors">
                <i data-lucide="trophy" class="w-6 h-6 text-white/70"></i><span>Leave a Review</span>
            </a></li>
            <li><a href="#updates" class="mobile-nav-link flex items-center gap-4 px-4 py-3 rounded-lg text-white hover:bg-white/5 font-extrabold text-lg uppercase transition-colors">
                <i data-lucide="clock" class="w-6 h-6 text-white/70"></i><span>Business Hours</span>
            </a></li>
        </ul>
    </nav>
    
    <div class="p-4 border-t border-white/10 flex flex-col gap-2 flex-shrink-0">
         <button id="profile-open-btn-mobile" class="flex items-center gap-4 bg-[var(--color-secondary)] text-white font-extrabold px-4 py-3 rounded-lg hover:brightness-110 transition uppercase">
            <i data-lucide="user-circle-2" class="w-6 h-6"></i>
            <span>My Profile</span>
        </button>
        <a href="logout.php" class="flex items-center gap-4 px-4 py-3 rounded-lg text-red-400 hover:text-red-50 font-extrabold text-lg uppercase transition-colors">
            <i data-lucide="log-out" class="w-6 h-6"></i>
            <span>Log Out</span>
        </a>
    </div>
</div>

<aside id="profile-panel" class="fixed top-0 right-0 h-full w-full max-w-lg bg-[var(--color-light)] z-50 shadow-2xl transform translate-x-full transition-transform duration-300 ease-in-out flex flex-col">
    
    <div class="flex items-start justify-between p-6 bg-[var(--color-primary)] text-white flex-shrink-0 border-b-4 border-[var(--color-secondary)]">
        <div>
            <h2 class="text-2xl font-extrabold flex items-center gap-3 uppercase tracking-wider">
                <i data-lucide="user-pen" class="text-[var(--color-secondary)]"></i>
                <span>Your Profile Information</span>
            </h2>
            <p class="text-white/80 mt-1">Keep your details up to date.</p>
        </div>
        <button id="profile-close-btn" class="text-white/70 hover:text-white rounded-full hover:bg-white/10 p-1 transition-colors">
            <i data-lucide="x" class="w-7 h-7"></i>
        </button>
    </div>
    <div class="p-6 overflow-y-auto flex-1">
        <form action=".db/client_profile_update.php" method="POST">
            <input type="hidden" name="client_id" value="<?php echo htmlspecialchars($client_id); ?>">
            
            <div class="space-y-5">
                
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-5">
                    <div>
                        <label for="first_name" class="block text-sm font-bold uppercase text-[var(--color-primary)]/70 mb-2">First Name</label>
                        <div class="relative">
                            <i data-lucide="user" class="w-5 h-5 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2"></i>
                            <input type="text" id="first_name" name="first_name" value="<?php echo htmlspecialchars($client_data['first_name'] ?? ''); ?>" class="w-full pl-11 pr-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-[var(--color-highlight)] transition text-base shadow-sm">
                        </div>
                    </div>
                    <div>
                        <label for="last_name" class="block text-sm font-bold uppercase text-[var(--color-primary)]/70 mb-2">Last Name</label>
                        <div class="relative">
                             <i data-lucide="user" class="w-5 h-5 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2"></i>
                            <input type="text" id="last_name" name="last_name" value="<?php echo htmlspecialchars($client_data['last_name'] ?? ''); ?>" class="w-full pl-11 pr-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-[var(--color-highlight)] transition text-base shadow-sm">
                        </div>
                    </div>
                </div>
                <div>
                    <label for="email" class="block text-sm font-bold uppercase text-[var(--color-primary)]/70 mb-2">Email</label>
                    <div class="relative">
                        <i data-lucide="mail" class="w-5 h-5 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2"></i>
                        <input type="email" id="email" name="email" value="<?php echo htmlspecialchars($client_data['email'] ?? ''); ?>" class="w-full pl-11 pr-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-[var(--color-highlight)] transition text-base shadow-sm" placeholder="Enter your email">
                    </div>
                </div>
                
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-5">
                    <div>
                        <label for="phone" class="block text-sm font-bold uppercase text-[var(--color-primary)]/70 mb-2">Phone</label>
                        <div class="relative">
                            <i data-lucide="phone" class="w-5 h-5 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2"></i>
                            <input type="tel" id="phone" name="phone" value="<?php echo htmlspecialchars($client_data['phone'] ?? ''); ?>" class="w-full pl-11 pr-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-[var(--color-highlight)] transition text-base shadow-sm">
                        </div>
                    </div>
                    <div>
                        <label for="mobile" class="block text-sm font-bold uppercase text-[var(--color-primary)]/70 mb-2">Mobile</label>
                         <div class="relative">
                            <i data-lucide="smartphone" class="w-5 h-5 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2"></i>
                            <input type="tel" id="mobile" name="mobile" value="<?php echo htmlspecialchars($client_data['mobile'] ?? ''); ?>" class="w-full pl-11 pr-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-[var(--color-highlight)] transition text-base shadow-sm">
                        </div>
                    </div>
                </div>
                <div>
                    <label for="street_address" class="block text-sm font-bold uppercase text-[var(--color-primary)]/70 mb-2">Address</label>
                    <div class="relative">
                        <i data-lucide="map-pin" class="w-5 h-5 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2"></i>
                        <input type="text" id="street_address" name="street_address" value="<?php echo htmlspecialchars($client_data['street_address'] ?? ''); ?>" placeholder="Street Address" class="w-full pl-11 pr-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-[var(--color-highlight)] transition text-base shadow-sm">
                    </div>
                </div>
                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
                    <div>
                        <label for="city" class="block text-sm font-bold uppercase text-[var(--color-primary)]/70 mb-2">City</label>
                        <input type="text" id="city" name="city" value="<?php echo htmlspecialchars($client_data['city'] ?? ''); ?>" class="w-full px-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-[var(--color-highlight)] transition text-base shadow-sm">
                    </div>
                    <div>
                        <label for="state_province" class="block text-sm font-bold uppercase text-[var(--color-primary)]/70 mb-2">State</label>
                        <input type="text" id="state_province" name="state_province" value="<?php echo htmlspecialchars($client_data['state_province'] ?? ''); ?>" class="w-full px-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-[var(--color-highlight)] transition text-base shadow-sm">
                    </div>
                    <div>
                        <label for="zip_code" class="block text-sm font-bold uppercase text-[var(--color-primary)]/70 mb-2">Zip Code</label>
                        <input type="text" id="zip_code" name="zip_code" value="<?php echo htmlspecialchars($client_data['zip_code'] ?? ''); ?>" class="w-full px-4 py-3 border border-gray-200 rounded-lg focus:ring-2 focus:ring-[var(--color-highlight)] transition text-base shadow-sm">
                    </div>
                </div>
            </div>
            
            <div class="mt-8 border-t pt-6 text-right">
                <button type="submit" class="bg-[var(--color-primary)] text-white font-extrabold py-3 px-8 rounded-lg shadow-lg hover:brightness-115 transition transform hover:-translate-y-0.5 flex items-center gap-2 text-base ml-auto uppercase tracking-wide">
                    <i data-lucide="save" class="w-5 h-5"></i>
                    <span>Save Changes</span>
                </button>
            </div>
        </form>
    </div>
</aside>

<main class="flex-1 min-w-0">
    <div id="dashboard" class="bg-[var(--color-light)] section-container px-6 lg:px-10 pt-12">
        <header class="mb-12 max-w-7xl mx-auto">
    
    <div class="flex flex-col lg:flex-row lg:items-center justify-between gap-6">
        
        <div class="flex items-center gap-6 sm:gap-8 flex-shrink-0">
            
            <div class="flex-shrink-0 relative group">
                <div class="relative w-24 h-24 sm:w-32 sm:h-32 rounded-full border-4 border-gray-200 shadow-xl ring-2 ring-[var(--color-highlight)] 
                    <?php if ($profile_pic_url === 'img/default-avatar.png'): ?>
                        bg-gray-100 text-[var(--color-primary)] flex items-center justify-center
                    <?php endif; ?>">
                    
                    <?php if ($profile_pic_url === 'img/default-avatar.png'): ?>
                        <i data-lucide="user-circle" class="w-20 h-20 sm:w-24 sm:h-24 opacity-60"></i>
                    <?php else: ?>
                        <img src="<?php echo $profile_pic_url; ?>" alt="Profile Picture" class="w-full h-full object-cover rounded-full">
                    <?php endif; ?>
                    
                    <button id="profile-open-btn-avatar" title="Change Profile Picture" class="absolute inset-0 flex items-center justify-center bg-[var(--color-primary)]/40 text-white opacity-0 group-hover:opacity-100 transition-opacity rounded-full">
                        <i data-lucide="camera" class="w-8 h-8 text-white"></i>
                    </button>
                </div>
            </div>

            <div class="flex-grow min-w-0">
                <h1 class="font-black text-4xl sm:text-5xl md:text-5xl text-[var(--color-primary)] break-words">
                    Welcome Back, <span class="text-[var(--color-secondary)]"> <?php echo $clientFirstName; ?>!</span>
                </h1>
                <div class="mt-1">
                    <span id="greeting-display">
                        </span>
                </div>
            </div>
        </div>
        
        <?php if ($isNextAppointmentConfirmed): ?>
        <div id="dashboard-countdown" class="flex-shrink-0 w-full lg:w-auto mt-6 lg:mt-0 p-4 rounded-xl shadow-lg border-2 border-[var(--color-highlight)]/50 bg-white">
            <h4 class="text-xs font-black text-[var(--color-primary)] uppercase mb-2 flex items-center justify-center gap-2">
                <i data-lucide="calendar-check" class="w-4 h-4 text-[var(--color-secondary)]"></i>
                Next Service Scheduled for:
            </h4>
            <div class="flex justify-center items-center space-x-2 font-black text-[var(--color-primary)]">
                <div class="text-center">
                    <span id="dash-days" class="text-xl md:text-2xl">00</span>
                    <p class="text-xs uppercase font-bold text-gray-500">Days</p>
                </div>
                <span class="text-xl md:text-2xl">:</span>
                <div class="text-center">
                    <span id="dash-hours" class="text-xl md:text-2xl">00</span>
                    <p class="text-xs uppercase font-bold text-gray-500">Hrs</p>
                </div>
                <span class="text-xl md:text-2xl">:</span>
                <div class="text-center">
                    <span id="dash-minutes" class="text-xl md:text-2xl">00</span>
                    <p class="text-xs uppercase font-bold text-gray-500">Mins</p>
                </div>
                <span class="text-xl md:text-2xl">:</span>
                <div class="text-center">
                    <span id="dash-seconds" class="text-xl md:text-2xl">00</span>
                    <p class="text-xs uppercase font-bold text-gray-500">Sec</p>
                </div>
            </div>
            <p id="dash-appointment-time" class="text-sm font-bold text-center mt-2 text-[var(--color-secondary)] uppercase">
                @ <?php echo $next_appointment['time_slot']; ?>
            </p>
        </div>
        <?php endif; ?>
        
    </div>
    
</header>

        <div class="max-w-7xl mx-auto">
            <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-8">
                
                <div class="bg-white p-6 rounded-2xl shadow-xl ring-1 ring-black/5 transition-all hover:shadow-2xl hover:-translate-y-1 xl:col-span-2">
                    <div class="flex justify-between items-start">
                        <h3 class="text-sm font-black uppercase text-[var(--color-primary)]/60 tracking-wider">Next Scheduled Service</h3>
                        <i data-lucide="calendar-check" class="w-6 h-6 text-[var(--color-secondary)]/30"></i>
                    </div>
                    <div class="mt-4 flex flex-col sm:flex-row justify-between items-end gap-4">
                        <div>
                            <p class="text-3xl font-black text-[var(--color-primary)] leading-none"><?php echo $nextServiceDateDisplay; ?></p>
                            <p class="text-lg text-gray-700 font-bold mt-1">Time: <?php echo $nextServiceTimeDisplay; ?></p>
                        </div>
                        <?php if (isset($next_appointment['date']) && $next_appointment['date'] != 'N/A'): ?>
                            <a href="#schedule" class="bg-[var(--color-primary)] text-white font-extrabold py-3 px-5 rounded-lg hover:opacity-90 transition shadow-md flex items-center gap-2 text-sm uppercase">Modify <i data-lucide="edit" class="w-4 h-4"></i></a>
                        <?php else: ?>
                            <a href="#schedule" class="bg-[var(--color-secondary)] text-white font-extrabold py-3 px-5 rounded-lg hover:brightness-110 transition shadow-md flex items-center gap-2 text-sm uppercase">Book Now <i data-lucide="plus" class="w-4 h-4"></i></a>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="bg-white p-6 rounded-2xl shadow-xl ring-1 ring-black/5 transition-all hover:shadow-2xl hover:-translate-y-1">
                    <div class="flex justify-between items-start">
                        <h3 class="text-sm font-black uppercase text-[var(--color-primary)]/60 tracking-wider">Pending Invoice</h3>
                        <i data-lucide="credit-card" class="w-6 h-6 text-[var(--color-secondary)]/30"></i>
                    </div>
                    <div class="mt-4">
                        <p class="text-4xl font-black text-[var(--color-highlight)] leading-none">$<?php echo $pendingInvoiceAmountDisplay; ?></p>
                        <p class="text-sm text-gray-700 mt-1 font-bold flex items-center gap-1.5"><i data-lucide="calendar-x-2" class="w-4 h-4 text-red-500"></i> Due: <?php echo $pendingInvoiceDueDate; ?></p>
                    </div>
                      <?php if (isset($pending_invoice['amount']) && $pending_invoice['amount'] > 0): ?>
                        <a href="#billing" class="mt-4 inline-block w-full bg-[var(--color-highlight)] text-white font-extrabold py-3 px-4 rounded-lg hover:brightness-110 transition text-center shadow-md uppercase text-sm">View Balance</a>
                    <?php else: ?>
                        <div class="mt-4 w-full text-center text-sm font-bold uppercase text-green-800 bg-green-100 py-3 px-4 rounded-lg flex items-center justify-center gap-2">
                            <i data-lucide="check-circle" class="w-5 h-5"></i> All Paid Up!
                        </div>
                    <?php endif; ?>
                </div>
                
                <div class="bg-white p-6 rounded-2xl shadow-xl ring-1 ring-black/5 transition-all hover:shadow-2xl hover:-translate-y-1">
                    <div class="flex justify-between items-start">
                        <h3 class="text-sm font-black uppercase text-[var(--color-primary)]/60 tracking-wider">Recent Report</h3>
                        <i data-lucide="message-square-warning" class="w-6 h-6 text-[var(--color-secondary)]/30"></i>
                    </div>
                    <div class="mt-4">
                        <?php 
                        $complaint_status_map = [
                            'Recibido'        => 'Received',
                            'Resolviendo'     => 'In Progress',
                            'Acción Requerida'=> 'Action Required',
                            'Resuelto'        => 'Resolved',
                            'Archivado'       => 'Archived'
                        ];
                        $db_status_complaint = strtolower($last_complaint['status']);
                        $translated_status = $complaint_status_map[ucfirst($last_complaint['status'])] ?? ucfirst($last_complaint['status']);
                        ?>
                        <?php if (isset($last_complaint['status']) && $last_complaint['status'] != 'No Report'): ?>
                            <span class="px-3 py-1 text-xs font-black rounded-full bg-[var(--color-secondary)] text-white uppercase">
                                <?php echo htmlspecialchars($translated_status); ?>
                            </span>
                            <p class="text-base text-gray-700 mt-2 font-bold truncate" title="<?php echo htmlspecialchars($lastComplaintSubject); ?>">
                                Subject: <?php echo htmlspecialchars($lastComplaintSubject); ?>
                            </p>
                        <?php else: ?>
                            <span class="px-3 py-1 text-xs font-black rounded-full bg-gray-200 text-gray-700 uppercase">None</span>
                            <p class="text-base text-gray-700 mt-2 font-bold">You have no active reports.</p>
                        <?php endif; ?>
                    </div>
    <a href="#complaints" class="mt-4 w-full flex items-center justify-center gap-2 bg-[var(--color-secondary)] text-white font-extrabold py-3 px-4 rounded-lg hover:brightness-110 transition shadow-md uppercase text-sm">
        <?php echo (isset($last_complaint['status']) && $last_complaint['status'] != 'No Report') ? 'View Resolution' : 'New Report'; ?> 
        <i data-lucide="plus" class="w-4 h-4"></i> 
    </a>
                </div>
            </div>
            <div class="mt-12 p-8 bg-[var(--color-primary)] rounded-2xl shadow-2xl ring-1 ring-white/10 relative overflow-hidden">
                <div aria-hidden="true" class="absolute inset-0 z-0 opacity-10"><div class="absolute top-0 right-0 translate-x-1/4 -translate-y-1/4 w-[42rem] h-[42rem] rounded-md blur-3xl" style="background: radial-gradient(closest-side, var(--color-secondary), transparent 70%);"></div></div>
                <div class="relative z-10 md:flex md:items-center md:justify-between md:gap-8">
                    <div class="flex items-center gap-5">
                        <i data-lucide="handshake" class="w-12 h-12 text-white flex-shrink-0"></i>
                        <div>
                            <h3 class="font-extrabold text-2xl sm:text-3xl text-[var(--color-highlight)]">Need to Talk To The Manager Directly?</h3>
                            <p class="text-white/90 mt-1">For urgent matters or high-value feedback, chat with a manager now.</p>
                        </div>
                    </div>
                    <?php $whatsapp_text = urlencode("Hello, I am a client and I need to speak directly with a Manager about an urgent matter. My Client ID is {$clientAccessCode}."); ?>
                    <a href="https://wa.me/<?php echo WHATSAPP_NUMBER_CLICK; ?>?text=<?php echo $whatsapp_text; ?>" target="_blank" class="mt-6 md:mt-0 flex-shrink-0 inline-flex items-center justify-center gap-2 px-6 py-3 rounded-lg font-black uppercase text-white bg-[var(--color-secondary)] shadow-lg hover:brightness-110 transition transform hover:-translate-y-0.5">
                        <i data-lucide="message-circle" class="w-5 h-5"></i>
                        <span>Chat with Manager</span>
                    </a>
                </div>
            </div>
        </div>
    </div>
    
<div id="schedule" class="bg-white section-container px-6 lg:px-10 ">
        <div class="max-w-5xl mx-auto space-y-12">
            
            <div class="bg-white p-6 rounded-2xl shadow-2xl text-white">

 <div class="mb-8 text-center"> 
    <h3 class="text-3xl md:text-4xl font-black text-[var(--color-primary)] mb-2 flex items-center justify-center gap-2"> 
        <i data-lucide="calendar-days" class="w-8 h-8 md:w-10 md:h-10 text-[var(--color-secondary)]"></i>
        BOOK YOUR APPOINTMENT
    </h3>
    <p class="text-gray-600 text-lg uppercase font-medium">SELECT AN AVAILABLE DATE AND TIME SLOT BELOW</p>
</div>

                <div class="bg-white p-6 rounded-xl shadow-md border border-gray-200 mb-8">
                    <div class="flex justify-between items-center mb-6">
                        <button id="prev-btn-public" class="p-2 rounded-md hover:bg-gray-200 transition-colors text-[var(--color-primary)]">
                            <i data-lucide="chevron-left" class="w-6 h-6"></i>
                        </button>
                        <h4 id="week-title" class="text-lg md:text-xl font-black text-[var(--color-primary)] uppercase px-4 py-2 text-center"></h4>
                        <button id="next-btn-public" class="p-2 rounded-md hover:bg-gray-200 transition-colors text-[var(--color-primary)]">
                            <i data-lucide="chevron-right" class="w-6 h-6"></i>
                        </button>
                    </div>

                    <div class="grid grid-cols-7 text-center font-bold text-sm text-white bg-[var(--color-primary)] p-2 rounded-t-lg">
                        <div>SUN</div> 
                        <div>MON</div>
                        <div>TUE</div>
                        <div>WED</div>
                        <div>THU</div>
                        <div>FRI</div>
                        <div>SAT</div> 
                    </div>

                    <div id="calendar-grid-public" class="grid grid-cols-7 border-x border-b border-gray-200 rounded-b-lg overflow-hidden min-h-[100px]"></div>

                </div>
                <div id="slots-container" class="bg-white p-6 rounded-xl shadow-md border border-gray-200 hidden mb-8">
                    <div class="text-center"> 
                        <h3 id="slots-header" class="text-3xl font-black mb-1 text-[var(--color-primary)] flex items-center justify-center gap-2">
                            <i data-lucide="clock" class="w-7 h-7 text-[var(--color-secondary)]"></i>
                            AVAILABLE TIME SLOTS
                        </h3>
                        <p id="slots-subheader" class="text-gray-600 text-lg uppercase font-medium mb-4">Select the time that works best for you</p>
                    </div>
                    <div id="slot-buttons" class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3"></div>
                </div>
                <div id="booking-confirmation-container" class="bg-white p-6 md:p-8 rounded-2xl shadow-2xl border-l-4 border-[var(--color-highlight)] hidden">
                    <div class="text-center mb-6"> 
                        <h3 class="text-2xl md:text-3xl font-black mb-1 text-[var(--color-primary)] flex items-center justify-center gap-2">
                            <i data-lucide="user-check" class="w-8 h-8 text-[var(--color-secondary)]"></i>
                            CONFIRM YOUR RESERVATION
                        </h3>
                        <p class="text-gray-600 text-lg uppercase font-medium">Please confirm your details and service selection.</p>
                    </div>
                    
                    <div class="bg-[var(--color-highlight)] bg-opacity-10 p-4 rounded-lg mb-6 border border-[var(--color-highlight)] text-center">
                        <p class="text-lg font-bold uppercase text-[var(--color-primary)]">Selected Appointment:</p>
                        <p id="selected-slot-display" class="text-2xl font-black text-[var(--color-primary)] mt-2"></p>
                    </div>
                    
                    <div class="bg-gray-50 p-5 rounded-lg border border-gray-200 space-y-3 mb-6">
                        <h4 class="text-lg font-black text-[var(--color-primary)] border-b pb-2 flex items-center gap-2">
                            <i data-lucide="user-circle" class="w-5 h-5 text-[var(--color-secondary)]"></i>
                            Your Appointment Details
                        </h4>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-2 text-sm">
                            <p class="text-lg text-[var(--color-primary)]"><span class="font-black">Name:</span> <?php echo $clientFullName; ?></p>
                            <p class="text-lg text-[var(--color-primary)]"><span class="font-black">Phone:</span> <?php echo htmlspecialchars($client_data['phone'] ?? 'N/A'); ?></p>
                            <p class="text-lg text-[var(--color-primary)]"><span class="font-black">Email:</span> <?php echo htmlspecialchars($client_data['email'] ?? 'N/A'); ?></p>
                            <p class="text-lg text-[var(--color-primary)]"><span class="font-black">Address:</span> <?php echo htmlspecialchars($client_data['street_address'] ?? 'N/A'); ?>, <?php echo htmlspecialchars($client_data['city'] ?? ''); ?></p>
                        </div>
                    </div>
                    
                    <form id="client-booking-form" class="space-y-6">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                        <input type="hidden" name="appointment_date" id="form-date">
                        <input type="hidden" name="appointment_time" id="form-time">
                        <input type="hidden" name="type" value="unica">
                        
                        <input type="hidden" name="first_name" value="<?php echo htmlspecialchars($client_data['first_name'] ?? ''); ?>">
                        <input type="hidden" name="last_name" value="<?php echo htmlspecialchars($client_data['last_name'] ?? ''); ?>">
                        <input type="hidden" name="email" value="<?php echo htmlspecialchars($client_data['email'] ?? ''); ?>">
                        <input type="hidden" name="phone" value="<?php echo htmlspecialchars($client_data['phone'] ?? ''); ?>">
                        <input type="hidden" name="address_line" value="<?php echo htmlspecialchars($client_data['street_address'] ?? ''); ?>">
                        <input type="hidden" name="city" value="<?php echo htmlspecialchars($client_data['city'] ?? ''); ?>">
                        <input type="hidden" name="state" value="<?php echo htmlspecialchars($client_data['state_province'] ?? ''); ?>">
                        <input type="hidden" name="zip_code" value="<?php echo htmlspecialchars($client_data['zip_code'] ?? ''); ?>">


                        <div>
                            <label for="service_id" class="block text-lg font-black text-[var(--color-primary)] mb-2 uppercase flex items-center gap-2">
                                <i data-lucide="sparkles" class="w-5 h-5 text-[var(--color-highlight)]"></i>
                                Select Your Service Type 
                            </label>
                            <select id="service_id" name="service_id" class="w-full p-3 border-2 text-[var(--color-primary)] border-gray-300 rounded-lg focus:ring-2 focus:ring-[var(--color-highlight)] transition text-base font-semibold shadow-sm" required>
                                <option value="" disabled selected>Choose a cleaning package or service...</option>
                                <?php foreach ($available_services as $service): ?>
                                    <option value="<?php echo $service['id']; ?>"><?php echo $service['name']; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <button type="submit" class="w-full bg-[var(--color-secondary)] hover:brightness-110 text-white p-4 font-black rounded-lg transition uppercase shadow-lg flex items-center justify-center gap-2 text-lg">
                            <i data-lucide="calendar-plus" class="w-6 h-6"></i> 
                            CONFIRM AND BOOK APPOINTMENT
                        </button>
                    </form>
                </div>
                </div>
            
            <div class="bg-white p-6 sm:p-8 rounded-2xl shadow-xl border border-gray-100">
                <div class="mb-8 text-center"> 
    <h3 class="text-3xl md:text-4xl font-black text-[var(--color-primary)] mb-2 flex items-center uppercase justify-center gap-2"> 
        <i data-lucide="calendar-clock" class="w-8 h-8 md:w-10 md:h-10 text-[var(--color-secondary)]"></i>
        Your Upcoming Services 
    </h3>
    <p class="text-gray-600 text-lg uppercase font-medium">SELECT AN AVAILABLE DATE AND TIME SLOT BELOW</p>
</div>
                <div class="space-y-4">
                    <?php if (empty($active_appointments)): ?>
                        <div class="p-6 text-center text-gray-700 font-semibold bg-gray-50 rounded-xl border-dashed border-2 border-gray-300">
                            <i data-lucide="calendar-x" class="w-10 h-10 mx-auto mb-3 text-[var(--color-highlight)]"></i>
                            <p class="font-black text-lg">You have no active appointments!</p>
                            <p class="text-sm">Use the form above to request your next service.</p>
                        </div>
                    <?php else: ?>
                        <?php foreach ($active_appointments as $appointment): ?>
                            <?php 
                            $cita_type = 'unica';
                            $is_pending = strtolower($appointment['status']) === 'pending';
                            $status_class = $is_pending ? 'bg-yellow-100 text-yellow-800 border-yellow-500' : 'bg-green-100 text-green-800 border-green-500';
                            $icon = $is_pending ? 'loader-2 animate-spin' : 'check-circle';
                            $full_id = 'cita-' . $cita_type . '-' . $appointment['id']; 
                            ?>
                            <div class="p-4 rounded-xl shadow-md flex justify-between items-center border-l-4 <?php echo $status_class; ?>">
                                <div>
                                    <p class="text-lg font-black text-gray-800"><?php echo $appointment['date']; ?></p>
                                    <p class="text-sm font-semibold text-gray-600">Time: <?php echo $appointment['time']; ?></p>
                                </div>
                                <div class="flex items-center gap-2">
                                    <span class="px-3 py-1 text-xs font-black rounded-full flex items-center gap-1.5 <?php echo $status_class; ?>">
                                        <i data-lucide="<?php echo $icon; ?>" class="w-4 h-4"></i> <?php echo $appointment['status']; ?>
                                    </span>
                                    <button type="button" class="action-cancel-btn p-2 rounded-full text-red-600 hover:bg-red-100 transition" title="Cancel Appointment" data-cita-id="<?php echo $full_id; ?>" data-cita-type="<?php echo $cita_type; ?>">
                                        <i data-lucide="x-circle" class="w-5 h-5"></i>
                                    </button>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <div id="billing" class="bg-[var(--color-light)] section-container px-6 lg:px-10">
    
    <div class="mb-12 text-center max-w-4xl mx-auto">
        <h3 class="text-3xl md:text-4xl font-black text-[var(--color-primary)] mb-2 flex items-center justify-center gap-2">
            <i data-lucide="badge-dollar-sign" class="w-8 h-8 md:w-10 md:h-10 text-[var(--color-secondary)]"></i>
            BILLING & PAYMENT HISTORY
        </h3>
        <p class="text-gray-600 text-lg uppercase font-medium">SIMPLE & TRANSPARENT ACCOUNT STATEMENT</p>
    </div>
    
    <div class="max-w-7xl mx-auto">
        
        <?php if (isset($pending_invoice['amount']) && $pending_invoice['amount'] > 0): ?>
            <div class="bg-[var(--color-highlight)] text-white p-6 rounded-2xl shadow-xl mb-8 flex flex-col sm:flex-row items-center justify-between gap-4">
                <div class="flex items-center gap-4">
                    <i data-lucide="alert-triangle" class="w-10 h-10 text-white flex-shrink-0"></i>
                    <div>
                        <h2 class="text-xl font-extrabold">You Have an Invoice Requiring Attention!</h2>
                        <p class="text-white/90 mt-1 font-semibold">
                            A balance of <span class="font-bold">$<?php echo $pendingInvoiceAmountDisplay; ?></span> is due on <span class="font-bold"><?php echo $pendingInvoiceDueDate; ?></span>.
                        </p>
                    </div>
                </div>
                <a href="#invoice-history-table" class="bg-white text-[var(--color-highlight)] font-extrabold py-2 px-5 rounded-lg hover:bg-gray-200 transition shadow-md flex-shrink-0">
                    View Invoice
                </a>
            </div>
        <?php endif; ?>
            
        <div id="invoice-history-table" class="bg-white p-6 sm:p-8 rounded-2xl shadow-xl max-w-4xl mx-auto px-4 py-8">
            <h2 class="text-2xl font-black text-[var(--color-primary)] flex items-center gap-3 mb-4">
                <i data-lucide="history" class="w-7 h-7 text-[var(--color-highlight)]"></i>
                <span>Invoice History</span>
            </h2>
            <div class="overflow-x-auto">
                <table class="w-full text-left responsive-invoices-table">
                    <thead>
                        <tr class="border-b border-black/10">
                            <th class="py-3 px-4 text-xs font-black uppercase text-[var(--color-primary)]/60">Invoice ID</th>
                            <th class="py-3 px-4 text-xs font-black uppercase text-[var(--color-primary)]/60">Date</th>
                            <th class="py-3 px-4 text-xs font-black uppercase text-[var(--color-primary)]/60">Amount</th>
                            <th class="py-3 px-4 text-xs font-black uppercase text-[var(--color-primary)]/60 text-center">Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $status_map = [
                            'pagada'    => 'Paid',
                            'pendiente' => 'Pending',
                            'vencida'   => 'Overdue',
                            'enviada'   => 'Sent',
                        ];
                        $stmt_invoices = $pdo->prepare("SELECT external_id, invoice_date, total_amount, status FROM invoices WHERE client_id = ? ORDER BY invoice_date DESC");
                        $stmt_invoices->execute([$client_id]);
                        $invoices_data = $stmt_invoices->fetchAll(PDO::FETCH_ASSOC);
                        if (!empty($invoices_data)) {
                            foreach($invoices_data as $invoice):
                                $status_from_db = strtolower($invoice['status']);
                                $status_text = $status_map[$status_from_db] ?? ucfirst($status_from_db);
                                $status_class = '';
                                $status_icon = 'help-circle';
                                switch ($status_from_db) {
                                    case 'pagada':
                                        $status_class = 'bg-green-100 text-green-800';
                                        $status_icon = 'check-circle';
                                        break;
                                    case 'pendiente':
                                    case 'enviada':
                                        $status_class = 'bg-yellow-100 text-yellow-800';
                                        $status_icon = 'loader-circle';
                                        break;
                                    case 'vencida':
                                        $status_class = 'bg-red-100 text-red-800';
                                        $status_icon = 'alert-circle';
                                        break;
                                    default:
                                        $status_class = 'bg-gray-100 text-gray-800';
                                }
                        ?>
                                <tr>
                                    <td data-label="Invoice ID" class="py-4 px-4 font-bold text-[var(--color-primary)]">#<?php echo htmlspecialchars($invoice['external_id']); ?></td>
                                    <td data-label="Date" class="py-4 px-4 font-semibold text-gray-700"><?php echo date("M d, Y", strtotime($invoice['invoice_date'])); ?></td>
                                    <td data-label="Amount" class="py-4 px-4 font-bold text-lg text-[var(--color-primary)]">$<?php echo number_format($invoice['total_amount'], 2); ?></td>
                                    <td data-label="Status" class="py-4 px-4 text-center">
                                        <span class="inline-flex items-center gap-1.5 px-3 py-1 text-xs font-bold <?php echo $status_class; ?> rounded-full">
                                            <i data-lucide="<?php echo $status_icon; ?>" class="w-4 h-4"></i>
                                            <span><?php echo htmlspecialchars($status_text); ?></span>
                                        </span>
                                    </td>
                                </tr>
                        <?php 
                            endforeach;
                        } else {
                            echo '<tr><td colspan="4" class="p-8 text-center text-gray-500">No invoices found for this client.</td></tr>';
                        }
                        ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
              
    <div id="complaints" class="bg-white section-container px-6 lg:px-10">
    
    <div class="mb-12 text-center max-w-4xl mx-auto">
        <h3 class="text-3xl md:text-4xl font-black text-[var(--color-primary)] mb-2 flex items-center justify-center gap-2">
            <i data-lucide="message-circle-x" class="w-8 h-8 md:w-10 md:h-10 text-[var(--color-secondary)]"></i>
            REPORT AN ISSUE WITH YOUR SERVICE
        </h3>
        <p class="text-gray-600 text-lg uppercase font-medium">YOUR VOICE MATTERS, LET'S MAKE IT RIGHT</p>
    </div>
    
    <?php
    $status_translations = [
        'Recibido'         => 'Received',
        'Resolviendo'      => 'In Progress',
        'Acción Requerida' => 'Action Required',
        'Resuelto'         => 'Resolved',
        'Archivado'        => 'Archived'
    ];
    ?>
    <div class="max-w-7xl mx-auto grid grid-cols-1 lg:grid-cols-4 gap-8 items-start">
        
        <div class="bg-white p-6 sm:p-8 rounded-2xl shadow-xl ring-1 ring-black/5 lg:col-span-2">
            <h4 class="text-2xl font-black uppercase text-[var(--color-primary)] flex items-center gap-3 mb-6 border-b border-black/10 pb-4">
                <i data-lucide="file-pen-line" class="w-7 h-7 text-[var(--color-secondary)]"></i>
                <span>Submit a New Report</span>
            </h4>
            <form action=".db/client_report_issue.php" method="POST">
                <input type="hidden" name="client_id" value="<?php echo htmlspecialchars($client_id); ?>">
                <div class="space-y-5">
                    <div>
                        <label for="service_date" class="block text-sm font-bold uppercase text-[var(--color-primary)]/60 mb-2">Date of Affected Service</label>
                        <div class="relative">
                            <i data-lucide="calendar" class="w-5 h-5 text-gray-400 absolute left-4 top-1/2 -translate-y-1/2"></i>
                            <input type="date" id="service_date" name="service_date" class="w-full h-14 pl-12 pr-4 bg-gray-50 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[var(--color-highlight)] transition" required>
                        </div>
                    </div>
                    <div>
                        <label for="report_subject" class="block text-sm font-bold uppercase text-[var(--color-primary)]/60 mb-2">Report Subject</label>
                        <div class="relative">
                            <i data-lucide="alert-circle" class="w-5 h-5 text-gray-400 absolute left-4 top-1/2 -translate-y-1/2"></i>
                            <input type="text" id="report_subject" name="report_subject" class="w-full h-14 pl-12 pr-4 bg-gray-50 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[var(--color-highlight)] transition" required placeholder="E.g., Unremoved stain">
                        </div>
                    </div>
                    <div>
                        <label for="report_details" class="block text-sm font-bold uppercase text-[var(--color-primary)]/60 mb-2">Incident Details</label>
                         <div class="relative">
                            <i data-lucide="message-square-text" class="w-5 h-5 text-gray-400 absolute left-4 top-4"></i>
                            <textarea id="report_details" name="report_details" rows="5" class="w-full pl-12 pr-4 py-4 bg-gray-50 border border-gray-200 rounded-xl focus:ring-2 focus:ring-[var(--color-highlight)] transition" required placeholder="Describe exactly what happened..."></textarea>
                        </div>
                    </div>
                </div>
                <button type="submit" class="mt-6 w-full bg-[var(--color-primary)] text-white font-extrabold py-4 px-6 rounded-lg shadow-lg hover:brightness-110 transition flex items-center justify-center gap-2 text-base uppercase tracking-wider">
                    <span>Submit Report</span> <i data-lucide="send-horizontal"></i>
                </button>
            </form>
        </div>
        
        <div class="bg-[var(--color-primary)] text-white p-6 sm:p-8 rounded-2xl shadow-2xl ring-1 ring-white/10 lg:col-span-2">
            <h4 class="text-2xl font-black uppercase flex items-center gap-3 text-white border-b border-white/20 pb-4 mb-6">
                <i data-lucide="history" class="w-7 h-7 text-[var(--color-secondary)]"></i>
                <span>Active Reports & Messages</span>
            </h4>
            <div class="space-y-6">
                <?php
                $stmt_active_complaints = $pdo->prepare("SELECT c.id, c.title, c.status, c.created_at, (SELECT cu.message FROM complaint_updates cu WHERE cu.complaint_id = c.id AND cu.type = 'portal_message' ORDER BY cu.created_at DESC LIMIT 1) as last_message FROM complaints c WHERE c.client_id = ? AND c.status IN ('Recibido', 'Resolviendo', 'Acción Requerida') ORDER BY c.created_at DESC");
                $stmt_active_complaints->execute([$client_id]);
                $active_complaints_data = $stmt_active_complaints->fetchAll(PDO::FETCH_ASSOC);
                if (!empty($active_complaints_data)) {
                    foreach ($active_complaints_data as $complaint):
                        $status_in_db = $complaint['status'];
                        $display_status = $status_translations[$status_in_db] ?? $status_in_db;
                        $status_style = '';
                        $icon = 'info';
                        switch ($status_in_db) {
                            case 'Recibido': $status_style = 'bg-gray-200 text-gray-800'; $icon = 'check'; break;
                            case 'Resolviendo': $status_style = 'bg-blue-200 text-blue-800'; $icon = 'loader-circle animate-spin'; break;
                            case 'Acción Requerida': $status_style = 'bg-yellow-200 text-yellow-800'; $icon = 'alert-triangle'; break;
                        }
                        $message = $complaint['last_message'] ?: 'Awaiting initial response from our team.';
                ?>
                <div class="p-4 bg-white/5 rounded-xl ring-1 ring-white/10">
                    <div class="flex flex-col sm:flex-row justify-between items-start gap-2">
                        <p class="font-extrabold text-white text-lg"><?php echo htmlspecialchars($complaint['title']); ?></p>
                        <span class="px-3 py-1 text-xs font-bold rounded-full flex items-center gap-1.5 flex-shrink-0 <?php echo $status_style; ?>">
                            <i data-lucide="<?php echo $icon; ?>" class="w-4 h-4"></i> <?php echo htmlspecialchars($display_status); ?>
                        </span>
                    </div>
                    <p class="text-sm text-white/70 mt-1 font-semibold">Reported on: <?php echo date("M d, Y", strtotime($complaint['created_at'])); ?></p>
                    
                    <div class="mt-4 p-3 bg-black/20 border-l-4 border-[var(--color-secondary)] rounded">
                        <p class="font-bold text-sm text-[var(--color-secondary)]">Last Update:</p>
                        <p class="text-white/90 mt-1 text-sm italic">"<?php echo htmlspecialchars($message); ?>"</p>
                    </div>
                    
                    <?php if ($status_in_db === 'Acción Requerida'): ?>
                    <div class="mt-4 pt-4 border-t border-white/10">
                        <p class="text-sm font-bold text-white mb-2">We've proposed a solution. Are you satisfied?</p>
                        <form action=".db/client_resolve_complaint.php" method="POST" class="inline-block">
                            <input type="hidden" name="complaint_id" value="<?php echo $complaint['id']; ?>">
                            <button type="submit" class="bg-green-600 text-white font-bold py-2 px-4 rounded-lg hover:bg-green-700 transition flex items-center gap-2 text-sm">
                                <i data-lucide="check-circle" class="w-4 h-4"></i> Yes, Mark as Resolved
                            </button>
                        </form>
                    </div>
                    <?php endif; ?>
                    
                    <div class="mt-4 pt-4 border-t border-white/10">
                        <form action=".db/client_add_comment.php" method="POST">
                            <input type="hidden" name="complaint_id" value="<?php echo $complaint['id']; ?>">
                            <label for="comment-<?php echo $complaint['id']; ?>" class="block text-xs font-bold uppercase text-white/70 mb-2">Add a reply:</label>
                            <textarea id="comment-<?php echo $complaint['id']; ?>" name="comment" rows="2" class="w-full p-2 bg-white/5 border border-white/20 rounded-lg focus:ring-2 focus:ring-[var(--color-secondary)] transition text-white" placeholder="Write your message here..."></textarea>
                            <button type="submit" class="mt-2 bg-[var(--color-secondary)] text-white font-bold py-2 px-5 rounded-lg hover:brightness-110 transition flex items-center gap-2 text-sm uppercase">
                                <i data-lucide="send" class="w-4 h-4"></i> Submit Comment
                            </button>
                        </form>
                    </div>
                </div>
                <?php
                    endforeach;
                } else {
                    echo '<div class="text-center text-white/70 p-6 bg-white/5 rounded-lg border-dashed border-2 border-white/20"><i data-lucide="party-popper" class="w-10 h-10 mx-auto mb-3 text-[var(--color-secondary)]"></i><p class="font-bold">No active reports found. Everything looks great!</p></div>';
                }
                ?>
            </div>
        </div>
    </div>
    
    <div class="max-w-xl mx-auto mt-16 text-center">
        <h3 class="text-3xl font-black text-[var(--color-primary)] mb-2 flex items-center justify-center gap-2">
            <i data-lucide="archive" class="w-8 h-8 text-[var(--color-secondary)]"></i>
            RESOLVED REPORTS ARCHIVE
        </h3>
        <p class="text-gray-600 text-lg uppercase font-medium">VIEW YOUR HISTORICAL & COMPLETED ISSUES</p>
    </div>
    
    <div class="max-w-4xl mx-auto mt-8">
        <div class="bg-white p-6 sm:p-8 rounded-2xl shadow-xl ring-1 ring-black/5">
            <div class="overflow-x-auto">
                <table class="w-full text-left responsive-invoices-table">
                    <thead>
                        <tr class="border-b border-black/10">
                            <th class="py-3 px-4 text-xs font-black uppercase text-[var(--color-primary)]/60">Date Reported</th>
                            <th class="py-3 px-4 text-xs font-black uppercase text-[var(--color-primary)]/60">Subject</th>
                            <th class="py-3 px-4 text-xs font-black uppercase text-[var(--color-primary)]/60 text-center">Final Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $status_map = [
                            'Resuelto'   => 'Resolved',
                            'Archivado'  => 'Archived',
                        ];
                        $stmt_archived_complaints = $pdo->prepare("SELECT title, created_at, status FROM complaints WHERE client_id = ? AND status IN ('Resuelto', 'Archivado') ORDER BY created_at DESC");
                        $stmt_archived_complaints->execute([$client_id]);
                        $archived_complaints_data = $stmt_archived_complaints->fetchAll(PDO::FETCH_ASSOC);
                        if (!empty($archived_complaints_data)) {
                            foreach ($archived_complaints_data as $complaint):
                                $status_in_db = $complaint['status'];
                                $display_status = $status_map[$status_in_db] ?? $status_in_db;
                        ?>
                        <tr>
                            <td data-label="Date Reported" class="py-4 px-4 font-semibold text-gray-700"><?php echo date("M d, Y", strtotime($complaint['created_at'])); ?></td>
                            <td data-label="Subject" class="py-4 px-4 font-bold text-[var(--color-primary)]"><?php echo htmlspecialchars($complaint['title']); ?></td>
                            <td data-label="Final Status" class="py-4 px-4 text-center">
                                <span class="inline-flex items-center gap-1.5 px-3 py-1 text-xs font-bold bg-green-100 text-green-800 rounded-full">
                                    <i data-lucide="check-circle-2" class="w-4 h-4"></i>
                                    <span><?php echo htmlspecialchars($display_status); ?></span>
                                </span>
                            </td>
                        </tr>
                        <?php
                            endforeach;
                        } else {
                            echo '<tr><td colspan="3" class="p-8 text-center text-gray-500">No resolved or archived reports found.</td></tr>';
                        }
                        ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
    
<div id="review" class="bg-[var(--color-light)] section-container px-6 lg:px-10">
    
    <div class="mb-12 text-center max-w-4xl mx-auto">
        <h3 class="text-3xl md:text-4xl font-black text-[var(--color-primary)] mb-2 flex items-center justify-center gap-2">
            <i data-lucide="star" class="w-8 h-8 md:w-10 md:h-10 text-[var(--color-secondary)]"></i>
            SHARE YOUR EXPERIENCE
        </h3>
        <p class="text-gray-600 text-lg uppercase font-medium">YOUR OPINION, AMPLIFIED</p>
    </div>
    
    <div class="max-w-6xl mx-auto grid grid-cols-1 lg:grid-cols-6 gap-8">
        
        <div class="lg:col-span-3 bg-white p-6 sm:p-8 rounded-2xl shadow-xl border-t-4 border-[var(--color-primary)]">
            <h4 class="text-2xl font-black uppercase text-[var(--color-primary)] flex items-center gap-3 mb-6 border-b border-black/10 pb-4">
                <i data-lucide="brain" class="w-7 h-7 text-[var(--color-secondary)]"></i>
                <span>Review Generator With our AI</span>
            </h4>
            <form id="review-generator-form" class="space-y-6">
                <div>
                    <label for="review-service" class="block text-lg font-bold text-gray-800 mb-2 flex items-center gap-2">
                        <span class="bg-[var(--color-primary)] text-white font-bold rounded-full w-8 h-8 flex items-center justify-center text-sm">1</span>
                        What service did we provide?
                    </label>
                    <select id="review-service" name="service" class="w-full p-3 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-[var(--color-secondary)] transition text-lg" required>
                        <option value="" disabled selected>Select a service...</option>
                        <?php foreach ($available_services as $service): ?>
                            <option value="<?php echo $service['name']; ?>"><?php echo $service['name']; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label for="review-experience" class="block text-lg font-bold text-gray-800 mb-2 flex items-center gap-2">
                         <span class="bg-[var(--color-primary)] text-white font-bold rounded-full w-8 h-8 flex items-center justify-center text-sm">2</span>
                        How was your experience?
                    </label>
                    <select id="review-experience" name="experience" class="w-full p-3 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-[var(--color-secondary)] transition text-lg" required>
                        <option value="" disabled selected>Select an option...</option>
                        <option value="Excellent">Excellent</option>
                        <option value="Great">Great</option>
                        <option value="Amazing">Amazing</option>
                        <option value="Beyond my expectations">Beyond my expectations</option>
                    </select>
                </div>
                <div>
                    <label for="review-feeling" class="block text-lg font-bold text-gray-800 mb-2 flex items-center gap-2">
                         <span class="bg-[var(--color-primary)] text-white font-bold rounded-full w-8 h-8 flex items-center justify-center text-sm">3</span>
                        How did our service help you?
                    </label>
                    <select id="review-feeling" name="feeling" class="w-full p-3 border-2 border-gray-200 rounded-lg focus:ring-2 focus:ring-[var(--color-secondary)] transition text-lg" required>
                           <option value="" disabled selected>Select an option...</option>
                        <option value="I feel relieved and stress-free">I feel relieved and stress-free</option>
                        <option value="It saved me a lot of time">It saved me a lot of time</option>
                        <option value="I'm proud of how my space looks now">I'm proud of how my space looks now</option>
                        <option value="I finally have peace of mind">I finally have peace of mind</option>
                    </select>
                </div>
                <div class="text-center pt-4">
                    <button id="generate-review-btn" type="submit" class="bg-[var(--color-primary)] text-white font-black py-4 px-8 rounded-lg shadow-xl hover:bg-opacity-90 transition uppercase transform hover:-translate-y-0.5 flex items-center justify-center gap-3 text-lg mx-auto">
                        <i data-lucide="brain"></i>
                        <span id="review-btn-text">Generate My Review</span>
                        <div id="review-loader" class="hidden w-6 h-6 border-4 border-t-transparent border-white rounded-full animate-spin"></div>
                    </button>
                </div>
            </form>
            <div id="review-result-container" class="mt-8"></div>
        </div>
        
        <div class="lg:col-span-3">
            <div class="bg-white p-6 sm:p-8 rounded-2xl shadow-xl border border-gray-100 text-center sticky top-28">
                <i data-lucide="share-2" class="w-12 h-12 text-[var(--color-secondary)] mx-auto mb-4"></i>
                <h4 class="font-black uppercase text-3xl text-[var(--color-primary)]">Post Your Review</h4>
                <p class="mt-2 text-gray-600 font-semibold">Copy your favorite version and share it on one of these platforms. Thank you!</p>
                <div class="mt-8 flex flex-col gap-4">
                    
                    <a href="<?php echo REVIEW_LINK_GOOGLE; ?>" target="_blank" rel="noopener" class="bg-[#4285F4] text-white font-black py-4 px-4 rounded-lg hover:opacity-90 transition flex items-center justify-center gap-2 shadow-lg text-base">
                        <i data-lucide="star"></i> Review on Google
                    </a>
                    
                    <a href="<?php echo REVIEW_LINK_FACEBOOK; ?>" target="_blank" rel="noopener" class="bg-[#1877F2] text-white font-black py-4 px-4 rounded-lg hover:opacity-90 transition flex items-center justify-center gap-2 shadow-lg text-base">
                        <i data-lucide="thumbs-up"></i> Review on Facebook
                    </a>
                    
                    <a href="<?php echo REVIEW_LINK_YELP; ?>" target="_blank" rel="noopener" class="bg-[#D32323] text-white font-black py-4 px-4 rounded-lg hover:opacity-90 transition flex items-center justify-center gap-2 shadow-lg text-base">
                        <i data-lucide="message-square-text"></i> Review on Yelp
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>
              
<div id="updates" class="bg-white section-container px-6 lg:px-10">
    
    <div class="mb-12 text-center max-w-4xl mx-auto">
        <h3 class="text-3xl md:text-4xl font-black text-[var(--color-primary)] mb-2 flex items-center justify-center gap-2">
            <i data-lucide="calendar-clock" class="w-8 h-8 md:w-10 md:h-10 text-[var(--color-secondary)]"></i>
            OUR BUSINESS SCHEDULE
        </h3>
        <p class="text-gray-600 text-lg uppercase font-medium">RELIABLE & ON TIME SERVICE</p>
    </div>
    
    <div class="max-w-7xl mx-auto grid grid-cols-1 lg:grid-cols-2 gap-8">
        
        <div class="bg-white p-6 sm:p-8 rounded-2xl shadow-xl ring-1 ring-black/5 flex flex-col">
            <h4 class="text-2xl font-black uppercase text-[var(--color-primary)] flex items-center gap-3 mb-4 border-b border-black/10 pb-4">
                <i data-lucide="building-2" class="w-7 h-7 text-[var(--color-secondary)]"></i>
                <span>Current Business Status</span>
            </h4>
            
            <div class="p-4 rounded-lg <?php echo $statusColorClass; ?> border border-opacity-50">
                <div class="flex items-center gap-3">
                    <span class="relative flex h-3 w-3">
                        <?php if ($isOpen): ?>
                            <span class="animate-ping absolute inline-flex h-full w-full rounded-full <?php echo $dotColorClass; ?> opacity-75"></span>
                        <?php endif; ?>
                        <span class="relative inline-flex rounded-full h-3 w-3 <?php echo $dotColorClass; ?>"></span>
                    </span>
                    <p class="text-xl font-extrabold"><?php echo $statusMessage; ?></p>
                </div>
                <p class="mt-1 pl-6 text-sm font-semibold">Today's Hours: <?php echo $todayHours; ?></p>
            </div>
            
            <div class="flex-grow mt-6 pt-6 border-t border-black/10">
                <h4 class="text-3xl font-black text-[var(--color-primary)]/60 text-center mb-4">Prefer to talk?</h4>
                <div class="space-y-3">
                    <a href="tel:<?php echo PHONE_PRIMARY_CLICK; ?>" class="w-full bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2">
                        <i data-lucide="phone" class="w-5 h-5"></i>
                        <span>Call Us Directly</span>
                    </a>
                      <a href="https://wa.me/<?php echo WHATSAPP_NUMBER_CLICK; ?>" target="_blank" class="w-full bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2">
                        <i data-lucide="message-square" class="w-5 h-5"></i>
                        <span>Chat on WhatsApp</span>
                    </a>
                </div>
            </div>
            
            <a href="#schedule" class="mt-6 w-full bg-[var(--color-primary)] text-white font-extrabold py-3 px-6 rounded-lg shadow-lg hover:brightness-115 transition flex items-center justify-center gap-2 text-base uppercase tracking-wider">
                <i data-lucide="calendar-clock" class="w-5 h-5"></i> Book an Appointment
            </a>
        </div>
        
        <div class="bg-white p-6 sm:p-8 rounded-2xl shadow-xl ring-1 ring-black/5 flex flex-col">
            <h4 class="text-2xl font-black uppercase text-[var(--color-primary)] flex items-center gap-3 mb-4 border-b border-black/10 pb-4">
                <i data-lucide="calendar-check" class="w-7 h-7 text-[var(--color-secondary)]"></i>
                <span>Full Weekly Schedule</span>
            </h4>
            
            <ul class="space-y-1">
                <?php foreach ($weekly_hours_raw as $hours): 
                    $day = $hours['day'];
                    $isToday = ($day === $currentDayName);
                    
                    // Clases para el resaltado del día actual y del color de apertura/cierre
                    $li_classes = $isToday ? 'bg-[var(--color-highlight)]/20 shadow-md ring-1 ring-[var(--color-highlight)]' : 'bg-white hover:bg-gray-50';
                    $text_color = $hours['is_open'] ? 'text-[var(--color-primary)]' : 'text-red-500';
                    $time_color = $hours['is_open'] ? 'text-gray-800' : 'text-red-500';
                ?>
                    <li class="flex justify-between items-center px-4 py-3 rounded-xl transition-colors <?php echo $li_classes; ?>">
                        
                        <span class="text-lg font-black <?php echo $text_color; ?> flex items-center gap-2">
                            <?php if ($isToday): ?>
                                <i data-lucide="chevrons-right" class="w-4 h-4 text-[var(--color-secondary)]"></i>
                            <?php endif; ?>
                            <?php echo strtoupper($day); ?>
                        </span>
                        
                        <?php if ($hours['is_open']): ?>
                            <span class="font-black text-lg <?php echo $time_color; ?>">
                                <?php echo date("g:i A", strtotime($hours['open_time'])) . " - " . date("g:i A", strtotime($hours['close_time'])); ?>
                            </span>
                        <?php else: ?>
                            <span class="font-black text-base <?php echo $time_color; ?>">CLOSED</span>
                        <?php endif; ?>
                    </li>
                <?php endforeach; ?>
            </ul>
        </div>
    </div>
</div>
</main>

   <?php @include '../files/page-footer.php'; ?>
    
<script>
    // ==========================================================
    // 0. DECLARACIÓN DE CONSTANTES Y VARIABLES GLOBALES (INYECTADAS POR PHP)
    // ==========================================================

    // Variables de PHP inyectadas para el calendario y contador
    const DB_SCHEDULE_CONFIG = <?php echo json_encode($db_schedule_config); ?>;
    const DB_WEEKLY_HOURS = <?php echo json_encode($db_weekly_hours); ?>;
    const DB_BLOCKED_DATES = <?php echo json_encode($db_blocked_dates); ?>;
    const OCCUPIED_SLOTS = <?php echo json_encode($occupied_slots); ?>; 
    const CAPACITY = parseInt(DB_SCHEDULE_CONFIG.capacity);
    
    // Variables del contador (inyectadas por PHP)
    const IS_NEXT_APPOINTMENT_CONFIRMED = <?php echo $isNextAppointmentConfirmed ? 'true' : 'false'; ?>;
    const NEXT_APPOINTMENT_ISO = "<?php echo $nextAppointmentISO; ?>";
    
    // Variables de estado y elementos del DOM para el Calendario
    let currentDate = new Date();
    const calendarGridPublic = document.getElementById('calendar-grid-public');
    const slotsContainer = document.getElementById('slots-container');
    const slotButtonsContainer = document.getElementById('slot-buttons');
    const bookingConfirmationContainer = document.getElementById('booking-confirmation-container'); 
    const clientBookingForm = document.getElementById('client-booking-form');
    
    // Elementos del DOM para Perfil y Menús
    const profilePanel = document.getElementById('profile-panel');
    const overlay = document.getElementById('overlay');
    const menuToggleBtn = document.getElementById('menu-toggle-btn');
    const mobileNavPanel = document.getElementById('mobile-nav-panel'); 
    const menuCloseBtn = document.getElementById('menu-close-btn');
    
    // ==========================================================
    // 1. LÓGICA DEL CONTADOR REGRESIVO (DASHBOARD)
    // ==========================================================

    if (IS_NEXT_APPOINTMENT_CONFIRMED) {
        const dashAppointmentDate = new Date(NEXT_APPOINTMENT_ISO).getTime();
        const dashCountdownContainer = document.getElementById('dashboard-countdown');
        const dashAppointmentTimeDisplay = document.getElementById('dash-appointment-time');

        function startDashboardCountdown() {
            const now = new Date().getTime();
            const distance = dashAppointmentDate - now;

            if (distance < 0) {
                if (dashCountdownContainer) {
                    dashCountdownContainer.innerHTML = `
                        <h4 class="text-sm font-black text-green-600 uppercase mb-2 flex items-center justify-center gap-2">
                            <i data-lucide="check-circle" class="w-4 h-4"></i>
                            Service is Today or Completed!
                        </h4>
                        <p class="text-lg font-black text-center text-[var(--color-primary)]">${dashAppointmentTimeDisplay.textContent.replace('@ ', '')}</p>
                    `;
                    lucide.createIcons();
                }
                clearInterval(dashCountdownInterval);
                return;
            }

            const days = Math.floor(distance / (1000 * 60 * 60 * 24));
            const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((distance % (1000 * 60)) / 1000);

            const pad = (num) => num.toString().padStart(2, '0');

            document.getElementById("dash-days").innerHTML = pad(days);
            document.getElementById("dash-hours").innerHTML = pad(hours);
            document.getElementById("dash-minutes").innerHTML = pad(minutes);
            document.getElementById("dash-seconds").innerHTML = pad(seconds);
        }

        startDashboardCountdown();
        const dashCountdownInterval = setInterval(startDashboardCountdown, 1000);
    }

    // ==========================================================
    // 2. UTILIDADES DE FORMATO Y VISTA
    // ==========================================================

    function toggleVisibility(element, show) {
        if (element) element.classList.toggle('hidden', !show);
    }
    
    function formatTime(hour, minute) {
        return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`;
    }

    function formatTime12h(timeStr24h) {
        if (!timeStr24h) return '';
        const [hours, minutes] = timeStr24h.split(':').map(Number);
        const displayHours = hours % 12 || 12;
        const ampm = hours >= 12 ? 'PM' : 'AM';
        const displayMinutes = String(minutes).padStart(2, '0');
        return `${displayHours}:${displayMinutes} ${ampm}`;
    }
    
    function formatPhoneNumber(input) {
        let value = input.value.replace(/\D/g, '');
        value = value.substring(0, 10);
        const areaCode = value.substring(0, 3);
        const middle = value.substring(3, 6);
        const last = value.substring(6, 10);
        if (value.length > 6) {
            input.value = `(${areaCode}) ${middle}-${last}`;
        } else if (value.length > 3) {
            input.value = `(${areaCode}) ${middle}`;
        } else if (value.length > 0) {
            input.value = `(${areaCode}`;
        } else {
            input.value = '';
        }
    }

    function renderGreeting() {
        var day = new Date();
        var currentHour = day.getHours();
        var greetingText, iconName;
        var styleClass = 'text-xl sm:text-2xl font-black tracking-wide uppercase text-[var(--color-primary)]'; 
        
        if (currentHour >= 0 && currentHour < 12) {
            greetingText = "Good Morning!"; iconName = "sun";
        } else if (currentHour >= 12 && currentHour <= 17) {
            greetingText = "Good Afternoon!"; iconName = "cloud-sun";
        } else {
            greetingText = "Good Evening!"; iconName = "moon";
        }
        
        const greetingDisplay = document.getElementById('greeting-display');
        if (greetingDisplay) {
            greetingDisplay.innerHTML = 
                `<span class="inline-flex items-center gap-3 ${styleClass}">
                    <i data-lucide="${iconName}" class="w-7 h-7 text-[var(--color-secondary)]"></i>
                    <span>${greetingText}</span>
                </span>`;
        }
    }


    // ==========================================================
    // 3. LÓGICA DEL CALENDARIO Y AGENDAMIENTO
    // ==========================================================
    
    function generateAvailableSlots(dateStr) {
        const selectedDate = new Date(dateStr + 'T00:00:00');
        const dayOfWeekIndex = selectedDate.getDay();
        const daysMap = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
        const dayName = daysMap[dayOfWeekIndex];
        
        if (DB_BLOCKED_DATES.includes(dateStr)) return [];
        const dayConfig = DB_WEEKLY_HOURS[dayName];
        if (!dayConfig || !dayConfig.is_open) return [];

        const slotDuration = DB_SCHEDULE_CONFIG.slot_duration || 60;
        let currentTime = new Date(dateStr + 'T' + dayConfig.open_time);
        const endTime = new Date(dateStr + 'T' + dayConfig.close_time);
        const now = new Date();
        const isToday = selectedDate.toDateString() === now.toDateString();
        
        if (isToday) {
            let currentMinutes = now.getHours() * 60 + now.getMinutes();
            let nextSlotMinutes = Math.ceil(currentMinutes / slotDuration) * slotDuration;
            
            let todayStartTime = new Date(dateStr + 'T00:00:00');
            todayStartTime.setHours(Math.floor(nextSlotMinutes / 60), nextSlotMinutes % 60, 0);

            if (todayStartTime.getTime() >= endTime.getTime()) return [];
            if (todayStartTime.getTime() > currentTime.getTime()) currentTime = todayStartTime;
        }
        
        const availableSlots = [];
        while (currentTime.getTime() < endTime.getTime()) {
            const hour = currentTime.getHours();
            const minute = currentTime.getMinutes();
            const timeKey = formatTime(hour, minute); 
            const uniqueKey = dateStr + ' ' + timeKey;
            const slotsOccupied = OCCUPIED_SLOTS[uniqueKey] || 0;
            
            if (slotsOccupied < CAPACITY) {
                availableSlots.push({ hour, minute, occupied: slotsOccupied });
            }
            currentTime.setTime(currentTime.getTime() + slotDuration * 60 * 1000);
        }
        return availableSlots;
    }
    
    function handlePublicSlotClick(dateStr, timeStr) {
        document.getElementById('form-date').value = dateStr;
        document.getElementById('form-time').value = timeStr + ':00';
        
        const date = new Date(dateStr + 'T00:00:00');
        const displayDate = date.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
        
        document.getElementById('selected-slot-display').textContent = `${displayDate} at ${timeStr}`;
        
        toggleVisibility(bookingConfirmationContainer, true); 
        bookingConfirmationContainer.scrollIntoView({ behavior: 'smooth', block: 'start' }); 
    }

    function renderDaySlots(dateStr) {
        const slots = generateAvailableSlots(dateStr);
        let buttonsHtml = '';
        const date = new Date(dateStr + 'T00:00:00');
        const displayDate = date.toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' });
        
        document.getElementById('slots-subheader').classList.add('hidden'); 

        if (slots.length > 0) {
            document.getElementById('slots-header').innerHTML = `<i data-lucide="clock" class="w-7 h-7 text-[var(--color-secondary)]"></i> AVAILABLE SLOTS FOR ${displayDate.toUpperCase()}`;
            
            slots.forEach(slot => {
                const timeStr24h = formatTime(slot.hour, slot.minute);
                const timeStr12h = formatTime12h(timeStr24h); 
                const remaining = CAPACITY - slot.occupied;
                
                buttonsHtml += `<button type="button" 
                                        class="bg-[var(--color-highlight)] hover:bg-[var(--color-primary)] hover:text-white text-[var(--color-primary)] font-black p-3 rounded-lg border-2 border-[var(--color-primary)] shadow-sm transition-all uppercase flex flex-col items-center justify-center"
                                        data-date="${dateStr}" 
                                        data-time="${timeStr24h}" 
                                        onclick="handlePublicSlotClick('${dateStr}', '${timeStr24h}')">
                                        <span class="text-xl">${timeStr12h}</span>
                                        <span class="text-xs mt-1">${remaining} spot${remaining !== 1 ? 's' : ''}</span>
                                    </button>`;
            });
            slotButtonsContainer.innerHTML = buttonsHtml;
            toggleVisibility(slotsContainer, true);
            lucide.createIcons();
            slotsContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
        } else {
            document.getElementById('slots-header').innerHTML = `<i data-lucide="clock" class="w-7 h-7 text-[var(--color-secondary)]"></i> NO SLOTS AVAILABLE FOR ${displayDate.toUpperCase()}`;
            slotButtonsContainer.innerHTML = `<p class="text-gray-500 col-span-full text-center py-8 text-lg font-medium uppercase">No available slots for this date.</p>`;
            toggleVisibility(slotsContainer, true);
            slotsContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
    }

    function renderWeeklyView() {
        const dayOfWeek = currentDate.getDay();
        let displayStartDate = new Date(currentDate);
        displayStartDate.setDate(currentDate.getDate() - dayOfWeek);

        let html = '';
        const endOfWeek = new Date(displayStartDate);
        endOfWeek.setDate(displayStartDate.getDate() + 6);

        document.getElementById('week-title').textContent =
            displayStartDate.toLocaleDateString('en-US', { month: 'long', day: 'numeric' }) +
            ' - ' +
            endOfWeek.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' });

        for (let i = 0; i < 7; i++) {
            const day = new Date(displayStartDate);
            day.setDate(displayStartDate.getDate() + i);
            const dayString = day.toISOString().split('T')[0];
            const now = new Date();
            const todayMidnight = now.setHours(0, 0, 0, 0); 
            const isPast = day.getTime() < todayMidnight;
            const isToday = day.toDateString() === now.toDateString();
            const dayName = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][i];
            
            let dayClasses = 'bg-white p-2 min-h-[80px] relative text-center flex flex-col justify-start items-center transition-all border border-gray-200';
            let dayNumberClasses = 'font-black text-4xl text-black';

            const availableSlotsToday = generateAvailableSlots(dayString);
            const slotsAvailable = availableSlotsToday.length;
            const isBlocked = DB_BLOCKED_DATES.includes(dayString);
            const isAvailable = slotsAvailable > 0 && !isPast && !isBlocked;

            let content = `<p class="${dayNumberClasses}">${day.getDate()}</p>`;

            if (isPast || isBlocked || !slotsAvailable) {
                dayClasses += ' opacity-60 bg-gray-100 cursor-not-allowed';
                if (isBlocked) {
                    content += `<div class="mt-1 text-xs font-black text-[var(--color-secondary)] uppercase bg-red-100 px-1 py-0.5 rounded-full whitespace-nowrap">BLOCKED</div>`;
                } else if (!isPast && DB_WEEKLY_HOURS[dayName]?.is_open) {
                    content += `<div class="mt-1 text-xs font-bold text-gray-400 uppercase">FULL</div>`;
                } else if (!DB_WEEKLY_HOURS[dayName]?.is_open) {
                    content += `<div class="mt-1 text-xs font-bold text-gray-400 uppercase">CLOSED</div>`;
                }
            }
            
            if (isAvailable) {
                dayClasses += ' hover:bg-green-50 cursor-pointer border-l-4 border-l-green-500';
                content += `<div class="mt-1 text-xs font-black text-green-600 uppercase bg-green-100 px-1 py-0.5 rounded-full whitespace-nowrap">✓ ${slotsAvailable} Available</div>`;
            }
            
            if (isToday && !isPast) {
                dayNumberClasses += ' text-[var(--color-primary)]';
                dayClasses = dayClasses.replace('bg-gray-100', 'bg-white'); 
            }

            html += `<div class="${dayClasses}" data-date="${dayString}" data-clickable="${isAvailable}">`;
            html += content;
            html += `</div>`;
        }

        calendarGridPublic.innerHTML = html;
        setupCalendarListeners();
        lucide.createIcons();
    }
    
    function setupCalendarListeners() {
        calendarGridPublic.querySelectorAll('[data-clickable="true"]').forEach(dayElement => {
            dayElement.removeEventListener('click', handleDayClick);
            dayElement.addEventListener('click', handleDayClick);
        });
        if (document.getElementById('prev-btn-public')) document.getElementById('prev-btn-public').addEventListener('click', handlePrevClick);
        if (document.getElementById('next-btn-public')) document.getElementById('next-btn-public').addEventListener('click', handleNextClick);
    }

    function handleDayClick() {
        calendarGridPublic.querySelectorAll('div').forEach(el => {
            el.classList.remove('border-4', 'border-[var(--color-highlight)]', 'z-10');
        });
        this.classList.add('border-4', 'border-[var(--color-highlight)]', 'z-10');
        const dateStr = this.dataset.date;
        renderDaySlots(dateStr);
        toggleVisibility(bookingConfirmationContainer, false);
    }

    function handlePrevClick() {
        currentDate.setDate(currentDate.getDate() - 7);
        renderWeeklyView();
        toggleVisibility(slotsContainer, false);
        toggleVisibility(bookingConfirmationContainer, false);
    }
    
    function handleNextClick() {
        currentDate.setDate(currentDate.getDate() + 7);
        renderWeeklyView();
        toggleVisibility(slotsContainer, false);
        toggleVisibility(bookingConfirmationContainer, false);
    }

    // ==========================================================
    // 4. MANEJO DE FORMS Y EVENTOS GLOBALES
    // ==========================================================

    function openProfilePanel() {
        profilePanel.classList.remove('translate-x-full');
        overlay.classList.remove('hidden');
    }

    function closeProfilePanel() {
        profilePanel.classList.add('translate-x-full');
        overlay.classList.add('hidden');
    }

    function openMobileMenu() {
        if (mobileNavPanel) {
            mobileNavPanel.classList.remove('-translate-x-full');
            overlay.classList.remove('hidden');
        }
    }
    
    function closeMobileMenu() {
         if (mobileNavPanel) {
            mobileNavPanel.classList.add('-translate-x-full');
            overlay.classList.add('hidden');
        }
    }

    document.addEventListener('DOMContentLoaded', () => {
        
        // --- 4.1 Listeners de Menú y Perfil ---
        const openProfileBtnTop = document.getElementById('profile-open-btn-top'); 
        const openProfileBtnAvatar = document.getElementById('profile-open-btn-avatar'); 
        const openProfileBtnMobile = document.getElementById('profile-open-btn-mobile'); 
        const closeProfileBtn = document.getElementById('profile-close-btn');
        const menuCloseBtn = document.getElementById('menu-close-btn');

        // Menú Hamburguesa (Abre)
        if (menuToggleBtn) menuToggleBtn.addEventListener('click', openMobileMenu);
        
        // Menú Hamburguesa (Cierra)
        if (menuCloseBtn) menuCloseBtn.addEventListener('click', closeMobileMenu);
        
        // Cerrar menú al hacer clic en un enlace (Cierra)
        const allNavLinks = mobileNavPanel ? mobileNavPanel.querySelectorAll('a') : [];
        allNavLinks.forEach(link => { link.addEventListener('click', closeMobileMenu); });

        // Perfil (Abre)
        if (openProfileBtnTop) openProfileBtnTop.addEventListener('click', (e) => { e.preventDefault(); openProfilePanel(); });
        if (openProfileBtnAvatar) openProfileBtnAvatar.addEventListener('click', (e) => { e.preventDefault(); openProfilePanel(); });
        if (openProfileBtnMobile) openProfileBtnMobile.addEventListener('click', (e) => { 
             e.preventDefault();
            closeMobileMenu();
            setTimeout(openProfilePanel, 300);
        });
        
        // Perfil (Cierra)
        if (closeProfileBtn) closeProfileBtn.addEventListener('click', closeProfilePanel);
        
        // Overlay (cierra cualquier panel abierto)
        if (overlay) overlay.addEventListener('click', () => {
            closeProfilePanel();
            closeMobileMenu();
        });

        // --- 4.2 Manejo de Formato de Teléfono ---
        const phoneInput = document.getElementById('phone');
        const mobileInput = document.getElementById('mobile');
        if (phoneInput) phoneInput.addEventListener('input', () => formatPhoneNumber(phoneInput));
        if (mobileInput) mobileInput.addEventListener('input', () => formatPhoneNumber(mobileInput));

        // --- 4.3 Listener del Formulario de Reserva (Booking) ---
        if (clientBookingForm) {
            clientBookingForm.addEventListener('submit', async function(e) { 
                e.preventDefault();
                const formData = new FormData(this);
                const data = Object.fromEntries(formData);
                
                if (!data.service_id || data.service_id === '') {
                    showToast('Please select a service type to continue.', 'error');
                    return;
                }

                const submitBtn = this.querySelector('button[type="submit"]');
                submitBtn.disabled = true;
                const originalBtnHtml = submitBtn.innerHTML;
                submitBtn.innerHTML = '<i data-lucide="loader" class="w-6 h-6 inline-block mr-2 animate-spin"></i> PROCESSING...';
                lucide.createIcons();

                try {
                    const response = await fetch('db/agenda-booking-handler.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) });
                    
                    if (!response.ok) throw new Error(`Server responded with status: ${response.status}`);
                    
                    let result;
                    try { result = await response.json(); } catch (jsonError) { throw new Error('Server response was not valid JSON.'); }
                    
                    if (result.status === 'success') {
                        showToast("✓ Appointment successfully booked! Redirecting...", 'success');
                        
                        if (result.token) { setTimeout(() => { window.location.href = `booking-status.php?token=${result.token}`; }, 500); } 
                        else { showToast("Token missing in response.", 'error'); }

                    } else {
                        showToast(`Booking Error: ${result.message}`, 'error');
                        submitBtn.disabled = false;
                        submitBtn.innerHTML = originalBtnHtml; 
                        lucide.createIcons();
                    }
                } catch (error) {
                    console.error("Fetch Error:", error);
                    showToast(`Connection Error: Could not reach agenda-booking-handler.php. Details: ${error.message}`, 'error');
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalBtnHtml; 
                    lucide.createIcons();
                }
            });
        }
        
        // --- 4.4 Lógica del Generador de Reseñas ---
        const reviewForm = document.getElementById('review-generator-form');
        if (reviewForm) {
            const generateBtn = document.getElementById('generate-review-btn');
            const btnText = document.getElementById('review-btn-text');
            const loader = document.getElementById('review-loader');
            const resultContainer = document.getElementById('review-result-container');
            
            reviewForm.addEventListener('submit', async function(e) {
                e.preventDefault();
                btnText.textContent = 'Generating...';
                loader.classList.remove('hidden');
                generateBtn.disabled = true;
                resultContainer.innerHTML = '<div class="text-center py-4">Connecting with IA Marketing Tool</div>';
                const formData = new FormData(reviewForm);
                const data = Object.fromEntries(formData.entries());
                
                try {
                    const response = await fetch('api-review-generator.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(data)
                    });
                    const result = await response.json();
                    if (!response.ok) throw new Error(result.error || 'An unknown error occurred.');
                    
                    displayResults(result.review_1, result.review_2);
                    showToast('Your reviews are ready!', 'success');
                } catch (error) {
                    resultContainer.innerHTML = `<div class="bg-red-100 text-center p-4 text-red-700 rounded-lg border border-red-300"><p><strong>Error:</strong> ${error.message}</p></div>`;
                    showToast('Failed to generate reviews.', 'error');
                } finally {
                    btnText.textContent = 'Generate Again';
                    loader.classList.add('hidden');
                    generateBtn.disabled = false;
                }
            });
            
            function displayResults(review1, review2) {
                resultContainer.innerHTML = `
                    <div class="space-y-6 pt-6 border-t">
                        <div class="bg-gray-50 p-6 rounded-xl shadow-inner border">
                            <h3 class="font-bold text-xl text-[var(--color-primary)] mb-3">Option 1: Direct & To the Point</h3>
                            <p class="text-gray-700 leading-relaxed">${review1}</p>
                            <div class="text-right mt-4">
                                <button class="copy-btn bg-[var(--color-secondary)] text-white font-bold uppercase py-2 px-4 rounded-lg hover:brightness-110 transition flex items-center gap-2 ml-auto">
                                    <i data-lucide="copy"></i><span class="copy-text">Copy Text</span>
                                </button>
                            </div>
                        </div>
                        <div class="bg-gray-50 p-6 rounded-xl shadow-inner border">
                            <h3 class="font-bold text-xl text-[var(--color-primary)] mb-3">Option 2: Personal & Emotional</h3>
                            <p class="text-gray-700 leading-relaxed">${review2}</p>
                            <div class="text-right mt-4">
                                <button class="copy-btn bg-[var(--color-secondary)] text-white font-bold uppercase py-2 px-4 rounded-lg hover:brightness-110 transition flex items-center gap-2 ml-auto">
                                    <i data-lucide="copy"></i><span class="copy-text">Copy Text</span>
                                </button>
                            </div>
                        </div>
                    </div>`;
                lucide.createIcons();
                attachCopyListeners();
                resultContainer.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
            
            function attachCopyListeners() {
                resultContainer.querySelectorAll('.copy-btn').forEach(button => {
                    button.addEventListener('click', function() {
                        const reviewText = this.closest('.rounded-xl').querySelector('p').innerText;
                        navigator.clipboard.writeText(reviewText).then(() => {
                            this.querySelector('.copy-text').textContent = 'Copied!';
                            this.querySelector('i').setAttribute('data-lucide', 'check');
                            lucide.createIcons();
                            showToast('Review copied to clipboard!', 'success');
                            setTimeout(() => {
                                this.querySelector('.copy-text').textContent = 'Copy Text';
                                this.querySelector('i').setAttribute('data-lucide', 'copy');
                                lucide.createIcons();
                            }, 2500);
                        });
                    });
                });
            }
        }


        // --- 4.5 Inicialización Final ---
        renderGreeting(); 
        if (calendarGridPublic) renderWeeklyView();
        lucide.createIcons();
    });
</script>
<script src="../files/toast.js"></script>
</body>
</html>