<?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' => '#'];

// 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'] ?? ''; 

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);
$business_name = htmlspecialchars($ci['company_name'] ?? 'Flow Business LLC');

// Lógica del Servicio
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$service = null;
$gallery_images = [];

try {
    if ($id > 0) {
        // Consulta segura a la tabla 'services'
        $stmt = $pdo->prepare("SELECT * FROM services WHERE id = ? LIMIT 1");
        $stmt->execute([$id]);
        $service = $stmt->fetch(PDO::FETCH_ASSOC);

        // Procesar imágenes de la galería si existen
        if ($service && !empty($service['gallery_images'])) {
            $gallery_images = array_filter(explode(',', $service['gallery_images']));
        }
    }
} catch (PDOException $e) {
    error_log("SERVICE PAGE DB ERROR: " . $e->getMessage());
    $service = null; 
}

// Función de limpieza de texto para títulos (sin HTML)
function clean_plain_text($text) {
    if (!$text) return '';
    return trim(strip_tags(html_entity_decode($text, ENT_QUOTES | ENT_HTML5)));
}

// URL de Reservas
$booking_url = 'booking.php';

// Procesamiento de contenido
$service_name = $service ? clean_plain_text($service['name']) : 'Service Not Found';

// Permitimos HTML en descripción y características porque la base de datos (Rich Text Editor) lo guarda así
$service_description = $service['description'] ? html_entity_decode($service['description']) : 'No description provided.';
$service_features = $service['features'] ? html_entity_decode($service['features']) : '';

// Procesamiento de Video YouTube
$youtube_id = null;
if (!empty($service['youtube_link'])) {
    $trusted_url = filter_var($service['youtube_link'], FILTER_SANITIZE_URL);
    $url_parts = parse_url($trusted_url);
    if (isset($url_parts['query'])) {
        parse_str($url_parts['query'], $query_params);
        // Validación de ID de YouTube (11 caracteres)
        $youtube_id = (isset($query_params['v']) && preg_match('/^[a-zA-Z0-9_-]{11}$/', $query_params['v'])) 
                      ? $query_params['v'] : null;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title><?php echo htmlspecialchars($service_name); ?> - <?php echo htmlspecialchars($ci['business_name'] ?? ''); ?></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>
    
    <style>
        .lightbox {
            display: none;
            position: fixed;
            z-index: 9999;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.95);
            text-align: center;
            padding: 20px;
            overflow: auto;
        }
        .lightbox-content-wrapper {
            position: relative;
            margin: 5% auto;
            max-width: 900px;
            padding: 20px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
        }
        .lightbox-img {
            display: block;
            width: 100%;
            height: auto;
            max-height: 70vh;
            object-fit: contain;
            margin-bottom: 20px;
        }
        .close-btn {
            position: absolute;
            top: -30px;
            right: 0px;
            color: #fff;
            font-size: 40px;
            font-weight: bold;
            transition: 0.3s;
            cursor: pointer;
            line-height: 1;
            padding: 5px 15px;
            background: rgba(0,0,0,0.5);
            border-radius: 4px;
        }
        .prev-btn, .next-btn {
            cursor: pointer;
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            width: auto;
            padding: 16px;
            color: white;
            font-weight: bold;
            font-size: 20px;
            transition: 0.6s ease;
            border-radius: 0 3px 3px 0;
            user-select: none;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 10000;
        }
        .prev-btn { left: 0; border-radius: 3px 0 0 3px; }
        .next-btn { right: 0; border-radius: 3px 0 0 3px; }
        .prev-btn:hover, .next-btn:hover { background-color: rgba(0, 0, 0, 0.8); }

        .video-responsive-container {
            position: relative;
            padding-bottom: 56.25%; 
            height: 0;
            overflow: hidden;
            max-width: 100%;
            margin-bottom: 1rem;
        }
        .video-responsive-container iframe {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }
    </style> 
</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'] ?? '');
            // CORREGIDO: Mensaje específico para la página de servicios
            $wa_message = "Hi! I'm interested in the " . clean_plain_text($service_name) . " service and would like more information.";
            
            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="info" class="w-5 h-5"></i>
                    <p class="text-sm font-black uppercase tracking-wide">Service Offered Page</p>
                </div>
            </div>
            
        </div>
    </header>
    
    <main class="max-w-3xl mx-auto px-4 py-8">
    
    <?php if ($service): ?>
    
        <section class="bg-white rounded-xl shadow-md overflow-hidden w-full border border-gray-100">

            <div class="relative w-full overflow-hidden mb-8">
                <?php if ($youtube_id): ?>
                    <div class="video-responsive-container">
                        <iframe src="https://www.youtube.com/embed/<?php echo htmlspecialchars($youtube_id); ?>" 
                                title="YouTube video player for <?php echo htmlspecialchars($service_name); ?>" frameborder="0" 
                                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 
                                allowfullscreen></iframe>
                    </div>
                <?php elseif (!empty($service['image_path'])): ?>
                    <img src="uploads/services/<?php echo htmlspecialchars($service['image_path']); ?>" 
                         alt="<?php echo htmlspecialchars($service_name); ?>" 
                         class="w-full h-[60vh] min-h-[300px] object-cover">
                <?php else: ?>
                    <div class="flex items-center justify-center w-full h-[60vh] min-h-[300px] text-gray-400 flex-col bg-gray-100">
                        <i data-lucide="video" class="w-16 h-16 mb-4"></i>
                        <span class="text-lg uppercase font-bold">No Media Available</span>
                    </div>
                <?php endif; ?>
            </div>

            <div class="px-4 sm:px-8 py-4 max-w-4xl mx-auto">
                <h1 class="text-4xl font-black text-[var(--color-primary)] uppercase leading-tight mb-4 text-center">
                    <?php echo htmlspecialchars($service_name); ?>
                </h1>
                <div class="w-16 h-1 bg-[var(--color-secondary)] mb-6 rounded-full mx-auto"></div>

                <div class="text-gray-700 text-lg leading-relaxed mb-8 text-center">
                    <?php echo $service_description; ?>
                </div>
                
            </div>

            <?php if (!empty($service_features)): ?>
            <div class="px-4 sm:px-8 py-8 border-t border-gray-100 max-w-4xl mx-auto">
                <h3 class="text-2xl font-black text-[var(--color-primary)] uppercase mb-4 text-center">What's Included:</h3>
                <div class="bg-gray-50 rounded-xl p-6 border border-gray-100">
                    <ul class="space-y-4 list-none">
                        <?php
                        if (strpos($service_features, '<li>') !== false || strpos($service_features, '<p>') !== false || strpos($service_features, '<br>') !== false) {
                            echo $service_features; 
                        } else {
                            $features_array = explode("\n", $service_features);
                            foreach ($features_array as $feature) {
                                $trimmed_feature = clean_plain_text($feature);
                                if (!empty($trimmed_feature)) {
                                    echo '<li class="flex items-start">';
                                    echo '<i data-lucide="check-circle-2" class="w-5 h-5 text-[var(--color-secondary)] mr-3 mt-0.5 flex-shrink-0"></i>';
                                    echo '<span class="text-gray-700 font-medium text-base leading-snug">'.htmlspecialchars($trimmed_feature).'</span>';
                                    echo '</li>';
                                }
                            }
                        }
                        ?>
                    </ul>
                </div>
            </div>
            
            <div class="flex justify-center mb-8">
                    <a href="<?php echo htmlspecialchars($booking_url); ?>"
                       class="group block w-full max-w-md bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-4 px-6 rounded-lg uppercase transition-all shadow-md hover:shadow-lg flex items-center justify-center gap-3 text-lg">
                        <i data-lucide="calendar-check-2" class="w-6 h-6"></i>
                        <span>BOOK YOUR APPOINTMENT NOW</span>
                    </a>
                </div>
                
            <?php endif; ?>
            
            <?php if (!empty($gallery_images)): ?>
            <div class="px-4 sm:px-8 py-8 border-t border-gray-100">
                <h3 class="text-2xl font-black text-[var(--color-primary)] uppercase mb-6 text-center">Service Gallery</h3>
                <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4 max-w-5xl mx-auto">
                    <?php foreach ($gallery_images as $index => $image_name):
                        $cleaned_image_name = htmlspecialchars(trim($image_name)); 
                        $image_path = 'uploads/services/' . $cleaned_image_name;
                    ?>
                        <div class="h-40 overflow-hidden rounded-lg shadow-md cursor-pointer gallery-item" 
                             data-image-url="<?php echo htmlspecialchars($image_path); ?>"
                             data-index="<?php echo $index; ?>">
                            <img src="<?php echo htmlspecialchars($image_path); ?>" 
                                 alt="<?php echo htmlspecialchars($service_name . ' Gallery Image ' . ($index + 1)); ?>" 
                                 class="w-full h-full object-cover transition-transform duration-300 hover:scale-105">
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>

        </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="briefcase" 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($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'; ?>

    <div id="myLightbox" class="lightbox">
        <div class="lightbox-content-wrapper">
            <span class="close-btn">&times;</span>
            <img class="lightbox-img" id="lightbox-img" src="" alt="Gallery Image Large">
            
            <a href="<?php echo htmlspecialchars($booking_url); ?>"
               class="group block w-full max-w-sm mx-auto bg-green-600 hover:bg-green-700 text-white font-black py-3 px-6 rounded-lg uppercase transition-all shadow-md flex items-center justify-center gap-3 text-base">
                <i data-lucide="calendar-check-2" class="w-5 h-5"></i>
                <span>BOOK YOUR APPOINTMENT</span>
            </a>
        </div>

        <a class="prev-btn hidden md:block" id="prevBtn"><i data-lucide="chevron-left"></i></a>
        <a class="next-btn hidden md:block" id="nextBtn"><i data-lucide="chevron-right"></i></a>
    </div>

    <script>
        lucide.createIcons();
        
        const lightbox = document.getElementById('myLightbox');
        const lightboxImg = document.getElementById('lightbox-img');
        const closeBtn = document.querySelector('.close-btn');
        const prevBtn = document.getElementById('prevBtn');
        const nextBtn = document.getElementById('nextBtn');
        const galleryItems = Array.from(document.querySelectorAll('.gallery-item')); 
        let currentImageIndex = 0;
        
        const imageUrls = galleryItems.map(item => item.getAttribute('data-image-url'));

        function openLightbox(index) {
            currentImageIndex = index;
            lightbox.style.display = 'flex'; 
            updateLightboxImage();
        }
        
        function updateLightboxImage() {
            if (imageUrls.length === 0) return;
            
            lightboxImg.src = imageUrls[currentImageIndex];
            
            if (imageUrls.length > 1) {
                 prevBtn.style.display = 'block';
                 nextBtn.style.display = 'block';
            } else {
                 prevBtn.style.display = 'none';
                 nextBtn.style.display = 'none';
            }
        }
        
        function changeSlide(step) {
            currentImageIndex += step;
            if (currentImageIndex < 0) {
                currentImageIndex = imageUrls.length - 1;
            } else if (currentImageIndex >= imageUrls.length) {
                currentImageIndex = 0;
            }
            updateLightboxImage();
        }

        // Event Listeners for Gallery Items
        galleryItems.forEach(item => {
            item.addEventListener('click', function() {
                const index = parseInt(this.getAttribute('data-index'));
                openLightbox(index);
            });
        });

        // Event Listeners for Navigation and Close
        closeBtn.addEventListener('click', () => lightbox.style.display = 'none');
        prevBtn.addEventListener('click', () => changeSlide(-1));
        nextBtn.addEventListener('click', () => changeSlide(1));
        
        // Close Lightbox by clicking outside the content (on the overlay)
        lightbox.addEventListener('click', function(e) {
            if (e.target.classList.contains('lightbox')) {
                lightbox.style.display = 'none';
            }
        });
        
        // Close with ESC key and navigation with arrow keys
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && lightbox.style.display === 'flex') {
                lightbox.style.display = 'none';
            }
            if (lightbox.style.display === 'flex') {
                if (e.key === 'ArrowLeft') {
                    changeSlide(-1);
                } else if (e.key === 'ArrowRight') {
                    changeSlide(1);
                }
            }
        });

    </script>
    <script src="files/toast.js"></script>
</body>
</html>