<?php
session_start();
require_once 'config.php';
require_once 'functions.php';
requireLogin();
$user = getConnectedUser($pdo);
requireAdmin($user);

// Créer table
try { $pdo->exec("CREATE TABLE IF NOT EXISTS admin_notes (
    id INT AUTO_INCREMENT PRIMARY KEY,
    contenu TEXT NOT NULL,
    categorie VARCHAR(50) DEFAULT 'general',
    priorite ENUM('haute','normale','basse') DEFAULT 'normale',
    statut ENUM('todo','en_cours','fait') DEFAULT 'todo',
    auteur_id INT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)"); } catch(Exception $e) {}

if ($_SERVER['REQUEST_METHOD']==='POST') {
    if (isset($_POST['add_note'])) {
        $contenu = trim(htmlspecialchars($_POST['contenu']??''));
        $prio    = in_array($_POST['priorite']??'', ['haute','normale','basse']) ? $_POST['priorite'] : 'normale';
        $cat     = trim(htmlspecialchars($_POST['categorie']??'general'));
        if ($contenu) $pdo->prepare("INSERT INTO admin_notes (contenu,categorie,priorite,auteur_id) VALUES (?,?,?,?)")->execute([$contenu,$cat,$prio,$user['id']]);
    }
    if (isset($_POST['update_statut'])) {
        $pdo->prepare("UPDATE admin_notes SET statut=? WHERE id=?")->execute([$_POST['statut'],(int)$_POST['nid']]);
    }
    if (isset($_POST['delete_note'])) {
        $pdo->prepare("DELETE FROM admin_notes WHERE id=?")->execute([(int)$_POST['nid']]);
    }
    header("Location: admin_notes.php"); exit;
}

$notes = $pdo->query("SELECT n.*, u.username FROM admin_notes n LEFT JOIN users u ON u.id=n.auteur_id ORDER BY FIELD(statut,'todo','en_cours','fait'), FIELD(priorite,'haute','normale','basse'), n.created_at DESC")->fetchAll();

$prioColors = ['haute'=>'#dc3545','normale'=>'#ffc107','basse'=>'#6c757d'];
$statutColors = ['todo'=>'#dc3545','en_cours'=>'#ffc107','fait'=>'#28a745'];
$statutLabels = ['todo'=>'À faire','en_cours'=>'En cours','fait'=>'✓ Fait'];

// Tâches pré-remplies pour l'ouverture
$defaultTasks = [
    ['Configurer SMTP pour envoi des courriels', 'technique', 'haute'],
    ['Vérifier que tous les grades sont bien configurés dans admin_limites', 'admin', 'haute'],
    ['Créer le cercle officiel de lancement', 'lancement', 'haute'],
    ['Tester le système de gage de bout en bout', 'test', 'haute'],
    ['Configurer la marquise défilante pour l\'ouverture', 'contenu', 'normale'],
    ['Ajouter les premiers événements dans le calendrier', 'contenu', 'normale'],
    ['Tester les notifications sur mobile', 'test', 'normale'],
    ['Vérifier les droits d\'accès par grade', 'admin', 'haute'],
    ['Installer le cron d\'annulation des gages expirés', 'technique', 'haute'],
    ['Activer le HTTPS sur le serveur', 'technique', 'haute'],
    ['Définir les commanditaires de lancement', 'business', 'normale'],
    ['Tester l\'inscription d\'un nouveau membre', 'test', 'normale'],
];

// Insérer les tâches par défaut si la table est vide
$count = (int)$pdo->query("SELECT COUNT(*) FROM admin_notes")->fetchColumn();
if ($count === 0) {
    foreach ($defaultTasks as [$c,$cat,$p]) {
        $pdo->prepare("INSERT INTO admin_notes (contenu,categorie,priorite,auteur_id) VALUES (?,?,?,?)")->execute([$c,$cat,$p,$user['id']]);
    }
    header("Location: admin_notes.php"); exit;
}

include 'header.php';
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<style>
.note-card { border-radius:7px; padding:10px 14px; margin-bottom:6px; transition:opacity 0.2s; }
.note-card.fait { opacity:0.45; }
</style>

<div class="container-fluid mt-3 mb-5" style="max-width:900px;">
    <div class="d-flex align-items-center gap-3 mb-4">
        <a href="admin.php" class="btn btn-outline-secondary btn-sm"><i class="fa-solid fa-arrow-left fa-xs me-1"></i>Admin</a>
        <h4 class="oracle-text text-info mb-0" style="letter-spacing:2px;"><i class="fa-solid fa-clipboard-list me-2"></i>NOTES & TÂCHES ADMIN</h4>
        <span class="badge bg-danger ms-auto"><?= count(array_filter($notes, fn($n)=>$n['statut']==='todo')) ?> à faire</span>
        <span class="badge bg-warning text-dark"><?= count(array_filter($notes, fn($n)=>$n['statut']==='en_cours')) ?> en cours</span>
    </div>

    <!-- Ajouter -->
    <div class="card bg-dark border-info shadow mb-4">
        <div class="card-body">
            <form method="POST" class="d-flex gap-2 flex-wrap">
                <input type="text" name="contenu" class="form-control form-control-sm bg-dark text-white border-secondary flex-grow-1" placeholder="Nouvelle tâche ou note..." required>
                <input type="text" name="categorie" class="form-control form-control-sm bg-dark text-white border-secondary" style="width:120px;" placeholder="Catégorie" value="general">
                <select name="priorite" class="form-select form-select-sm bg-dark text-white border-secondary" style="width:120px;">
                    <option value="haute">🔴 Haute</option>
                    <option value="normale" selected>🟡 Normale</option>
                    <option value="basse">⚫ Basse</option>
                </select>
                <button type="submit" name="add_note" class="btn btn-info btn-sm fw-bold"><i class="fa-solid fa-plus fa-xs me-1"></i>Ajouter</button>
            </form>
        </div>
    </div>

    <!-- Liste -->
    <?php foreach ($notes as $n):
        $pc = $prioColors[$n['priorite']] ?? '#aaa';
        $sc = $statutColors[$n['statut']] ?? '#aaa';
        $sl = $statutLabels[$n['statut']] ?? $n['statut'];
        $isDone = $n['statut'] === 'fait';
    ?>
    <div class="note-card <?=$isDone?'fait':''?>" style="background:#0a0a12;border:1px solid <?=$isDone?'#1a1a1a':'#1a1a2a'?>;">
        <div class="d-flex align-items-center gap-2">
            <!-- Priorité dot -->
            <span style="width:8px;height:8px;border-radius:50%;background:<?=$pc?>;flex-shrink:0;"></span>
            <!-- Contenu -->
            <div style="flex:1;min-width:0;">
                <span style="font-size:0.75rem;color:<?=$isDone?'#555':'#ddd'?>;<?=$isDone?'text-decoration:line-through':''?>"><?=htmlspecialchars($n['contenu'])?></span>
                <span style="font-size:0.58rem;color:#444;margin-left:6px;"><?=htmlspecialchars($n['categorie'])?></span>
            </div>
            <!-- Auteur + date -->
            <span style="font-size:0.58rem;color:#333;flex-shrink:0;"><?=$n['username']??'Admin'?> · <?=date('d/m',strtotime($n['created_at']))?></span>
            <!-- Statut -->
            <form method="POST" class="d-flex gap-1">
                <input type="hidden" name="nid" value="<?=$n['id']?>">
                <select name="statut" onchange="this.form.submit()" class="form-select form-select-sm border-0 py-0" style="background:transparent;color:<?=$sc?>;font-size:0.62rem;width:100px;">
                    <option value="todo"    <?=$n['statut']==='todo'?'selected':''?>>À faire</option>
                    <option value="en_cours"<?=$n['statut']==='en_cours'?'selected':''?>>En cours</option>
                    <option value="fait"    <?=$n['statut']==='fait'?'selected':''?>>✓ Fait</option>
                </select>
                <button type="submit" name="update_statut" style="display:none;"></button>
            </form>
            <!-- Supprimer -->
            <form method="POST">
                <input type="hidden" name="nid" value="<?=$n['id']?>">
                <button type="submit" name="delete_note" onclick="return confirm('Supprimer ?')" style="background:none;border:none;color:#333;cursor:pointer;font-size:0.7rem;">✕</button>
            </form>
        </div>
    </div>
    <?php endforeach; ?>
</div>

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