<?php
// Inclure la configuration
require_once 'includes/config.php';

// Vérifier si le mode compte à rebours est activé
if (defined('COUNTDOWN_ENABLED') && COUNTDOWN_ENABLED === true) {
    // Rediriger vers la page de compte à rebours
    require_once 'countdown.php';
    exit;
}

// Inclure les fonctions de données structurées
require_once 'includes/structured-data.php';
// Appliquer les en-têtes de sécurité
setSecurityHeaders();

// Vérifier s'il y a un direct en cours
$liveStream = getLiveStream();
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Direct - <?php echo SITE_NAME; ?></title>
    <meta name="description" content="Suivez nos diffusions en direct sur <?php echo SITE_NAME; ?>. Contenu en temps réel, discussions et événements exclusifs.">
    <link rel="canonical" href="<?php echo getBaseUrl(); ?>/direct.php">
    <link rel="stylesheet" href="css/styles.css?v=<?php echo filemtime('css/styles.css'); ?>">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css">
    
    <!-- Favicons -->
    <link rel="apple-touch-icon" sizes="180x180" href="img/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="img/favicon-16x16.png">
    <link rel="manifest" href="site.webmanifest">
    <link rel="icon" type="image/x-icon" href="img/favicon.ico">
    <meta name="theme-color" content="#FF0000">
    
    <!-- Open Graph Meta Tags -->
    <meta property="og:title" content="Direct - <?php echo SITE_NAME; ?>">
    <meta property="og:description" content="Suivez nos diffusions en direct sur <?php echo SITE_NAME; ?>. Contenu en temps réel, discussions et événements exclusifs.">
    <meta property="og:image" content="<?php echo getBaseUrl(); ?>/img/logo.png">
    <meta property="og:url" content="<?php echo getBaseUrl(); ?>/direct.php">
    <meta property="og:type" content="website">
    <meta property="og:site_name" content="<?php echo SITE_NAME; ?>">
    <meta property="og:locale" content="fr_FR">

    <!-- Twitter Card Meta Tags -->
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:title" content="Direct - <?php echo SITE_NAME; ?>">
    <meta name="twitter:description" content="Suivez nos diffusions en direct sur <?php echo SITE_NAME; ?>. Contenu en temps réel, discussions et événements exclusifs.">
    <meta name="twitter:image" content="<?php echo getBaseUrl(); ?>/img/logo.png">
    
    <!-- Données structurées JSON-LD pour la page direct -->
    <script type="application/ld+json" nonce="<?php echo getCspNonce(); ?>">
    {
        "@context": "https://schema.org",
        "@type": "WebPage",
        "name": "Direct - <?php echo SITE_NAME; ?>",
        "description": "Suivez nos diffusions en direct sur <?php echo SITE_NAME; ?>. Contenu en temps réel.",
        "url": "<?php echo getBaseUrl(); ?>/direct.php",
        "isPartOf": {
            "@type": "WebSite",
            "name": "<?php echo SITE_NAME; ?>",
            "url": "<?php echo getBaseUrl(); ?>"
        },
        "publisher": {
            "@type": "Organization",
            "name": "<?php echo ORGANIZATION_NAME; ?>",
            "url": "<?php echo getBaseUrl(); ?>",
            "logo": {
                "@type": "ImageObject",
                "url": "<?php echo getBaseUrl(); ?>/img/logo.png"
            }
        }
    }
    </script>
    
    <?php
    // Générer les fils d'Ariane pour la page direct
    $breadcrumbs = [
        ['name' => 'Accueil', 'url' => getBaseUrl()],
        ['name' => 'Direct', 'url' => getBaseUrl() . '/direct.php']
    ];
    $breadcrumbJsonLd = generateBreadcrumbJsonLd($breadcrumbs);
    outputJsonLd($breadcrumbJsonLd);
    ?>
    
    <!-- Script pour éviter le flash en mode sombre -->
    <script nonce="<?php echo getCspNonce(); ?>">
        (function() {
            const savedTheme = localStorage.getItem('theme');
            const systemPrefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
            const shouldUseDark = savedTheme === 'dark' || (!savedTheme && systemPrefersDark);
            
            if (shouldUseDark) {
                document.documentElement.setAttribute('data-theme', 'dark');
            }
        })();
    </script>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>
    <!-- Contenu principal -->
    <div class="main-content">
        <?php include 'includes/header.php'; ?>
        
        <!-- Section Direct -->
        <div class="live-page">
            <div class="section-header">
                <div class="section-logo">
                    <img src="img/logo.png" alt="<?php echo SITE_NAME; ?>">
                </div>
                <h2 class="section-title">Diffusion en direct</h2>
            </div>
            
            <div class="live-container">
                <?php 
                // Vérifier s'il y a un direct en cours
                $liveStream = getLiveStream();
                
                if ($liveStream) {
                    // Afficher le direct en cours
                    ?>
                    <div class="live-badge large">
                        <i class="fas fa-circle"></i> EN DIRECT
                    </div>
                    <div class="live-player">
                        <iframe 
                            src="<?php echo PEERTUBE_URL; ?>/videos/embed/<?php echo $liveStream['id']; ?>?autoplay=1" 
                            frameborder="0" 
                            allowfullscreen="allowfullscreen"
                            allow="autoplay; fullscreen"
                            title="<?php echo htmlspecialchars($liveStream['title']); ?>">
                        </iframe>
                    </div>
                    <div class="live-info">
                        <h1 class="live-title"><?php echo htmlspecialchars($liveStream['title']); ?></h1>
                        <div class="live-channel-info">
                            <?php if (strpos($liveStream['channelAvatar'], 'default-avatar.png') !== false || empty($liveStream['channelAvatar'])): ?>
                                <div class="channel-avatar-placeholder">
                                    <i class="fas fa-user-circle"></i>
                                </div>
                            <?php else: ?>
                                <img src="<?php echo $liveStream['channelAvatar']; ?>" alt="<?php echo $liveStream['channel']; ?>" class="channel-avatar">
                            <?php endif; ?>
                            <span class="channel-name"><?php echo $liveStream['channel']; ?></span>
                        </div>
                        <?php if (!empty($liveStream['description'])): ?>
                        <div class="live-description">
                            <?php echo markdown_to_html($liveStream['description']); ?>
                        </div>
                        <?php endif; ?>
                    </div>
                <?php
                } else {
                    // Aucun direct en cours - vérifier s'il y a une annonce configurée
                    $showNextLiveAnnouncement = defined('NEXT_LIVE_ENABLED') && NEXT_LIVE_ENABLED === true;

                    if ($showNextLiveAnnouncement) {
                        // Afficher l'annonce du prochain live
                        // Définir l'image de fond si disponible
                        $bgImageStyle = '';
                        if (!empty(NEXT_LIVE_IMAGE) && file_exists(NEXT_LIVE_IMAGE)) {
                            $bgImageStyle = 'background-image: url(\'' . htmlspecialchars(NEXT_LIVE_IMAGE) . '\');';
                        }
                        ?>
                        <div class="next-live-announcement" style="<?php echo $bgImageStyle; ?>" nonce="<?php echo getCspNonce(); ?>">
                            <?php if (!empty(NEXT_LIVE_IMAGE) && file_exists(NEXT_LIVE_IMAGE)): ?>
                                <div class="next-live-image-container">
                                    <img src="<?php echo htmlspecialchars(NEXT_LIVE_IMAGE); ?>"
                                         alt="<?php echo htmlspecialchars(NEXT_LIVE_TITLE); ?>"
                                         class="next-live-image">
                                </div>
                            <?php endif; ?>
                            <div class="next-live-content">
                                <i class="fas fa-calendar-alt"></i>
                                <?php
                                if (!empty(NEXT_LIVE_DATE)) {
                                    $liveDate = new DateTime(NEXT_LIVE_DATE, new DateTimeZone(DEFAULT_TIMEZONE));
                                    $dayFormatter = new IntlDateFormatter(
                                        'fr_FR',
                                        IntlDateFormatter::FULL,
                                        IntlDateFormatter::NONE,
                                        DEFAULT_TIMEZONE,
                                        IntlDateFormatter::GREGORIAN,
                                        'EEEE d MMMM'
                                    );
                                    $formattedDay = $dayFormatter->format($liveDate);
                                    $formattedDay = ucfirst($formattedDay);
                                    $dynamicTitle = NEXT_LIVE_TITLE . ' - ' . $formattedDay;
                                } else {
                                    $dynamicTitle = NEXT_LIVE_TITLE;
                                }
                                ?>
                                <h1><?php echo htmlspecialchars($dynamicTitle); ?></h1>
                                <?php
                                if (!empty(NEXT_LIVE_DATE)) {
                                    $liveHour = $liveDate->format('H\hi');
                                    $dynamicDescription = 'Rejoignez-nous à ' . $liveHour . '. ' . NEXT_LIVE_DESCRIPTION;
                                } else {
                                    $dynamicDescription = NEXT_LIVE_DESCRIPTION;
                                }
                                ?>
                                <p><?php echo nl2br(htmlspecialchars($dynamicDescription)); ?></p>
                                <?php if (!empty(NEXT_LIVE_DATE)): ?>
                                    <div class="next-live-datetime">
                                        <p class="next-live-date">
                                            <i class="fas fa-clock"></i>
                                            <?php
                                            $formatter = new IntlDateFormatter(
                                                'fr_FR',
                                                IntlDateFormatter::FULL,
                                                IntlDateFormatter::SHORT,
                                                DEFAULT_TIMEZONE
                                            );
                                            echo $formatter->format($liveDate);

                                            $offset = $liveDate->format('P');
                                            echo ' <span class="utc-offset">(UTC' . $offset . ')</span>';
                                            ?>
                                        </p>

                                        <!-- Autres fuseaux horaires -->
                                        <div class="next-live-timezones">
                                            <?php
                                            // Ordre croissant : du plus en retard au plus en avance
                                            $timezones = [
                                                'Ma\'ohi Nui' => 'Pacific/Tahiti',
                                                'Martinique / Guadeloupe' => 'America/Martinique',
                                                'Guyane' => 'America/Cayenne',
                                                'France' => 'Europe/Paris',
                                                'Kanaky' => 'Pacific/Noumea'
                                            ];

                                            foreach($timezones as $name => $timezone):
                                                $liveDateLocal = clone $liveDate;
                                                $liveDateLocal->setTimezone(new DateTimeZone($timezone));

                                                // Vérifier si c'est un jour différent
                                                $dayDiff = $liveDateLocal->format('j') - $liveDate->format('j');

                                                $dayIndicator = '';
                                                if ($dayDiff > 0) {
                                                    $dayIndicator = ' <span class="day-shift">+1j</span>';
                                                } elseif ($dayDiff < 0) {
                                                    $dayIndicator = ' <span class="day-shift">-1j</span>';
                                                }
                                            ?>
                                                <span class="timezone-item">
                                                    <strong><?php echo $name; ?> :</strong> <?php echo $liveDateLocal->format('H\hi'); ?><?php echo $dayIndicator; ?>
                                                </span>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                <?php endif; ?>
                                <a href="index.php" class="btn-primary">Retour à l'accueil</a>
                            </div>
                        </div>
                    <?php
                    } else {
                        ?>
                        <div class="no-live-message">
                            <i class="fas fa-tv"></i>
                            <h1>Aucun direct en cours</h1>
                            <p>Revenez plus tard pour découvrir nos prochaines diffusions en direct.</p>
                            <a href="index.php" class="btn-primary">Retour à l'accueil</a>
                        </div>
                    <?php
                    }
                }
                ?>
            </div>
        </div>
    </div>
    <?php include 'includes/footer.php'; ?>
    <?php include 'includes/mobile-menu.php'; ?>
    <script src="js/main.js"></script>
    <script src="js/pwa-update.js?v=<?php echo filemtime('js/pwa-update.js'); ?>"></script>
</body>
</html> 