<?php
include 'header.php';
include 'db.php';

$headerBg = 'bg-black';
if (!isset($_GET['id'])) {
    header('Location: /shop.php');
    exit;
}

$shopId = mysqli_real_escape_string($conn, $_GET['id']);
$query = mysqli_query($conn, "SELECT * FROM shop WHERE id = '$shopId'");
$shop = mysqli_fetch_assoc($query);

if (!$shop) {
    header('Location: /shop.php');
    exit;
}

function parseShopHours($hours, $days) {
    $hoursInfo = [];
    $currentHour = date('H:i');
    $currentDay = date('l');
    
    list($openHour, $closeHour) = explode(' à ', $hours);
    $daysArray = explode(',', $days);
    
    $isMorningOpen = strtotime($openHour) <= strtotime('10:00');
    $isLateOpen = strtotime($closeHour) >= strtotime('20:00');
    $isWeekendOpen = in_array('Saturday', $daysArray) || in_array('Sunday', $daysArray);
    
    $isCurrentlyOpen = in_array($currentDay, $daysArray) && 
                         strtotime($currentHour) >= strtotime($openHour) && 
                         strtotime($currentHour) <= strtotime($closeHour);
    
    $schedule = [];
    $allDays = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
    $dayTranslation = [
        'Monday' => 'Lundi',
        'Tuesday' => 'Mardi',
        'Wednesday' => 'Mercredi',
        'Thursday' => 'Jeudi',
        'Friday' => 'Vendredi',
        'Saturday' => 'Samedi',
        'Sunday' => 'Dimanche'
    ];
    
    foreach ($allDays as $day) {
        if (in_array($day, $daysArray)) {
            $schedule[$dayTranslation[$day]] = [$openHour . ' - ' . $closeHour];
        } else {
            $schedule[$dayTranslation[$day]] = ['Fermé'];
        }
    }
    
    $nextOpen = null;
    if (!$isCurrentlyOpen) {
        $currentDayIndex = array_search($currentDay, $allDays);
        
        if (in_array($currentDay, $daysArray) && strtotime($openHour) > strtotime($currentHour)) {
            $nextOpen = ['day' => $currentDay, 'time' => $openHour];
        } else {
            for ($i = 1; $i <= 7; $i++) {
                $nextDayIndex = ($currentDayIndex + $i) % 7;
                $nextDay = $allDays[$nextDayIndex];
                
                if (in_array($nextDay, $daysArray)) {
                    $nextOpen = ['day' => $nextDay, 'time' => $openHour];
                    break;
                }
            }
        }
    }
    
    return [
        'currently_open' => $isCurrentlyOpen,
        'morning_open' => $isMorningOpen,
        'late_open' => $isLateOpen,
        'weekend_open' => $isWeekendOpen,
        'formatted_schedule' => $schedule,
        'next_open' => $nextOpen
    ];
}

$openingInfo = parseShopHours($shop['hour_open'], $shop['day_open']);
$mainImage = trim(explode(',', trim($shop['url_image'], '()'))[0]);
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($shop['title']) ?> - Vert Chasseur</title>
    <link rel="icon" type="image/png" href="logo_new.png">
    <meta name="description" content="<?= htmlspecialchars(substr($shop['description'], 0, 160)) ?>">
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            darkMode: 'class',
            theme: {
                extend: {}
            }
        }
    </script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Princess+Sofia&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <script src="https://unpkg.com/alpinejs" defer></script>
    <style>
        body {
            font-family: 'Poppins', sans-serif;
            letter-spacing: -0.01em;
        }
        .status-dot {
            animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
        }
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
        .txt-chasseur {
            font-family: "Princess Sofia", serif;
            font-weight: 400;
            font-style: normal;
        }
        .shop-image {
            transition: transform 0.7s ease;
        }
        .shop-image:hover {
            transform: scale(1.05);
        }
    </style>
</head>
<body class="bg-white dark:bg-black text-black dark:text-white transition-colors duration-300" x-data="{ showScheduleDetails: true }">
    <script>
        if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
            document.documentElement.classList.add('dark');
        }
        window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
            if (e.matches) {
                document.documentElement.classList.add('dark');
            } else {
                document.documentElement.classList.remove('dark');
            }
        });
    </script>

    <div class="relative h-[70vh]">
        <img src="<?= htmlspecialchars($mainImage) ?>" alt="<?= htmlspecialchars($shop['title']) ?>" class="w-full h-full object-cover shop-image">
        <div class="absolute inset-0 bg-gradient-to-t from-black/50 to-transparent"></div>
    </div>

    <div class="max-w-7xl mx-auto px-4 -mt-32 relative z-10 pb-20">
        <div class="bg-white dark:bg-black rounded-3xl shadow-xl dark:shadow-gray-900/30 p-8 border border-gray-100 dark:border-gray-800">
            <div class="flex flex-col md:flex-row md:items-start justify-between gap-6 mb-12">
                <div>
                    <h1 class="text-4xl font-light mb-4 text-black dark:text-white"><?= htmlspecialchars($shop['title']) ?></h1>
                    <div class="flex items-center gap-4">
                        <span class="inline-flex items-center px-3 py-1.5 rounded-full text-xs font-medium <?= $openingInfo['currently_open'] ? 'bg-green-500 text-white' : 'bg-red-500 text-white' ?>">
                            <span class="status-dot w-1.5 h-1.5 rounded-full bg-white mr-1.5"></span>
                            <?= $openingInfo['currently_open'] ? 'Ouvert' : 'Fermé' ?>
                        </span>
                        
                        <div class="flex gap-2">
                            <?php if($openingInfo['morning_open']): ?>
                                <span class="px-2 py-1 bg-blue-500/70 text-white backdrop-blur-md rounded-full text-xs border border-blue-400/20">
                                    <i class="fas fa-sun"></i>
                                </span>
                            <?php endif; ?>
                            <?php if($openingInfo['late_open']): ?>
                                <span class="px-2 py-1 bg-indigo-500/70 text-white backdrop-blur-md rounded-full text-xs border border-indigo-400/20">
                                    <i class="fas fa-moon"></i>
                                </span>
                            <?php endif; ?>
                            <?php if($openingInfo['weekend_open']): ?>
                                <span class="px-2 py-1 bg-purple-500/70 text-white backdrop-blur-md rounded-full text-xs border border-purple-400/20">
                                    <i class="fas fa-calendar"></i>
                                </span>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <div class="flex flex-col md:flex-row gap-4">
                    <?php if (!empty($shop['number_phone'])): ?>
                    <a href="tel:<?= htmlspecialchars($shop['number_phone']) ?>" class="flex items-center justify-center gap-3 bg-green-500 text-white px-6 py-3 rounded-xl hover:bg-green-600 transition-all font-medium">
                        <i class="fas fa-phone"></i>
                        <span>Appeler l'enseigne</span>
                    </a>
                    <?php endif; ?>
                    
                    <?php if (!empty($shop['uber_eats_link'])): ?>
                    <a href="<?= htmlspecialchars($shop['uber_eats_link']) ?>" target="_blank" class="flex items-center justify-center gap-3 bg-black text-white dark:bg-white dark:text-black px-6 py-3 rounded-xl hover:bg-gray-800 dark:hover:bg-gray-200 transition-all font-medium">
                        <i class="fas fa-utensils"></i>
                        <span>Commander</span>
                    </a>
                    <?php endif; ?>
                </div>
            </div>

            <div class="grid md:grid-cols-2 gap-12">
                <div class="space-y-8">
                    <div>
                        <h2 class="text-2xl font-medium mb-4 text-black dark:text-white">À propos</h2>
                        <p class="text-gray-600 dark:text-gray-300 leading-relaxed">
                            <?= nl2br(htmlspecialchars($shop['description'])) ?>
                        </p>
                    </div>

                    <?php if (!empty($shop['products'])): ?>
                    <div>
                        <h2 class="text-2xl font-medium mb-4 text-black dark:text-white">Nos produits</h2>
                        <p class="text-gray-600 dark:text-gray-300 leading-relaxed">
                            <?= nl2br(htmlspecialchars($shop['products'])) ?>
                        </p>
                    </div>
                    <?php endif; ?>
                </div>

                <div class="bg-gray-50 dark:bg-gray-900/50 rounded-2xl p-8 space-y-6">
                    <div class="flex items-center gap-4">
                        <div class="bg-gray-100 dark:bg-gray-800 p-4 rounded-full">
                            <i class="fas fa-clock text-gray-500 dark:text-gray-400 text-xl"></i>
                        </div>
                        <h3 class="font-medium text-xl text-black dark:text-white">Horaires d'ouverture</h3>                            
                    </div>
                    
                    <p class="text-xs text-gray-500 dark:text-gray-400">Les horaires peuvent varier. Contactez le commerce pour confirmation.</p>

                    <div class="space-y-4">
                        <div class="bg-white dark:bg-black p-6 rounded-xl shadow-sm border border-gray-100 dark:border-gray-800">
                            <h4 class="font-medium mb-3 flex items-center gap-3 text-black dark:text-white">
                                <i class="fas fa-calendar text-gray-400 dark:text-gray-500"></i>
                                Jours d'ouverture
                            </h4>
                            <p class="text-gray-600 dark:text-gray-300">
                                <?= str_replace(',', ', ', $shop['day_open']) ?>
                            </p>
                        </div>
                        <div class="bg-white dark:bg-black p-6 rounded-xl shadow-sm border border-gray-100 dark:border-gray-800">
                            <h4 class="font-medium mb-3 flex items-center gap-3 text-black dark:text-white">
                                <i class="fas fa-hourglass text-gray-400 dark:text-gray-500"></i>
                                Heures d'ouverture
                            </h4>
                            <p class="text-gray-600 dark:text-gray-300"><?= $shop['hour_open'] ?></p>
                        </div>
                        
                        <button @click="showScheduleDetails = !showScheduleDetails" 
                                class="w-full flex items-center justify-center gap-2 py-2 bg-white dark:bg-black rounded-xl text-sm font-medium text-gray-600 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-900 transition-all border border-gray-100 dark:border-gray-800">
                            <span x-show="!showScheduleDetails">Voir détails</span>
                            <span x-show="showScheduleDetails">Masquer détails</span>
                            <i x-show="!showScheduleDetails" class="fas fa-chevron-down ml-1"></i>
                            <i x-show="showScheduleDetails" class="fas fa-chevron-up ml-1"></i>
                        </button>
                        
                        <div x-show="showScheduleDetails" 
                             x-transition
                             class="p-4 bg-white dark:bg-black rounded-xl text-xs space-y-2 border border-gray-100 dark:border-gray-800">
                            <?php foreach($openingInfo['formatted_schedule'] as $day => $hours): ?>
                            <div class="flex justify-between">
                                <span class="font-medium text-black dark:text-white"><?= $day ?>:</span>
                                <span class="text-gray-600 dark:text-gray-300">
                                    <?php if (count($hours) === 1 && $hours[0] === 'Fermé'): ?>
                                        <span class="text-red-500">Fermé</span>
                                    <?php else: ?>
                                        <?= implode(' & ', $hours) ?>
                                    <?php endif; ?>
                                </span>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    
                    <?php if (!$openingInfo['currently_open'] && isset($openingInfo['next_open'])): ?>
                    <div class="bg-white dark:bg-black p-4 rounded-xl shadow-sm border border-gray-100 dark:border-gray-800 text-sm">
                        <h4 class="font-medium mb-2 flex items-center gap-2 text-black dark:text-white">
                            <i class="fas fa-clock text-gray-400 dark:text-gray-500"></i>
                            Prochaine ouverture
                        </h4>
                        <p class="text-gray-600 dark:text-gray-300">
                        <?php 
                        $dayTranslation = [
                            'Monday' => 'Lundi',
                            'Tuesday' => 'Mardi',
                            'Wednesday' => 'Mercredi',
                            'Thursday' => 'Jeudi',
                            'Friday' => 'Vendredi',
                            'Saturday' => 'Samedi',
                            'Sunday' => 'Dimanche'
                        ];
                        $nextDay = $dayTranslation[$openingInfo['next_open']['day']];
                        $nextTime = $openingInfo['next_open']['time'];
                        
                        if ($openingInfo['next_open']['day'] === date('l')) {
                            echo "Aujourd'hui à " . $nextTime;
                        } else {
                            echo $nextDay . " à " . $nextTime;
                        }
                        ?>
                        </p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <footer class="w-full py-8 mt-16 border-t border-gray-100 dark:border-gray-900">
        <p class="text-xs text-gray-500 dark:text-gray-400 text-center max-w-3xl mx-auto px-4">© 2025 Vert Chasseur · A <a href="https://aktascorp.com" class="underline hover:text-gray-600 dark:hover:text-gray-300">aktascorp</a> member · <a href="https://aktascorp.com/privacy" class="hover:text-gray-600 dark:hover:text-gray-300">Confidentialité</a></p>
    </footer>
</body>
</html>