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

$ci = $client_info ?? [];
$br = $branding ?? [];

// Configuración WhatsApp
$wa = $ci['whatsapp'] ?? ['display' => 'N/A', 'link' => '#'];
$whatsapp_contact = $wa['display'] ?? ''; 
$whatsapp_url_link = $wa['link'] ?? ''; 

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);

// Variables visuales
$google_font_url = $google_font_url ?? '';
$logo_url = $ci['logo_url'] ?? '';
$full_title = $br['full_title'] ?? '';
$favicon = $br['favicon'] ?? '';

// Lógica de Token y Base de Datos
$token = $_GET['token'] ?? '';
$cita = null;

if ($token) {
    try {
        // Consulta a la tabla correcta 'unique_appointments'
        $stmt = $pdo->prepare("
            SELECT ua.*, 
                   COALESCE(c.first_name, l.first_name) as first_name,
                   COALESCE(c.last_name, l.last_name) as last_name,
                   COALESCE(c.email, l.email) as email,
                   COALESCE(c.phone, l.phone) as phone,
                   COALESCE(c.street_address, l.street_address) as address,
                   COALESCE(c.city, l.city) as city,
                   COALESCE(c.state_province, l.state_province) as state,
                   COALESCE(c.zip_code, l.zip_code) as zip
            FROM unique_appointments ua
            LEFT JOIN clients c ON ua.client_id = c.id
            LEFT JOIN leads l ON ua.lead_id = l.id
            WHERE ua.public_token = ? LIMIT 1
        ");
        $stmt->execute([$token]);
        $cita = $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        error_log("APPOINTMENT STATUS DB Fetch Error: " . $e->getMessage());
    }
}

// Función para formatear hora
function formatTime12hStatus($timeStr24h) {
    if (!$timeStr24h) return '';
    $timestamp = strtotime($timeStr24h);
    return ($timestamp === false) ? $timeStr24h : date('g:i A', $timestamp);
}

// Lógica de Estados
$isPending = ($cita['status'] === 'pending');
$isConfirmed = ($cita['status'] === 'confirmed');
$isCompleted = ($cita['status'] === 'completed');
$isCancelled = ($cita['status'] === 'cancelled');

// Configuración de UI según estado
$headerBg = 'bg-gray-500'; $headerIcon = 'help-circle'; $headerTitle = 'UNKNOWN STATUS'; $headerSub = 'Please contact support for assistance.';

if ($isPending) { 
    $headerBg = 'bg-orange-500'; 
    $headerIcon = 'clock'; 
    $headerTitle = 'REQUEST RECEIVED'; 
    $headerSub = 'We are reviewing your request. You will receive a confirmation shortly.'; 
}
if ($isConfirmed) { 
    $headerBg = 'bg-green-600'; 
    $headerIcon = 'check-circle'; 
    $headerTitle = 'CONFIRMED APPOINTMENT'; 
    $headerSub = 'Everything is set! Our team is scheduled to see you.'; 
}
if ($isCompleted) { 
    $headerBg = 'bg-blue-600'; 
    $headerIcon = 'thumbs-up'; 
    $headerTitle = 'SERVICE COMPLETED'; 
    $headerSub = 'Thank you for trusting us with your service.'; 
}
if ($isCancelled) { 
    $headerBg = 'bg-red-500'; 
    $headerIcon = 'x-circle'; 
    $headerTitle = 'CANCELLED'; 
    $headerSub = 'This appointment has been cancelled.'; 
}

// Preparar fecha para JS (Countdown)
$appointmentDateTime = '';
if (!empty($cita['appointment_date']) && !empty($cita['appointment_time'])) {
    try {
        $dateTime = new DateTime($cita['appointment_date'] . ' ' . $cita['appointment_time']);
        $appointmentDateTime = $dateTime->format(DateTime::ATOM);
    } catch (Exception $e) {
        error_log("DateTime parsing error: " . $e->getMessage());
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Status - <?php echo htmlspecialchars($ci['business_name'] ?? 'Appointment System'); ?></title>
    <meta name="robots" content="noindex, nofollow">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($favicon); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($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="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'] ?? '');
            // Mensaje coherente para checar status
            $wa_message = "Hi! I'm on your website and would like to check my appointment status.";
            
            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 Status Checker</p>
                </div>
            </div>
            
        </div>
    </header>

    <main class="max-w-3xl mx-auto px-4 py-8">
        
        <?php if ($cita): ?>

            <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-sync" class="w-6 h-6 text-[var(--color-secondary)] mb-2 md:mb-0"></i>
                    <h3 class="text-4xl font-black text-gray-800"> TRACK YOUR APPOINTMENT</h3>
                </div>
                <p class="text-lg uppercase font-bold text-[var(--color-secondary)]">Real-time status updates for your service</p>
            </section>
        
            <section class="bg-white p-6 md:p-8 rounded-xl shadow-md border border-gray-200 mb-8">
                <div class="<?php echo htmlspecialchars($headerBg); ?> -m-6 md:-m-8 mb-6 md:mb-8 p-6 md:p-8 text-center text-white rounded-t-xl transition-colors duration-300">
                    <div class="inline-flex items-center justify-center w-16 h-16 md:w-20 md:h-20 bg-white bg-opacity-20 rounded-full mb-4">
                        <i data-lucide="<?php echo htmlspecialchars($headerIcon); ?>" class="w-8 h-8 md:w-10 md:h-10"></i>
                    </div>
                    <h3 class="text-2xl md:text-3xl font-black uppercase"><?php echo htmlspecialchars($headerTitle); ?></h3>
                    <p class="mt-2 text-white text-opacity-90 font-medium text-base md:text-lg"><?php echo htmlspecialchars($headerSub); ?></p>
                </div>
                
                <?php if ($isConfirmed && $appointmentDateTime): ?>
                <div id="countdown-container" class="bg-red-500/10 border border-red-200 p-4 md:p-6 rounded-lg mb-8 text-center">
                    <h4 class="text-xl font-black text-red-600 uppercase mb-3 flex items-center justify-center gap-2">
                            <i data-lucide="clock" class="w-6 h-6"></i>
                            TIME REMAINING FOR YOUR APPOINTMENT
                    </h4>
                    <div class="flex justify-center items-center space-x-4 font-black text-red-700">
                        <div class="text-center">
                            <span id="days" class="text-3xl md:text-4xl">00</span>
                            <p class="text-sm uppercase font-bold text-gray-500">Days</p>
                        </div>
                        <span class="text-3xl">:</span>
                        <div class="text-center">
                            <span id="hours" class="text-3xl md:text-4xl">00</span>
                            <p class="text-sm uppercase font-bold text-gray-500">Hours</p>
                        </div>
                        <span class="text-3xl">:</span>
                        <div class="text-center">
                            <span id="minutes" class="text-3xl md:text-4xl">00</span>
                            <p class="text-sm uppercase font-bold text-gray-500">Minutes</p>
                        </div>
                        <span class="text-3xl">:</span>
                        <div class="text-center">
                            <span id="seconds" class="text-3xl md:text-4xl">00</span>
                            <p class="text-sm uppercase font-bold text-gray-500">Seconds</p>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <div class="mb-6">
                    <h4 class="text-xl font-black text-[var(--color-primary)] mb-4 uppercase flex items-center gap-2">
                        <i data-lucide="user" class="w-6 h-6"></i>
                        Client Information
                    </h4>
                    <div class="bg-gray-50 p-4 rounded-lg border border-gray-200">
                        <p class="text-2xl font-black text-gray-800 uppercase"><?php echo htmlspecialchars($cita['first_name'] . ' ' . $cita['last_name']); ?></p>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-3 mt-3">
                            <div class="flex items-center gap-2">
                                <i data-lucide="mail" class="w-4 h-4 text-gray-400"></i>
                                <span class="text-gray-700 font-medium"><?php echo htmlspecialchars($cita['email']); ?></span>
                            </div>
                            <div class="flex items-center gap-2">
                                <i data-lucide="phone" class="w-4 h-4 text-gray-400"></i>
                                <span class="text-gray-700 font-medium"><?php echo htmlspecialchars($cita['phone']); ?></span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="mb-6">
                    <h4 class="text-xl font-black text-[var(--color-primary)] mb-4 uppercase flex items-center gap-2">
                        <i data-lucide="calendar-clock" class="w-6 h-6"></i>
                        Appointment Details
                    </h4>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div class="bg-gray-50 p-4 rounded-lg border border-gray-200">
                            <div class="flex items-center gap-3">
                                <div class="bg-[var(--color-highlight)] bg-opacity-20 p-3 rounded-lg">
                                    <i data-lucide="calendar" class="w-6 h-6 text-[var(--color-primary)]"></i>
                                </div>
                                <div>
                                    <p class="text-xs font-bold text-gray-400 uppercase">Date</p>
                                    <p class="text-lg font-black text-gray-800"><?php echo htmlspecialchars(date('M d, Y', strtotime($cita['appointment_date']))); ?></p>
                                </div>
                            </div>
                        </div>
                        <div class="bg-gray-50 p-4 rounded-lg border border-gray-200">
                            <div class="flex items-center gap-3">
                                <div class="bg-[var(--color-highlight)] bg-opacity-20 p-3 rounded-lg">
                                    <i data-lucide="clock" class="w-6 h-6 text-[var(--color-primary)]"></i>
                                </div>
                                <div>
                                    <p class="text-xs font-bold text-gray-400 uppercase">Time</p>
                                    <p class="text-lg font-black text-gray-800"><?php echo htmlspecialchars(formatTime12hStatus($cita['appointment_time'])); ?></p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if (!empty($cita['address'])): ?>
                <div class="mb-6">
                    <h4 class="text-xl font-black text-[var(--color-primary)] mb-4 uppercase flex items-center gap-2">
                        <i data-lucide="map-pin" class="w-6 h-6"></i>
                        Service Location
                    </h4>
                    <div class="bg-gray-50 p-4 rounded-lg border border-gray-200">
                        <p class="font-medium text-gray-800"><?php echo htmlspecialchars($cita['address']); ?></p>
                        <p class="text-gray-600 mt-1">
                            <?php echo htmlspecialchars($cita['city']); ?>, 
                            <?php echo htmlspecialchars($cita['state']); ?> 
                            <?php echo htmlspecialchars($cita['zip']); ?>
                        </p>
                    </div>
                </div>
                <?php endif; ?>

                <div class="pt-4 border-t-2 border-gray-200 space-y-3">
                    
                    <?php if ($isCompleted || $isCancelled): ?>
                        <?php
                            $f_name = urlencode(htmlspecialchars($cita['first_name'] ?? ''));
                            $l_name = urlencode(htmlspecialchars($cita['last_name'] ?? ''));
                            $email = urlencode(htmlspecialchars($cita['email'] ?? ''));
                            $phone = urlencode(htmlspecialchars($cita['phone'] ?? ''));
                            $addr = urlencode(htmlspecialchars($cita['address'] ?? ''));
                            $city = urlencode(htmlspecialchars($cita['city'] ?? ''));
                            $state = urlencode(htmlspecialchars($cita['state'] ?? ''));
                            $zip = urlencode(htmlspecialchars($cita['zip'] ?? ''));
                        ?>
                        <a href="booking.php?fname=<?php echo $f_name; ?>&lname=<?php echo $l_name; ?>&email=<?php echo $email; ?>&phone=<?php echo $phone; ?>&addr=<?php echo $addr; ?>&city=<?php echo $city; ?>&state=<?php echo $state; ?>&zip=<?php echo $zip; ?>" 
                            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 AGAIN
                        </a>
                    <?php endif; ?>
                    
                    <button onclick="window.location.reload()" 
                            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="refresh-cw" class="w-4 h-4 inline-block mr-2"></i>
                        Refresh Status
                    </button>
                </div>
            </section>

        <?php else: ?>
        <section class="w-full bg-white rounded-2xl shadow-2xl overflow-hidden border-t-8 border-[var(--color-secondary)] text-center p-8">
            
            <div class="w-32 h-32 bg-[var(--color-secondary)] rounded-full flex items-center justify-center mx-auto mb-4 border-4 border-red-200">
                <i data-lucide="calendar-off" class="w-20 h-20 text-white"></i>
            </div>
            
            <h3 class="text-3xl font-black text-[var(--color-primary)] uppercase mb-2">APPOINTMENT NOT FOUND</h3>
            
            <p class="text-gray-500 text-lg mb-6">The page you just accessed does not exist or the link has expired</p>
            
            <a href="booking.php" 
                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="calendar-plus" class="w-4 h-4"></i> 
                BOOK AN APPOINTMENT
            </a>
            
            <?php if (!empty($phone_primary)): ?>
                <a href="tel:<?php echo htmlspecialchars($phone_primary); ?>" 
                   class="w-full bg-[var(--color-primary)] hover:opacity-90 text-white font-black mt-4 py-2.5 px-4 rounded-lg uppercase sm:w-auto flex items-center justify-center gap-2">
                    <i data-lucide="phone-call" class="w-4 h-4"></i> CALL OFFICE TO HELP
                </a>
            <?php endif; ?>
            
            <p class="text-md text-gray-400 mt-4">If you believe this is an error, please contact the office.</p>
            <p class="text-lg font-black text-gray-400 mt-4 items-center justify-center"><?php echo htmlspecialchars($ci['business_name'] ?? ''); ?></p>

        </section>
    <?php endif; ?>

    </main>

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

    <script>
        lucide.createIcons();
        
        // Lógica del contador de tiempo restante (JavaScript)
        <?php if ($isConfirmed && $appointmentDateTime): ?>
        
        const appointmentDate = new Date("<?php echo htmlspecialchars($appointmentDateTime); ?>").getTime(); 
        const countdownContainer = document.getElementById('countdown-container');

        function startCountdown() {
            const now = new Date().getTime();
            const distance = appointmentDate - now;

            // Si el contador ha llegado a cero
            if (distance < 0) {
                if (countdownContainer) {
                      countdownContainer.innerHTML = `
                          <h4 class="text-xl font-black text-red-600 uppercase mb-3 flex items-center justify-center gap-2">
                              <i data-lucide="check-circle" class="w-6 h-6"></i>
                              APPOINTMENT TIME HAS PASSED
                          </h4>
                          <p class="text-lg text-gray-700 font-bold">The service should be underway or completed.</p>
                      `;
                      lucide.createIcons();
                }
                clearInterval(countdownInterval);
                return;
            }

            // Cálculo del tiempo restante (días, horas, minutos, segundos)
            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));
            // Faltaba el cálculo de segundos en el código anterior
            const seconds = Math.floor((distance % (1000 * 60)) / 1000);

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

            // Actualizar el DOM
            const elDays = document.getElementById("days");
            const elHours = document.getElementById("hours");
            const elMinutes = document.getElementById("minutes");
            const elSeconds = document.getElementById("seconds");

            if(elDays) elDays.innerHTML = pad(days);
            if(elHours) elHours.innerHTML = pad(hours);
            if(elMinutes) elMinutes.innerHTML = pad(minutes);
            if(elSeconds) elSeconds.innerHTML = pad(seconds);
        }

        // Ejecutar inmediatamente
        startCountdown();

        // Actualizar cada 1 segundo
        const countdownInterval = setInterval(startCountdown, 1000);
        
        <?php endif; ?>
    </script>
    <script src="files/toast.js"></script>
</body>
</html>