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

requireLogin();
$user = getConnectedUser($pdo);
requireAdmin($user);

$msg = ''; $error = '';

// ============================================================
// ACTIONS POST
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // --- AJOUTER / MODIFIER ---
    if (isset($_POST['save_event'])) {
        $id          = (int)($_POST['event_id'] ?? 0);
        $title       = trim(htmlspecialchars($_POST['title']       ?? ''));
        $description = trim(htmlspecialchars($_POST['description'] ?? ''));
        $event_date  = $_POST['event_date'] ?? '';
        $location    = trim(htmlspecialchars($_POST['location']    ?? ''));
        $type        = in_array($_POST['type'] ?? '', ['local','sport','artistique']) ? $_POST['type'] : 'local';
        $language    = in_array($_POST['language'] ?? '', ['CA-FR','US-EN']) ? $_POST['language'] : 'CA-FR';
        $importance  = max(1, min(3, (int)($_POST['importance'] ?? 1)));
        $url         = trim(htmlspecialchars($_POST['url']         ?? ''));
        $is_active   = isset($_POST['is_active']) ? 1 : 0;

        if (empty($title) || empty($event_date)) {
            $error = "Le titre et la date sont obligatoires.";
        } else {
            if ($id > 0) {
                $pdo->prepare("UPDATE events SET title=?,description=?,event_date=?,location=?,type=?,language=?,importance=?,url=?,is_active=? WHERE id=?")
                    ->execute([$title,$description,$event_date,$location,$type,$language,$importance,$url,$is_active,$id]);
                $msg = "Événement #{$id} mis à jour !";
            } else {
                $pdo->prepare("INSERT INTO events (title,description,event_date,location,type,language,importance,url,is_active) VALUES (?,?,?,?,?,?,?,?,?)")
                    ->execute([$title,$description,$event_date,$location,$type,$language,$importance,$url,$is_active]);
                $msg = "Événement ajouté !";
            }
        }
    }

    // --- SUPPRIMER ---
    if (isset($_POST['delete_event'])) {
        $id = (int)$_POST['event_id'];
        $pdo->prepare("DELETE FROM events WHERE id=?")->execute([$id]);
        $msg = "Événement #{$id} supprimé.";
    }

    // --- TOGGLE ACTIF ---
    if (isset($_POST['toggle_event'])) {
        $id  = (int)$_POST['event_id'];
        $val = (int)$_POST['new_active'];
        $pdo->prepare("UPDATE events SET is_active=? WHERE id=?")->execute([$val,$id]);
        $msg = "Statut mis à jour.";
    }

    // --- IMPORT CSV / XLS ---
    if (isset($_POST['import_file']) && isset($_FILES['import'])) {
        $file = $_FILES['import'];
        $ext  = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $rows = [];

        if ($ext === 'csv') {
            // Lire le CSV
            $handle = fopen($file['tmp_name'], 'r');
            $header = null;
            while (($line = fgetcsv($handle, 0, ',')) !== false) {
                if (!$header) { $header = array_map('strtolower', array_map('trim', $line)); continue; }
                $rows[] = array_combine($header, $line);
            }
            fclose($handle);

        } elseif (in_array($ext, ['xls','xlsx'])) {
            // Lire XLS/XLSX avec PhpSpreadsheet si disponible, sinon message
            if (class_exists('\PhpOffice\PhpSpreadsheet\IOFactory')) {
                $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file['tmp_name']);
                $sheet       = $spreadsheet->getActiveSheet()->toArray(null, true, true, false);
                $header      = array_map('strtolower', array_map('trim', $sheet[0]));
                array_shift($sheet);
                foreach ($sheet as $row) {
                    if (empty(array_filter($row))) continue;
                    $rows[] = array_combine($header, $row);
                }
            } else {
                $error = "PhpSpreadsheet non installé. Utilise un fichier CSV à la place.";
            }
        } else {
            $error = "Format non supporté. Utilise CSV, XLS ou XLSX.";
        }

        if (!$error && !empty($rows)) {
            $inserted = 0;
            foreach ($rows as $row) {
                $title      = trim($row['title']       ?? $row['titre']       ?? '');
                $desc       = trim($row['description'] ?? '');
                $evdate     = trim($row['event_date']  ?? $row['date']        ?? '');
                $loc        = trim($row['location']    ?? $row['lieu']        ?? '');
                $type       = in_array(trim($row['type'] ?? ''), ['local','sport','artistique']) ? trim($row['type']) : 'local';
                $lang       = in_array(trim($row['language'] ?? ''), ['CA-FR','US-EN']) ? trim($row['language']) : 'CA-FR';
                $imp        = max(1, min(3, (int)($row['importance'] ?? 1)));
                $url        = trim($row['url']         ?? '');
                $active     = (int)($row['is_active']  ?? 1);

                if (empty($title) || empty($evdate)) continue;

                $pdo->prepare("INSERT INTO events (title,description,event_date,location,type,language,importance,url,is_active) VALUES (?,?,?,?,?,?,?,?,?)")
                    ->execute([$title,$desc,$evdate,$loc,$type,$lang,$imp,$url,$active]);
                $inserted++;
            }
            $msg = "{$inserted} événement(s) importé(s) avec succès !";
        }
    }
}

// Charger tous les événements
$events = $pdo->query("SELECT * FROM events ORDER BY event_date ASC")->fetchAll();

// Événement à éditer ?
$editEvent = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM events WHERE id=?");
    $stmt->execute([(int)$_GET['edit']]);
    $editEvent = $stmt->fetch();
}

include 'header.php';
?>

<div class="container-fluid mt-4 px-4">
    <a href="admin.php" class="btn btn-outline-secondary btn-sm mb-3">&larr; Admin</a>
    <h5 class="oracle-text text-warning mb-3"> GESTION DES ÉVÉNEMENTS</h5>

    <?php if ($msg):   ?><div class="alert alert-success small py-2"><?= $msg ?></div><?php endif; ?>
    <?php if ($error): ?><div class="alert alert-danger  small py-2"><?= $error ?></div><?php endif; ?>

    <div class="row g-4">

        <!-- FORMULAIRE AJOUTER / MODIFIER -->
        <div class="col-md-5">
            <div class="card bg-dark border-<?= $editEvent ? 'warning' : 'success' ?> shadow">
                <div class="card-header py-2 fw-bold small text-<?= $editEvent ? 'warning' : 'success' ?>">
                    <?= $editEvent ? '✏️ MODIFIER — ' . htmlspecialchars($editEvent['title']) : '➕ NOUVEL ÉVÉNEMENT' ?>
                </div>
                <div class="card-body">
                    <form method="POST">
                        <input type="hidden" name="event_id" value="<?= $editEvent['id'] ?? 0 ?>">
                        <div class="mb-2">
                            <label class="small text-white d-block mb-1">Titre *</label>
                            <input type="text" name="title" class="form-control form-control-sm"
                                   value="<?= htmlspecialchars($editEvent['title'] ?? '') ?>" required maxlength="255">
                        </div>
                        <div class="mb-2">
                            <label class="small text-white d-block mb-1">Description</label>
                            <textarea name="description" class="form-control form-control-sm" rows="2"><?= htmlspecialchars($editEvent['description'] ?? '') ?></textarea>
                        </div>
                        <div class="row g-2 mb-2">
                            <div class="col-7">
                                <label class="small text-white d-block mb-1">Date & heure *</label>
                                <input type="datetime-local" name="event_date" class="form-control form-control-sm"
                                       value="<?= !empty($editEvent['event_date']) ? date('Y-m-d\TH:i', strtotime($editEvent['event_date'])) : '' ?>" required>
                            </div>
                            <div class="col-5">
                                <label class="small text-white d-block mb-1">Importance</label>
                                <select name="importance" class="form-select form-select-sm">
                                    <option value="1" <?= ($editEvent['importance']??1)==1?'selected':'' ?>>1 — Normal</option>
                                    <option value="2" <?= ($editEvent['importance']??1)==2?'selected':'' ?>>2 — Important</option>
                                    <option value="3" <?= ($editEvent['importance']??1)==3?'selected':'' ?>>3 — ★ Prioritaire</option>
                                </select>
                            </div>
                        </div>
                        <div class="mb-2">
                            <label class="small text-white d-block mb-1">Lieu</label>
                            <input type="text" name="location" class="form-control form-control-sm"
                                   value="<?= htmlspecialchars($editEvent['location'] ?? '') ?>" maxlength="255">
                        </div>
                        <div class="row g-2 mb-2">
                            <div class="col-5">
                                <label class="small text-white d-block mb-1">Type</label>
                                <select name="type" class="form-select form-select-sm">
                                    <option value="local"      <?= ($editEvent['type']??'')==='local'?'selected':'' ?>> Local</option>
                                    <option value="sport"      <?= ($editEvent['type']??'')==='sport'?'selected':'' ?>> Sport</option>
                                    <option value="artistique" <?= ($editEvent['type']??'')==='artistique'?'selected':'' ?>> Artistique</option>
                                </select>
                            </div>
                            <div class="col-4">
                                <label class="small text-white d-block mb-1">Langue</label>
                                <select name="language" class="form-select form-select-sm">
                                    <option value="CA-FR" <?= ($editEvent['language']??'CA-FR')==='CA-FR'?'selected':'' ?>> CA-FR</option>
                                    <option value="US-EN" <?= ($editEvent['language']??'')==='US-EN'?'selected':'' ?>> US-EN</option>
                                </select>
                            </div>
                            <div class="col-3 d-flex align-items-end">
                                <div class="form-check mb-1">
                                    <input class="form-check-input" type="checkbox" name="is_active" id="activeChk"
                                           <?= ($editEvent['is_active'] ?? 1) ? 'checked' : '' ?>>
                                    <label class="form-check-label small text-success" for="activeChk">Actif</label>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="small text-white d-block mb-1">URL (optionnel)</label>
                            <input type="url" name="url" class="form-control form-control-sm"
                                   placeholder="https://..." value="<?= htmlspecialchars($editEvent['url'] ?? '') ?>">
                        </div>
                        <div class="d-flex gap-2">
                            <button type="submit" name="save_event" class="btn btn-<?= $editEvent ? 'warning' : 'success' ?> btn-sm fw-bold flex-grow-1">
                                <?= $editEvent ? ' ENREGISTRER' : '➕ AJOUTER' ?>
                            </button>
                            <?php if ($editEvent): ?>
                                <a href="admin_events.php" class="btn btn-outline-secondary btn-sm">Annuler</a>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
            </div>

            <!-- IMPORT CSV / XLS -->
            <div class="card bg-dark border-info shadow mt-3">
                <div class="card-header py-2 fw-bold small text-info"> IMPORTER UNE LISTE (CSV / XLS)</div>
                <div class="card-body">
                    <p class="text-muted small mb-2">
                        Le fichier doit avoir ces colonnes (en-tête obligatoire) :<br>
                        <code class="text-info" style="font-size:0.65rem;">title, description, event_date, location, type, language, importance, url, is_active</code><br>
                        <span style="font-size:0.65rem;">event_date format : <code>2026-06-15 20:00:00</code> | type : local/sport/artistique | importance : 1,2,3</span>
                    </p>
                    <form method="POST" enctype="multipart/form-data">
                        <div class="input-group input-group-sm">
                            <input type="file" name="import" class="form-control" accept=".csv,.xls,.xlsx" required>
                            <button type="submit" name="import_file" class="btn btn-info fw-bold">IMPORTER</button>
                        </div>
                    </form>

                    <!-- Télécharger un modèle CSV -->
                    <div class="mt-2 text-end">
                        <a href="admin_events_template.php" class="text-muted small text-decoration-none">
                            ⬇️ Télécharger un modèle CSV
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- LISTE DES ÉVÉNEMENTS -->
        <div class="col-md-7">
            <div class="card bg-dark border-secondary shadow">
                <div class="card-header bg-secondary text-white py-2 fw-bold small d-flex justify-content-between">
                    <span> LISTE (<?= count($events) ?>)</span>
                    <div class="d-flex gap-2">
                        <a href="?filter=active"   class="text-success small text-decoration-none">Actifs</a>
                        <a href="?filter=inactive" class="text-muted small text-decoration-none">Inactifs</a>
                        <a href="admin_events.php"  class="text-info small text-decoration-none">Tous</a>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table table-dark table-hover table-sm small mb-0">
                        <thead>
                            <tr>
                                <th style="width:30px;">#</th>
                                <th>Titre</th>
                                <th class="text-center">Date</th>
                                <th class="text-center">Type</th>
                                <th class="text-center">Imp.</th>
                                <th class="text-center">Lang</th>
                                <th class="text-center">Actif</th>
                                <th class="text-center">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if (empty($events)): ?>
                            <tr><td colspan="8" class="text-center text-muted py-3">Aucun événement. Ajoutes-en un !</td></tr>
                        <?php endif; ?>
                        <?php foreach ($events as $ev):
                            $isPast = strtotime($ev['event_date']) < time();
                        ?>
                        <tr class="<?= $isPast ? 'opacity-50' : '' ?>">
                            <td class="text-muted"><?= $ev['id'] ?></td>
                            <td>
                                <strong class="<?= $ev['is_active'] ? 'text-white' : 'text-muted' ?>"><?= htmlspecialchars(mb_substr($ev['title'],0,30)) ?><?= strlen($ev['title'])>30?'…':'' ?></strong>
                                <?php if (!empty($ev['url'])): ?>
                                    <a href="<?= htmlspecialchars($ev['url']) ?>" target="_blank" class="text-info ms-1" style="font-size:0.6rem;"></a>
                                <?php endif; ?>
                            </td>
                            <td class="text-center text-muted" style="font-size:0.65rem;white-space:nowrap;">
                                <?= date('d M Y', strtotime($ev['event_date'])) ?><br>
                                <span style="font-size:0.6rem;"><?= date('H:i', strtotime($ev['event_date'])) ?></span>
                            </td>
                            <td class="text-center" style="font-size:0.75rem;">
                                <?= match($ev['type']) { 'sport'=>'', 'artistique'=>'', default=>'' } ?>
                            </td>
                            <td class="text-center">
                                <span class="badge <?= match((int)$ev['importance']) { 3=>'bg-warning text-dark', 2=>'bg-info text-dark', default=>'bg-secondary' } ?>" style="font-size:0.55rem;">
                                    <?= $ev['importance'] ?>★
                                </span>
                            </td>
                            <td class="text-center" style="font-size:0.65rem;"><?= $ev['language'] ?></td>
                            <td class="text-center">
                                <form method="POST" class="d-inline">
                                    <input type="hidden" name="event_id" value="<?= $ev['id'] ?>">
                                    <input type="hidden" name="new_active" value="<?= $ev['is_active']?0:1 ?>">
                                    <button type="submit" name="toggle_event"
                                            class="btn btn-xs py-0 <?= $ev['is_active']?'btn-success':'btn-outline-secondary' ?>">
                                        <?= $ev['is_active']?'✓':'✗' ?>
                                    </button>
                                </form>
                            </td>
                            <td class="text-center">
                                <a href="?edit=<?= $ev['id'] ?>" class="btn btn-xs btn-outline-warning py-0">✏️</a>
                                <form method="POST" class="d-inline">
                                    <input type="hidden" name="event_id" value="<?= $ev['id'] ?>">
                                    <button type="submit" name="delete_event" class="btn btn-xs btn-outline-danger py-0"
                                            onclick="return confirm('Supprimer cet événement ?')">X️</button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>
