<?php
session_start();
require_once 'config.php';
require_once 'functions.php';

header('Content-Type: text/html; charset=UTF-8');

$view  = $_GET['view'] ?? 'list';
$lang  = $_SESSION['lang'] ?? 'CA-FR';
$limit = 15;

try {
    $stmt = $pdo->prepare("SELECT * FROM events WHERE is_active=1 AND event_date >= NOW() ORDER BY event_date ASC LIMIT ?");
    $stmt->execute([$limit]);
    $events = $stmt->fetchAll();
} catch (Exception $e) {
    $events = [];
}

$typeColors = ['local'=>'#0dcaf0','sport'=>'#ffc107','artistique'=>'#a78bfa'];
$typeIcons  = ['local'=>'📍','sport'=>'⚽','artistique'=>'🎭'];

$moisFr = ['01'=>'Janvier','02'=>'Février','03'=>'Mars','04'=>'Avril','05'=>'Mai','06'=>'Juin',
           '07'=>'Juillet','08'=>'Août','09'=>'Septembre','10'=>'Octobre','11'=>'Novembre','12'=>'Décembre'];

if ($view === 'cal') {
    $byMonth = [];
    foreach ($events as $ev) {
        $mkey = date('Y-m', strtotime($ev['event_date']));
        $byMonth[$mkey][] = $ev;
    }
    if (empty($byMonth)) {
        echo '<div style="text-align:center;padding:20px;color:#999;font-size:0.72rem;">Aucun événement à venir.</div>';
    } else {
        foreach ($byMonth as $mkey => $evs) {
            $parts = explode('-', $mkey);
            $mLabel = ($moisFr[$parts[1]] ?? $parts[1]) . ' ' . $parts[0];
            echo '<div style="font-size:0.6rem;color:#0dcaf0;font-weight:700;letter-spacing:1px;padding:6px 0 4px;border-bottom:1px solid #1a1a2a;margin-bottom:6px;">'.strtoupper($mLabel).'</div>';
            foreach ($evs as $ev) {
                $col  = $typeColors[$ev['type']] ?? '#aaa';
                $day  = date('d', strtotime($ev['event_date']));
                $time = date('H:i', strtotime($ev['event_date']));
                $safe = htmlspecialchars($ev['title'], ENT_QUOTES);
                echo '<div style="display:flex;align-items:flex-start;gap:8px;padding:5px 0;border-bottom:1px solid #0d0d1a;">';
                echo '<div style="width:32px;text-align:center;flex-shrink:0;">';
                echo '<div style="font-size:1rem;font-weight:700;color:'.$col.';line-height:1;">'.$day.'</div>';
                echo '<div style="font-size:0.5rem;color:#777;">'.$time.'</div></div>';
                echo '<div style="flex:1;min-width:0;">';
                echo '<div style="font-size:0.7rem;font-weight:600;color:#ddd;">'.$safe.'</div>';
                if (!empty($ev['location'])) echo '<div style="font-size:0.55rem;color:#888;">'.htmlspecialchars($ev['location']).'</div>';
                // Bouton +Gage dans le calendrier aussi
                echo '<button onclick="gageRapide(\''.addslashes($safe).'\');"
                    style="margin-top:3px;background:rgba(255,193,7,0.15);border:1px solid #ffc107;color:#ffc107;border-radius:4px;padding:1px 6px;font-size:0.52rem;cursor:pointer;">+ Gage</button>';
                echo '</div></div>';
            }
            echo '<div style="margin-bottom:10px;"></div>';
        }
    }
} else {
    if (empty($events)) {
        echo '<div style="text-align:center;padding:20px;color:#999;font-size:0.72rem;">Aucun événement à venir.</div>';
    } else {
        foreach ($events as $ev) {
            $col  = $typeColors[$ev['type']] ?? '#aaa';
            $ico  = $typeIcons[$ev['type']] ?? '📌';
            $date = date('d M', strtotime($ev['event_date']));
            $time = date('H:i', strtotime($ev['event_date']));
            $imp  = (int)($ev['importance'] ?? 1);
            $safe = htmlspecialchars($ev['title'], ENT_QUOTES);

            echo '<div style="background:#080810;border:1px solid #1a1a2a;border-left:3px solid '.$col.';border-radius:0 5px 5px 0;padding:7px 10px;margin-bottom:5px;">';
            echo '<div style="display:flex;align-items:center;gap:6px;margin-bottom:2px;">';
            echo '<span style="font-size:0.65rem;font-weight:700;color:'.$col.';">'.$date.'</span>';
            echo '<span style="font-size:0.5rem;color:#666;">'.$time.'</span>';
            if ($imp >= 3) echo '<span style="font-size:0.5rem;background:rgba(220,53,69,0.2);color:#dc3545;border:1px solid #dc3545;border-radius:3px;padding:0 4px;margin-left:auto;">IMPORTANT</span>';
            echo '</div>';
            echo '<div style="font-size:0.72rem;font-weight:600;color:#ddd;">'.$ico.' '.$safe.'</div>';
            if (!empty($ev['description'])) {
                $desc = htmlspecialchars(substr($ev['description'],0,80));
                echo '<div style="font-size:0.6rem;color:#888;margin-top:2px;">'.$desc.(strlen($ev['description'])>80?'…':'').'</div>';
            }
            if (!empty($ev['location'])) echo '<div style="font-size:0.58rem;color:#666;margin-top:1px;">📍 '.htmlspecialchars($ev['location']).'</div>';
            if (!empty($ev['url'])) echo '<a href="'.htmlspecialchars($ev['url']).'" target="_blank" style="font-size:0.58rem;color:#0dcaf0;display:block;margin-top:2px;">En savoir plus →</a>';

            // Bouton +Gage avec quotes correctement échappées
            echo '<button onclick="gageRapide(\''.addslashes($safe).'\');"
                style="margin-top:5px;background:rgba(255,193,7,0.15);border:1px solid #ffc107;color:#ffc107;border-radius:4px;padding:2px 10px;font-size:0.58rem;cursor:pointer;display:block;">
                + Créer un gage sur cet événement</button>';
            echo '</div>';
        }
    }
}