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

// Definir usuario por defecto si no existe en la configuración global
$user_id_to_query = $ci['user_id'] ?? 1; 

// Valores por defecto para el calendario
$db_schedule_config = [
    'slot_duration' => 60, 
    'capacity' => 1, 
    'start_time' => '09:00:00', 
    'end_time' => '17:00:00', 
    'work_days' => ['1', '2', '3', '4', '5']
];
$db_weekly_hours = [];
$db_blocked_dates = [];
$occupied_slots = [];

// Configuración de WhatsApp
$whatsapp_contact = $wa['display'] ?? ''; 
$whatsapp_url_link = $wa['link'] ?? ''; 

// Función para formatear número de EE.UU.
function formatUSPhoneNumber($number) {
    $number = preg_replace('/[^0-9]/', '', $number);
    if (strlen($number) === 10) {
        return '(' . substr($number, 0, 3) . ') ' . substr($number, 3, 3) . '-' . substr($number, 6, 4);
    }
    return $number;
}

$whatsapp_display_formatted = formatUSPhoneNumber($whatsapp_contact);

// Mapeo de días en Inglés
$daysMapEnglish = [
    0 => 'Sunday', 1 => 'Monday', 2 => 'Tuesday', 3 => 'Wednesday',
    4 => 'Thursday', 5 => 'Friday', 6 => 'Saturday'
];

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

    // 1. Cargar Configuración del Scheduler desde la tabla 'schedule_config'
    $stmt_sched_config = $pdo->prepare("SELECT slot_duration, capacity, start_time, end_time, work_days FROM schedule_config WHERE user_id = ? LIMIT 1");
    $stmt_sched_config->execute([$user_id_to_query]);
    
    if ($row = $stmt_sched_config->fetch(PDO::FETCH_ASSOC)) {
        $activeWorkDays = !empty($row['work_days']) ? explode(',', $row['work_days']) : [];
        $db_schedule_config = [
            'slot_duration' => (int)$row['slot_duration'],
            'capacity'      => (int)$row['capacity'],
            'start_time'    => $row['start_time'],
            'end_time'      => $row['end_time'],
            'work_days'     => $activeWorkDays
        ];
    }
    
    // Rellenar las horas semanales
    $activeDays = $db_schedule_config['work_days'];
    for ($i = 0; $i <= 6; $i++) {
        $dayName = $daysMapEnglish[$i];
        $isOpen = in_array((string)$i, $activeDays);
        $db_weekly_hours[$dayName] = [
            'is_open'    => $isOpen,
            'open_time'  => $isOpen ? $db_schedule_config['start_time'] : '00:00:00',
            'close_time' => $isOpen ? $db_schedule_config['end_time'] : '00:00:00'
        ];
    }

    // 2. Obtener Fechas Bloqueadas desde 'staff_blocked_days'
    $stmt_blocked_dates = $pdo->prepare("SELECT DISTINCT blocked_date FROM staff_blocked_days JOIN staff ON staff_blocked_days.staff_id = staff.id WHERE staff.user_id = ?");
    $stmt_blocked_dates->execute([$user_id_to_query]);
    $db_blocked_dates = $stmt_blocked_dates->fetchAll(PDO::FETCH_COLUMN);

    // 3. Obtener Slots Ocupados desde 'unique_appointments'
    // Se usa 'unique_appointments' porque es la tabla transaccional de citas reales
    $stmt_occupied_slots = $pdo->prepare("
        SELECT 
            ua.appointment_date, 
            ua.appointment_time, 
            COUNT(ua.id) as count 
        FROM unique_appointments ua
        WHERE 
            ua.user_id = ? AND 
            ua.status NOT IN ('cancelled', 'completed')
        GROUP BY 
            ua.appointment_date, 
            ua.appointment_time
    ");
    $stmt_occupied_slots->execute([$user_id_to_query]);
    
    $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'];
    }

} catch (PDOException $e) {
    error_log("BOOKING PAGE ERROR (Database): " . $e->getMessage());
    die("Internal Platform Error. Please try again later. (Ref: Booking-DB-Load)");
} catch (Exception $e) {
    error_log("BOOKING PAGE ERROR (General): " . $e->getMessage());
    die("Internal Platform Error. Please try again later. (Ref: Booking-General-Load)");
}

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>Booking Appointment System - <?php echo htmlspecialchars($biz['company_name'] ?? ''); ?></title>
    <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($branding['favicon'] ?? '/core/img/favicon.png'); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($branding['favicon'] ?? '/core/img/favicon.png'); ?>">
    
    <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>
    <script src="https://unpkg.com/imask"></script>
    <link rel="stylesheet" href="style.css">
</head>
<body class="max-w-full mx-auto bg-[var(--color-background)]">
    <div id="toast-container" class="toast-container"></div>
    
    <header class="bg-white shadow-sm top-0 z-20 border-b-4 border-[var(--color-highlight)]">
        <div class="max-w-6xl mx-auto px-4 py-4 flex flex-col md:flex-row justify-between items-center space-y-3 md:space-y-0">
            
            <div class="flex-shrink-0 flex items-center justify-center">
                <?php if (!empty($biz['logo_url'])): ?>
                    <img src="<?php echo htmlspecialchars($biz['logo_url']); ?>" alt="Logo <?php echo htmlspecialchars($biz['company_name'] ?? ''); ?>" class="h-20 md:h-12 object-contain">
                <?php else: ?>
                    <h2 class="text-2xl font-black text-[var(--color-primary)] uppercase">
                        <?php echo htmlspecialchars($biz['company_name'] ?? ''); ?>
                    </h2>
                <?php endif; ?>
            </div>

            <?php 
            $wa_clean = preg_replace('/[^0-9]/', '', $biz['whatsapp'] ?? '');
            $wa_message = "Hi! I'm on your website and would like to schedule an appointment.";
            
            if (!empty($biz['whatsapp'])): 
            ?>
                <a href="https://wa.me/<?php echo $wa_clean; ?>?text=<?php echo rawurlencode($wa_message); ?>" 
                   target="_blank" 
                   class="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 w-full md:w-auto order-3 md:order-none">
                    <i data-lucide="message-circle" class="w-5 h-5"></i>
                    <span class="text-lg">WHATSAPP: <?php echo formatUSPhoneNumber($biz['whatsapp']); ?></span>
                </a>
            <?php endif; ?>

            <div class="hidden md:block flex-shrink-0 text-right">
                <h1 class="text-2xl md:text-3xl font-black text-[var(--color-primary)] leading-none">
                    <?php echo htmlspecialchars($biz['company_name'] ?? ''); ?>
                </h1>
                <div class="flex items-center justify-end gap-2 text-[var(--color-secondary)]">
                    <i data-lucide="calendar-check" class="w-5 h-5"></i>
                    <p class="text-sm font-black uppercase tracking-wide">Appointment Booking System</p>
                </div>
            </div>
            
        </div>
    </header>
    
    <main class="max-w-3xl mx-auto px-4 py-8">
        
        <section class="mb-8 text-center">
            <div class="flex flex-col items-center justify-center md:flex-row md:gap-2"> 
                <i data-lucide="calendar-check" class="w-6 h-6 text-[var(--color-secondary)] mb-2 md:mb-0"></i>
                <h3 class="text-4xl font-black text-gray-800"> BOOK YOUR APPOINTMENT</h3>
            </div>
            <p class="text-lg uppercase font-bold text-[var(--color-secondary)]">Select an available date and time slot below</p>
        </section>

        <section 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">
                    <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-gray-700 uppercase px-4 py-2 text-center"></h4>
                <button id="next-btn-public" class="p-2 rounded-md hover:bg-gray-200 transition-colors">
                    <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-[var(--color-primary)] bg-gray-50 border-b p-2">
                <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 gap-px bg-gray-200 border border-gray-200 rounded-b-lg overflow-hidden min-h-[100px] overflow-x-auto"></div>
        </section>

        <section 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-gray-800 flex flex-col items-center justify-center md:flex-row md:gap-2">
                    </h3>
                <p class="text-lg uppercase font-bold text-[var(--color-secondary)] mb-4">Select the time that works best for you</p>
                <p id="slots-subheader" class="hidden"></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>
        </section>

        <section id="booking-form-container" class="bg-white p-6 md:p-8 rounded-xl shadow-2xl hidden">
            <div class="text-center mb-6"> 
                <div class="flex flex-col items-center justify-center md:flex-row md:gap-2 mb-1">
                    <i data-lucide="user-check" class="w-8 h-8 text-[var(--color-secondary)] mb-2 md:mb-0"></i>
                    <h3 class="text-2xl md:text-3xl font-black text-gray-800">CONFIRM YOUR RESERVATION</h3>
                </div>
                <p class="text-lg uppercase font-bold text-[var(--color-secondary)]">Please verify your details below to finalize the appointment</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">Selected Appointment:</p>
                <p id="selected-slot-display" class="text-2xl font-black text-[var(--color-primary)] mt-2"></p>
            </div>
    
            <form id="public-booking-form" class="space-y-4">
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['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"> 
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-md font-bold text-gray-600 mb-1 uppercase">Your First Name *</label>
                        <input type="text" name="first_name" required class="w-full p-3 border border-gray-300 rounded-lg" value="<?php echo htmlspecialchars($_GET['fname'] ?? ''); ?>">
                    </div>
                    <div>
                        <label class="block text-md font-bold text-gray-600 mb-1 uppercase">Your Last Name *</label>
                        <input type="text" name="last_name" required class="w-full p-3 border border-gray-300 rounded-lg" value="<?php echo htmlspecialchars($_GET['lname'] ?? ''); ?>">
                    </div>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-md font-bold text-gray-600 mb-1 uppercase">Most Used Email Address *</label>
                        <input type="email" name="email" required class="w-full p-3 border border-gray-300 rounded-lg" value="<?php echo htmlspecialchars($_GET['email'] ?? ''); ?>">
                    </div>
                    <div>
                        <label class="block text-md font-bold text-gray-600 mb-1 uppercase">Primary Phone Number*</label>
                        <input type="tel" name="phone" id="phone-input" required maxlength="14" placeholder="(555) 555-1212" class="w-full p-3 border border-gray-300 rounded-lg" value="<?php echo htmlspecialchars($_GET['phone'] ?? ''); ?>">
                    </div>
                </div>
                
                <div class="space-y-4 pt-2">
                    <label class="block text-md font-black text-gray-700 mb-1 uppercase">SERVICE LOCATION ADDRESS *</label>
                    <div>
                        <label class="block text-xs font-bold text-gray-600 mb-1 uppercase">Street Address</label>
                        <input type="text" name="address_line" required class="w-full p-3 border border-gray-300 rounded-lg" value="<?php echo htmlspecialchars($_GET['addr'] ?? ''); ?>">
                    </div>

                    <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
                        <div>
                            <label class="block text-xs font-bold text-gray-600 mb-1 uppercase">City</label>
                            <input type="text" name="city" required class="w-full p-3 border border-gray-300 rounded-lg" value="<?php echo htmlspecialchars($_GET['city'] ?? ''); ?>">
                        </div>
                        <div>
                            <label class="block text-xs font-bold text-gray-600 mb-1 uppercase">State</label>
                            <input type="text" name="state" required class="w-full p-3 border border-gray-300 rounded-lg" value="<?php echo htmlspecialchars($_GET['state'] ?? ''); ?>">
                        </div>
                        <div>
                            <label class="block text-xs font-bold text-gray-600 mb-1 uppercase">Zip Code</label>
                            <input type="text" name="zip_code" required class="w-full p-3 border border-gray-300 rounded-lg" value="<?php echo htmlspecialchars($_GET['zip'] ?? ''); ?>">
                        </div>
                    </div>
                </div>

                <button type="submit" class="w-full bg-[var(--color-secondary)] hover:opacity-90 text-white p-4 font-black rounded-lg transition uppercase shadow-md flex items-center justify-center gap-2 text-lg">
                    <i data-lucide="calendar-plus" class="w-6 h-6"></i> 
                    BOOK YOUR APPOINTMENT 
                </button>
            </form>
        </section>
    </main>

    <?php @include 'brand/page-footer.php'; ?>

<script>
    let currentDate = new Date();
    let calendarGridPublic = document.getElementById('calendar-grid-public');
    let slotsContainer = document.getElementById('slots-container');
    let slotButtonsContainer = document.getElementById('slot-buttons');
    let bookingFormContainer = document.getElementById('booking-form-container');

    // Datos desde PHP (Backend seguro)
    const dbScheduleConfig = <?php echo json_encode($db_schedule_config); ?>;
    const dbWeeklyHours = <?php echo json_encode($db_weekly_hours); ?>;
    const dbBlockedDates = <?php echo json_encode($db_blocked_dates); ?>;
    const occupiedSlots = <?php echo json_encode($occupied_slots); ?>; 
    const capacity = parseInt(dbScheduleConfig.capacity);

    // Formato tiempo sistema (HH:MM)
    function formatTime(hour, minute) {
        return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`;
    }

    // Formato tiempo visualización (12 Horas AM/PM)
    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 toggleVisibility(element, show) {
        element.classList.toggle('hidden', !show);
    }
    
    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' 
        });
        
        const timeStr12h = formatTime12h(timeStr);
        document.getElementById('selected-slot-display').textContent = `${displayDate} at ${timeStr12h}`;
        
        toggleVisibility(bookingFormContainer, true);
        bookingFormContainer.scrollIntoView({ behavior: 'smooth', block: 'start' }); 
    }
    
    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 (dbBlockedDates.includes(dateStr)) return [];
        const dayConfig = dbWeeklyHours[dayName];
        if (!dayConfig || !dayConfig.is_open) return [];

        const slotDuration = dbScheduleConfig.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();
        
        // Ajustar slots si es el día actual (no mostrar slots pasados)
        if (isToday) {
            let currentMinutes = now.getHours() * 60 + now.getMinutes();
            let nextSlotMinutes = Math.ceil((currentMinutes + 1) / 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 = occupiedSlots[uniqueKey] || 0;
            
            if (slotsOccupied < capacity) {
                availableSlots.push({ hour, minute, occupied: slotsOccupied });
            }
            currentTime.setTime(currentTime.getTime() + slotDuration * 60 * 1000);
        }
        return availableSlots;
    }

    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-3xl';

            const availableSlotsToday = generateAvailableSlots(dayString);
            const slotsAvailable = availableSlotsToday.length;
            const isBlocked = dbBlockedDates.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 && dbWeeklyHours[dayName]?.is_open) {
                     content += `<div class="mt-1 text-xs font-bold text-gray-400 uppercase">FULL</div>`;
                } else if (!dbWeeklyHours[dayName]?.is_open) {
                     content += `<div class="mt-1 text-xs font-bold text-gray-400 uppercase">CLOSED</div>`;
                } else if (isPast) {
                     content += `<div class="mt-1 text-xs font-bold text-gray-400 uppercase">PAST</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} spot${slotsAvailable !== 1 ? 's' : ''}</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);
        });
        document.getElementById('prev-btn-public').removeEventListener('click', handlePrevClick);
        document.getElementById('prev-btn-public').addEventListener('click', handlePrevClick);
        document.getElementById('next-btn-public').removeEventListener('click', handleNextClick);
        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(bookingFormContainer, false); 
    }

    function handlePrevClick() {
        currentDate.setDate(currentDate.getDate() - 7);
        renderWeeklyView();
        toggleVisibility(slotsContainer, false);
        toggleVisibility(bookingFormContainer, false);
    }
    
    function handleNextClick() {
        currentDate.setDate(currentDate.getDate() + 7);
        renderWeeklyView();
        toggleVisibility(slotsContainer, false);
        toggleVisibility(bookingFormContainer, false);
    }
    
    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) {
            // Diseño del header de slots
            document.getElementById('slots-header').innerHTML = `
                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 {
            // Diseño para cuando no hay slots
            document.getElementById('slots-header').innerHTML = `
                <i data-lucide="clock" class="w-7 h-7 text-[var(--color-secondary)] mb-2 md:mb-0"></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' });
        }
    }
    
    // Máscara para teléfono (US Format)
    const phoneInput = document.getElementById('phone-input');
    if (phoneInput) {
        phoneInput.addEventListener('input', function(e) {
            let value = e.target.value.replace(/\D/g, ''); 
            if (value.length > 10) value = value.substring(0, 10);
            let formattedValue = '';
            if (value.length > 0) formattedValue += '(' + value.substring(0, 3);
            if (value.length >= 4) formattedValue += ') ' + value.substring(3, 6);
            if (value.length >= 7) formattedValue += '-' + value.substring(6, 10);
            e.target.value = formattedValue;
        });
    }

    // Envío del formulario
    document.getElementById('public-booking-form').addEventListener('submit', async function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        const data = Object.fromEntries(formData);
        
        // Validación básica
        const phoneDigits = (data.phone || '').replace(/\D/g, '');
        if (phoneDigits.length !== 10) {
            showToast('Phone number must be exactly 10 digits (US format).', '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 {
            // Llamada al handler en la carpeta DB
            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();
        }
    });

    document.addEventListener('DOMContentLoaded', () => {
        renderWeeklyView();
        lucide.createIcons();
    });
</script>
<script src="files/toast.js"></script>
</body>
</html>