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

$ci = $client_info ?? [];
$br = $branding ?? [];
$wa = $ci['whatsapp'] ?? ['display' => 'N/A', 'link' => '#'];

// Configuración visual
$google_font_url = $google_font_url ?? '';
$logo_url = $ci['logo_url'] ?? '';
$full_title = $br['full_title'] ?? '';
$favicon = $br['favicon'] ?? '';

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

// FIX: Validación para evitar el error "Cannot redeclare"
if (!function_exists('formatUSPhoneNumber')) {
    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);
$csrf_token = $_SESSION['csrf_token'] ?? ''; 

// --- VERIFICACIÓN DE SERVICIO ---
$raw_token = $_GET['token'] ?? '';
// Limpieza estricta del token
$token = trim(preg_replace('/[^a-zA-Z0-9.\-_]/', '', $raw_token)); 
$appt = null;
$view = 'invalid';
$staffPhoto = '';
$clientFn = 'Valued Customer';
$staffFn = 'Staff';
$staffLn = 'Member';
$serviceName = 'Service'; // Default

// Mensaje por defecto (Genérico)
$wa_message = "Hi! I have a question about the service verification."; 

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

if ($token && isset($pdo)) {
    try {
        // CORRECCIÓN: Agregamos JOIN a 'services' para obtener el nombre del servicio
        $stmt = $pdo->prepare("
            SELECT ua.*, 
                   s.first_name as staff_fn, s.last_name as staff_ln, s.profile_photo_url, s.job_title,
                   c.first_name as client_fn, c.last_name as client_ln, c.id as client_id,
                   srv.name as service_name
            FROM unique_appointments ua
            LEFT JOIN staff s ON ua.staff_id = s.id
            LEFT JOIN clients c ON ua.client_id = c.id
            LEFT JOIN services srv ON ua.service_id = srv.id
            WHERE ua.verification_token = ? AND ua.verification_token IS NOT NULL LIMIT 1
        ");

        $stmt->execute([$token]);
        $appt = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($appt) {
            $view = 'verify';
            
            $clientFn = htmlspecialchars($appt['client_fn'] ?? 'Valued Customer');
            $staffFn = htmlspecialchars($appt['staff_fn'] ?? 'Staff');
            $staffLn = htmlspecialchars($appt['staff_ln'] ?? 'Member');
            $serviceName = htmlspecialchars($appt['service_name'] ?? 'Service');
            
            // CORRECCIÓN: Mensaje de WhatsApp Personalizado con ID y Nombre del Servicio
            $wa_message = "Hi! I have a question regarding the verification for {$serviceName} (Ref: #{$appt['id']}).";

            // Construcción segura de la URL de la foto:
            if (!empty($appt['profile_photo_url'])) {
                $staffPhoto = htmlspecialchars($appt['profile_photo_url']); 
            } else {
                $staffPhoto = "https://ui-avatars.com/api/?name=".urlencode($staffFn . ' ' . $staffLn) . "&background=random&color=fff&size=128";
            }
        }
    } catch (Exception $e) {
        error_log("SERVICE VERIFICATION DB Error: " . $e->getMessage());
        $view = 'db_error';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Verify Service - <?php echo htmlspecialchars($ci['company_name'] ?? ''); ?> <?php echo htmlspecialchars($full_title); ?></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'] ?? '');
        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="check-circle" class="w-5 h-5"></i>
                <p class="text-sm font-black uppercase tracking-wide">Service Verification System</p>
            </div>
        </div>
        
    </div>
</header>

<main class="max-w-3xl mx-auto px-4 py-8">
    
    <?php if ($view === 'verify'): ?>
    
    <section class="bg-white w-full max-w-md mx-auto rounded-2xl shadow-xl overflow-hidden border border-gray-100 animate-[fadeIn_0.5s_ease-out]">
        
        <div class="bg-[var(--color-primary)] p-6 text-white text-center relative rounded-t-2xl">
            <div class="absolute inset-0 opacity-10 bg-[radial-gradient(circle_at_center,_var(--tw-gradient-stops))] from-white via-transparent to-transparent pointer-events-none"></div>

            <div class="flex flex-col items-center justify-center gap-4 relative z-10">
                <div class="relative">
                    <img src="<?php echo htmlspecialchars($staffPhoto); ?>" class="w-32 h-32 rounded-full border-4 border-[var(--color-highlight)] object-cover bg-gray-200 shadow-lg" alt="Staff Photo: <?php echo $staffFn; ?>">
                    <div class="absolute bottom-0 right-0 bg-green-500 text-white p-1.5 rounded-full border-2 border-white shadow-sm">
                        <i data-lucide="check" class="w-4 h-4"></i>
                    </div>
                </div>

                <div class="text-center">
                    <p class="text-xs text-white/70 uppercase tracking-widest font-bold mb-1">Performed by</p>
                    <h2 class="text-3xl font-black uppercase leading-tight tracking-tight shadow-black drop-shadow-md">
                        <?php echo htmlspecialchars($staffFn . ' ' . $staffLn); ?>
                    </h2>
                    <p class="text-sm text-white/90 font-medium mt-1 bg-black/20 px-3 py-1 rounded-full inline-block">
                        <?php echo htmlspecialchars($appt['job_title'] ?? 'Service Specialist'); ?>
                    </p>
                </div>
            </div>

            <div class="bg-white/10 backdrop-blur-sm rounded-xl p-3 mt-6 text-center shadow-inner border border-white/10">
                <p class="text-xs opacity-70 uppercase font-bold mb-1">Service Completed</p>
                <p class="font-bold text-lg leading-none mb-2"><?php echo $serviceName; ?></p>
                
                <div class="flex justify-center gap-4 text-sm pt-2 border-t border-white/20">
                    <span><?php echo htmlspecialchars(date('d M, Y', strtotime($appt['appointment_date']))); ?></span>
                    <span class="opacity-50">|</span>
                    <span><?php echo htmlspecialchars(formatTime12hVerification($appt['appointment_time'])); ?></span>
                </div>
            </div>
        </div>

        <div class="p-6 sm:p-8 bg-white relative">
            <div class="text-center mb-8 client-greeting">
                <div class="w-20 h-20 bg-green-50 rounded-full flex items-center justify-center mx-auto mb-5 shadow-sm">
                    <i data-lucide="check" class="w-10 h-10 text-green-500 stroke-[3px]"></i>
                </div>
                
                <h3 class="text-3xl sm:text-4xl font-black text-gray-900 mb-4 leading-tight">
                    Thank You,<br>
                    <span class="text-[var(--color-primary)]"><?php echo $clientFn; ?>!</span>
                </h3>

                <p class="text-gray-600 text-lg font-medium leading-snug px-1">
                    Please confirm the completion of the service.
                </p>
                <p class="text-gray-500 text-base mt-2">
                    Your honest rating helps us reward our team.
                </p>
            </div>

            <div class="flex justify-center items-center gap-2 rating-buttons mb-8">
                <?php for($i=1; $i<=5; $i++): ?>
                    <button type="button" onclick="setRating(<?php echo $i; ?>)" class="star-btn p-1 transition-all hover:scale-110 focus:outline-none text-gray-300" data-value="<?php echo $i; ?>">
                        <i data-lucide="star" class="w-12 h-12 fill-current"></i> </button>
                <?php endfor; ?>
                <input type="hidden" id="rating-input" value="5">
            </div>

            <div class="mb-6 relative">
                <label for="feedback-input" class="block text-sm sm:text-base font-black text-gray-800 uppercase tracking-wide mb-2 ml-1">
                    Comments About The Service
                </label>
                <textarea id="feedback-input" rows="3" class="w-full p-4 border border-gray-200 rounded-xl text-base focus:ring-2 focus:ring-[var(--color-secondary)] focus:border-transparent outline-none resize-none bg-gray-50 transition-all placeholder-gray-400" placeholder="Everything was great..."></textarea>
            </div>

            <button onclick="submitVerification()" id="submit-btn" class="w-full bg-[var(--color-secondary)] text-white py-4 rounded-xl font-black uppercase shadow-lg shadow-[var(--color-secondary)]/30 hover:shadow-xl hover:-translate-y-0.5 active:translate-y-0 transition-all flex justify-center items-center gap-2 text-lg group">
                <i data-lucide="check-circle-2" class="w-6 h-6 group-hover:scale-110 transition-transform"></i> Confirm Service
            </button>
        </div>
    </section>

    <section id="success-view" class="hidden bg-white w-full max-w-sm sm:max-w-md mx-auto rounded-2xl shadow-xl p-10 text-center border-t-8 border-green-500 my-8 animate-[fadeIn_0.5s_ease-out]">
        <div class="w-24 h-24 bg-green-50 rounded-full flex items-center justify-center mx-auto mb-6 animate-pulse">
            <i data-lucide="check-circle" class="w-24 h-24 text-green-600"></i>
        </div>
        <h2 class="text-3xl font-black text-[var(--color-primary)] uppercase mb-3">All Set <?php echo $clientFn; ?>!</h2>
        <p class="text-gray-600 mb-8 text-lg font-black">Thank you for your feedback. We look forward to serving you again.</p>
        <div class="text-xs text-gray-300 uppercase font-bold tracking-widest">You may close this window</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-x" class="w-20 h-20 text-white"></i>
            </div>
            
            <h3 class="text-3xl font-black text-[var(--color-primary)] uppercase mb-2">SERVICE 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();

    <?php if ($view === 'verify'): ?>
    // STAR LOGIC
    function setRating(rating) {
        document.getElementById('rating-input').value = rating;
        const stars = document.querySelectorAll('.star-btn');
        stars.forEach((btn, index) => {
            const btnEl = btn;
            if (index < rating) {
                btnEl.classList.add('text-[var(--color-highlight)]');
                btnEl.classList.remove('text-gray-300');
                btnEl.style.transform = "scale(1.2)";
                setTimeout(() => btnEl.style.transform = "scale(1)", 150);
            } else {
                btnEl.classList.remove('text-[var(--color-highlight)]');
                btnEl.classList.add('text-gray-300');
            }
        });
    }
    // Inicializar 5 estrellas por defecto
    setRating(5);

    // SUBMIT FORM
    async function submitVerification() {
        const formContainer = document.querySelector('.bg-white.w-full.max-w-md'); 
        const btn = document.getElementById('submit-btn');
        const rating = document.getElementById('rating-input').value;
        const feedback = document.getElementById('feedback-input').value;

        // Deshabilitar botón y mostrar carga
        const originalContent = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '<span class="animate-pulse flex items-center gap-2"><div class="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div> Saving...</span>';
        btn.classList.add('opacity-75', 'cursor-not-allowed');

        const data = {
            action: 'verify_service',
            token: '<?php echo htmlspecialchars($token); ?>', 
            csrf_token: '<?php echo htmlspecialchars($csrf_token); ?>', 
            rating: rating,
            feedback: feedback
        };

        try {
            const res = await fetch('db/service-verification-handler.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(data)
            });
            const result = await res.json();
            
            if (result.success) {
                showToast("Confirmation Successful! Thank you for your feedback.", "success");

                // Transición suave
                formContainer.style.opacity = '0';
                formContainer.style.transform = 'scale(0.95)';
                setTimeout(() => {
                    formContainer.style.display = 'none'; 
                    const successView = document.getElementById('success-view');
                    successView.classList.remove('hidden');
                    lucide.createIcons();
                }, 300);
            } else {
                showToast("Error: " + (result.message || 'An unknown error occurred.'), "error");
                resetButton(btn, originalContent);
            }
        } catch (e) {
            console.error(e);
            showToast("Connection error. Please check your internet.", "error");
            resetButton(btn, originalContent);
        }
    }

    function resetButton(btn, originalContent) {
        btn.disabled = false;
        btn.classList.remove('opacity-75', 'cursor-not-allowed');
        btn.innerHTML = originalContent;
        lucide.createIcons();
    }
    <?php endif; ?>
</script>
    <script src="files/toast.js"></script>
</body>
</html>