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

// Inicialización de variables de acceso rápido y fallbacks
$ci = $client_info ?? [];
$br = $branding ?? [];
$wa = $ci['whatsapp'] ?? ['display' => 'N/A', 'link' => '#'];
$google_font_url = $google_font_url ?? '';
$logo_url = $ci['logo_url'] ?? '';
$full_title = $br['full_title'] ?? '';
$favicon = $br['favicon'] ?? '';

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

// LIMPIEZA DEL TOKEN DE ENTRADA
$raw_token = $_GET['token'] ?? '';
$token = trim(preg_replace('/[^a-fA-F0-9]/', '', $raw_token)); 
$appointment = null;
$error_type = 'missing'; 

// Función para formatear la hora (g:i A -> 10:30 AM)
function formatTime12hConfirmation($timeStr24h) {
    if (!$timeStr24h) return '';
    $timestamp = strtotime($timeStr24h);
    return ($timestamp === false) ? $timeStr24h : date('g:i A', $timestamp);
}

if (!empty($token) && isset($pdo)) {
    try {
        // Consulta optimizada para unique_appointments unida con clientes o leads
        $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 = :token LIMIT 1
        ");
        $stmt->execute(['token' => $token]);
        $appointment = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$appointment) {
            $error_type = 'invalid';
        }
    } catch (Exception $e) {
        error_log("APPOINTMENT CONFIRMATION DB Fetch Error: " . $e->getMessage());
        $error_type = 'db_error';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Confirmation - <?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); ?>">
    
    <link rel="stylesheet" href="style.css">
    <script src="https://unpkg.com/lucide@latest"></script>
    
</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 corregido gramaticalmente
            $wa_message = "Hi! I'm on your website and would like to know about my 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">
        
        <?php if ($appointment): ?>
            <?php 
                $isPending = ($appointment['status'] === 'pending');
                $isConfirmed = ($appointment['status'] === 'confirmed');
                $isCancelled = ($appointment['status'] === 'cancelled');
                
                if ($isPending) {
                    $headerBg = 'bg-orange-500'; 
                    $headerIcon = 'clock'; 
                    $headerTitle = 'ACTION REQUIRED'; 
                    $headerSub = 'Please confirm your attendance';
                } elseif ($isConfirmed) {
                    $headerBg = 'bg-green-600'; 
                    $headerIcon = 'check-circle'; 
                    $headerTitle = 'APPOINTMENT CONFIRMED'; 
                    $headerSub = 'Everything is set! See you soon';
                } elseif ($isCancelled) {
                    $headerBg = 'bg-red-500'; 
                    $headerIcon = 'x-circle'; 
                    $headerTitle = 'APPOINTMENT CANCELLED'; 
                    $headerSub = 'This appointment has been cancelled';
                } else { 
                    $headerBg = 'bg-blue-600'; 
                    $headerIcon = 'thumbs-up'; 
                    $headerTitle = 'APPOINTMENT COMPLETED'; 
                    $headerSub = 'Thank you for your visit';
                }
            ?>
            
            <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-clock" class="w-6 h-6 text-[var(--color-secondary)] mb-2 md:mb-0"></i>
                    <h3 class="text-4xl font-black text-gray-800"> YOUR APPOINTMENT STATUS</h3>
                </div>
                <p class="text-lg uppercase font-bold text-[var(--color-secondary)]">Review the details and manage your appointment below</p>
            </section>
   

            <section class="bg-white p-6 md:p-8 rounded-xl shadow-md border border-gray-200 mb-8 w-full">
                <div id="status-header" 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 id="status-icon" data-lucide="<?php echo htmlspecialchars($headerIcon); ?>" class="w-8 h-8 md:w-10 md:h-10"></i>
                    </div>
                    <h3 id="status-title" class="text-2xl md:text-3xl font-black uppercase"><?php echo htmlspecialchars($headerTitle); ?></h3>
                    <p id="status-subtitle" class="mt-2 text-white text-opacity-90 font-medium text-base md:text-lg"><?php echo htmlspecialchars($headerSub); ?></p>
                </div>
                
                <div class="mb-6">
                    <h4 class="text-xl font-black text-gray-800 mb-4 uppercase flex items-center gap-2">
                        <i data-lucide="user" class="w-6 h-6 text-[var(--color-secondary)]"></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($appointment['first_name'] . ' ' . $appointment['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($appointment['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($appointment['phone']); ?></span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="mb-6">
                    <h4 class="text-xl font-black text-gray-800 mb-4 uppercase flex items-center gap-2">
                        <i data-lucide="calendar-clock" class="w-6 h-6 text-[var(--color-secondary)]"></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($appointment['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(formatTime12hConfirmation($appointment['appointment_time'])); ?></p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if (!empty($appointment['address'])): ?>
                <div class="mb-6">
                    <h4 class="text-xl font-black text-gray-800 mb-4 uppercase flex items-center gap-2">
                        <i data-lucide="map-pin" class="w-6 h-6 text-[var(--color-secondary)]"></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($appointment['address']); ?></p>
                        <p class="text-gray-600 mt-1">
                            <?php echo htmlspecialchars($appointment['city']); ?>, 
                            <?php echo htmlspecialchars($appointment['state']); ?> 
                            <?php echo htmlspecialchars($appointment['zip']); ?>
                        </p>
                    </div>
                </div>
                <?php endif; ?>

                <div id="action-panel" class="pt-4 border-t-2 border-gray-200">
                    <?php $statusLink = 'booking-status.php?token=' . urlencode($token); ?>
                    
                    <?php if ($isPending): ?>
                        <div class="bg-orange-50 border-2 border-orange-200 rounded-lg p-4 mb-4 text-center">
                            <p class="text-orange-800 font-bold uppercase text-sm">Confirmation Required</p>
                            <p class="text-xs text-gray-600 mt-1">Please confirm your attendance to secure your appointment slot</p>
                        </div>
                        
                        <div class="grid grid-cols-1 gap-3">
                            <button 
                                id="confirm-btn" 
                                data-token="<?php echo htmlspecialchars($token); ?>"
                                class="w-full bg-green-600 hover:bg-green-700 text-white font-black py-4 px-6 rounded-lg uppercase shadow-lg transform transition hover:-translate-y-1 flex items-center justify-center gap-2 text-xl">
                                <i data-lucide="check-circle" class="w-6 h-6"></i>
                                YES, I CONFIRM
                            </button>
                            
                            <?php
                                $f_name = urlencode(htmlspecialchars($appointment['first_name'] ?? ''));
                                $l_name = urlencode(htmlspecialchars($appointment['last_name'] ?? ''));
                                $email = urlencode(htmlspecialchars($appointment['email'] ?? ''));
                                $phone = urlencode(htmlspecialchars($appointment['phone'] ?? ''));
                            ?>
                            <a href="booking.php?fname=<?php echo $f_name; ?>&lname=<?php echo $l_name; ?>&email=<?php echo $email; ?>&phone=<?php echo $phone; ?>" 
                                class="w-full bg-white border-2 border-gray-300 text-gray-600 hover:border-gray-400 hover:text-gray-800 font-bold py-3 px-6 rounded-lg uppercase shadow-sm flex items-center justify-center gap-2">
                                <i data-lucide="edit-2" class="w-5 h-5"></i>
                                NO, I NEED TO MODIFY
                            </a>
                        </div>
                        <p class="text-xs text-center text-gray-400 mt-4" id="pending-message">Confirming reserves your spot immediately.</p>
                    
                    <?php elseif ($isConfirmed): ?>
                        <div class="bg-green-50 border-2 border-green-200 rounded-lg p-4 mb-4 text-center">
                            <p class="text-green-800 font-bold uppercase text-sm">✓ Confirmed</p>
                            <p class="text-xs text-gray-600 mt-1">You're all set! We look forward to seeing you</p>
                        </div>
                        <a href="<?php echo htmlspecialchars($statusLink); ?>" 
                           class="w-full bg-blue-600 hover:bg-blue-700 text-white font-black py-4 px-6 rounded-lg uppercase shadow-lg flex items-center justify-center gap-2 text-lg transition mb-3">
                            <i data-lucide="map-pin" class="w-6 h-6"></i>
                            TRACK YOUR APPOINTMENT
                        </a>

                    <?php elseif ($isCancelled || $appointment['status'] === 'completed'): ?>
                        <div class="bg-red-50 border-2 border-red-200 rounded-lg p-4 mb-4 text-center">
                            <p class="text-red-800 font-bold uppercase text-sm">✕ <?php echo $isCancelled ? 'Cancelled' : 'Completed'; ?></p>
                            <p class="text-xs text-gray-600 mt-1">This appointment status is final.</p>
                        </div>
                        <a href="booking.php" 
                           class="w-full bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-4 px-6 rounded-lg uppercase shadow-lg flex items-center justify-center gap-2">
                            <i data-lucide="calendar-plus" class="w-6 h-6"></i>
                            BOOK AGAIN
                        </a>
                    <?php else: ?>
                         <a href="booking.php" 
                           class="w-full bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-4 px-6 rounded-lg uppercase shadow-lg flex items-center justify-center gap-2">
                            <i data-lucide="calendar-plus" class="w-6 h-6"></i>
                            BOOK AGAIN
                        </a>
                    <?php endif; ?>
                </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($ci['phone_primary'])): ?>
                <a href="tel:<?php echo htmlspecialchars($ci['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();
        
        const confirmBtn = document.getElementById('confirm-btn');
        const actionPanel = document.getElementById('action-panel');
        const statusHeader = document.getElementById('status-header');
        const statusIcon = document.getElementById('status-icon');
        const statusTitle = document.getElementById('status-title');
        const statusSubtitle = document.getElementById('status-subtitle');

        if (confirmBtn) {
            confirmBtn.addEventListener('click', async function() {
                const token = this.dataset.token;
                const originalContent = this.innerHTML;
                
                this.disabled = true;
                this.innerHTML = '<i data-lucide="loader" class="w-6 h-6 animate-spin mr-2"></i> PROCESSING...';
                lucide.createIcons(); 

                try {
                    // LLamada al handler de confirmación
                    const res = await fetch('db/agenda-confirm-handler.php', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({ 
                            token: token,
                            csrf_token: '<?php echo htmlspecialchars($_SESSION['csrf_token'] ?? ''); ?>' 
                        })
                    });
                    const data = await res.json();

                    if (data.status === 'success') {
                        showToast("Confirmation Successful! Redirecting...", "success");

                        const statusLink = `booking-status.php?token=${token}`;
                        let countdownSeconds = 5; 
                        
                        actionPanel.innerHTML = `
                            <div id="confirmation-message" class="bg-green-50 border-2 border-green-200 rounded-lg p-4 mb-4 text-center">
                                <p class="text-green-800 font-bold uppercase text-sm">✓ Successfully Confirmed</p>
                                <p class="text-xs text-gray-600 mt-1" id="countdown-message">Redirecting to status page in ${countdownSeconds} seconds...</p>
                            </div>
                            <a href="${statusLink}" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-black py-4 px-6 rounded-lg uppercase shadow-lg flex items-center justify-center gap-2 text-lg transition">
                                <i data-lucide="map-pin" class="w-6 h-6"></i> TRACK YOUR APPOINTMENT NOW
                            </a>
                        `;
                        lucide.createIcons();
                        
                        if (statusHeader) {
                            statusHeader.classList.remove('bg-orange-500'); 
                            statusHeader.classList.add('bg-green-600');
                            
                            if (statusIcon) statusIcon.setAttribute('data-lucide', 'check-circle');
                            if (statusTitle) statusTitle.textContent = 'APPOINTMENT CONFIRMED';
                            if (statusSubtitle) statusSubtitle.textContent = 'Everything is set! See you soon';
                            lucide.createIcons(); 
                        }
                        
                        setTimeout(() => {
                            const countdownElement = document.getElementById('countdown-message');
                            
                            if (countdownElement) {
                                const countdownInterval = setInterval(() => {
                                    countdownSeconds--;
                                    if (countdownSeconds <= 0) {
                                        clearInterval(countdownInterval);
                                        window.location.href = statusLink;
                                    } else {
                                        countdownElement.textContent = `Redirecting to status page in ${countdownSeconds} seconds...`;
                                    }
                                }, 1000);
                            }
                        }, 100); 

                    } else {
                        showToast(data.message, "error");
                        this.disabled = false;
                        this.innerHTML = originalContent;
                        lucide.createIcons();
                    }
                } catch (e) {
                    showToast("Connection Error", "error");
                    this.disabled = false;
                    this.innerHTML = originalContent;
                    lucide.createIcons();
                }
            });
        }
    </script>
    <script src="files/toast.js"></script>
</body>
</html>