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

requireLogin();
$user = getConnectedUser($pdo);
if (!$user) { header("Location: index.php"); exit; }
$userId    = (int)$user['id'];
$circleId  = (int)($_SESSION['circle_id'] ?? 1);
$isAdminU  = isAdmin($user);
$isOracleU = isOracle($user, $circleId, $pdo);
if (!$isAdminU && !$isOracleU) { header("Location: index.php"); exit; }

$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_marquee'])) {
        $message   = trim(htmlspecialchars($_POST['message']));
        $color     = preg_match('/^#[0-9a-fA-F]{6}$/', $_POST['text_color']??'') ? $_POST['text_color'] : '#FFFFFF';
        $speed     = in_array($_POST['speed'],['slow','normal','quick','super_quick']) ? $_POST['speed'] : 'normal';
        $endDate   = !empty($_POST['end_date']) ? $_POST['end_date'] : null;
        $targetCId = $isAdminU ? (int)($_POST['circle_id'] ?? $circleId) : $circleId;

        $pdo->prepare("INSERT INTO marquee (user_id,circle_id,message,text_color,speed,end_date,is_active) VALUES (?,?,?,?,?,?,1)")
            ->execute([$userId, $targetCId, $message, $color, $speed, $endDate]);

    // Sauvegarder couleur de fond si fournie
    if (!empty($_POST['marquee_bg']) && preg_match('/^#[0-9a-fA-F]{6}$/', $_POST['marquee_bg'])) {
        $bg = $_POST['marquee_bg'];
        $pdo->prepare("INSERT INTO admin_config (config_key,config_value) VALUES ('marquee_bg',?) ON DUPLICATE KEY UPDATE config_value=?")
            ->execute([$bg, $bg]);
    }
        $msg = "Message ajouté à la marquise !";
    }

    if (isset($_POST['toggle_marquee'])) {
        $mId  = (int)$_POST['marquee_id'];
        $newV = (int)$_POST['new_active'];
        $pdo->prepare("UPDATE marquee SET is_active=? WHERE id=?")->execute([$newV, $mId]);
        $msg = "Marquise mise à jour.";
    }

    if (isset($_POST['delete_marquee'])) {
        $pdo->prepare("DELETE FROM marquee WHERE id=?")->execute([(int)$_POST['marquee_id']]);
        $msg = "Message supprimé.";
    }
}

$items = $pdo->prepare("SELECT m.*, c.name as circle_name, u.username FROM marquee m LEFT JOIN circles c ON c.id=m.circle_id LEFT JOIN users u ON u.id=m.user_id WHERE m.circle_id=? ORDER BY m.id DESC");
$items->execute([$circleId]);
$marquees = $items->fetchAll();

// Lire couleur fond marquise actuelle
$marqueeBgCurrent = '#0d0d0d';
try {
    $bgStmt = $pdo->prepare("SELECT config_value FROM admin_config WHERE config_key='marquee_bg'");
    $bgStmt->execute(); $bgVal = $bgStmt->fetchColumn();
    if ($bgVal) $marqueeBgCurrent = $bgVal;
} catch (Exception $e) {}

include 'header.php';
?>

<div class="container mt-4">
    <h5 class="oracle-text text-info mb-3"> BANDE DÉFILANTE (MARQUISE)</h5>

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

    <div class="card bg-dark border-info shadow mb-4">
        <div class="card-header bg-transparent border-info py-2 fw-bold small text-info">➕ Ajouter un message</div>
        <div class="card-body">
            <form method="POST">
                <div class="row g-3">
                    <div class="col-12">
                        <label class="small text-white d-block mb-1">Message</label>
                        <input type="text" name="message" class="form-control form-control-sm" placeholder="Ex: Félicitations à Pascal pour sa victoire !" required maxlength="255">
                    </div>
                    <div class="col-md-3">
                        <label class="small text-white d-block mb-1">Couleur du texte</label>
                        <input type="color" name="text_color" class="form-control form-control-sm form-control-color" value="#FFFFFF">
                    </div>
                    <div class="col-md-3">
                        <label class="small text-white d-block mb-1">Couleur du fond <span class="text-muted" style="font-size:0.65rem;">(global)</span></label>
                        <div class="d-flex gap-2 align-items-center">
                            <input type="color" name="marquee_bg" class="form-control form-control-sm form-control-color"
                                   value="<?= htmlspecialchars($marqueeBgCurrent) ?>"
                                   oninput="document.getElementById('mqBgPreview').style.background=this.value">
                            <div id="mqBgPreview"
                                 style="flex:1;height:31px;border-radius:4px;border:1px solid #333;background:<?= htmlspecialchars($marqueeBgCurrent) ?>;
                                        display:flex;align-items:center;padding:0 8px;">
                                <span style="font-size:0.6rem;color:#ffc107;font-family:'Orbitron',sans-serif;font-weight:700;white-space:nowrap;overflow:hidden;">Aperçu fond</span>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <label class="small text-white d-block mb-1">Vitesse</label>
                        <select name="speed" class="form-select form-select-sm">
                            <option value="slow">Lent</option>
                            <option value="normal" selected>Normal</option>
                            <option value="quick">Rapide</option>
                            <option value="super_quick">Super rapide</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="small text-white d-block mb-1">Date de fin (optionnel)</label>
                        <input type="datetime-local" name="end_date" class="form-control form-control-sm">
                    </div>
                </div>
                <div class="mt-3 text-end">
                    <button type="submit" name="add_marquee" class="btn btn-info btn-sm fw-bold px-4">AJOUTER</button>
                </div>
            </form>
        </div>
    </div>

    <div class="card bg-dark border-secondary shadow">
        <div class="card-header bg-secondary py-2 fw-bold small text-white">Messages actifs</div>
        <div class="table-responsive">
            <table class="table table-dark table-hover table-sm small mb-0">
                <thead><tr><th>Message</th><th class="text-center">Couleur</th><th class="text-center">Vitesse</th><th class="text-center">Fin</th><th class="text-center">Actif</th><th></th></tr></thead>
                <tbody>
                <?php if (empty($marquees)): ?>
                    <tr><td colspan="6" class="text-center text-muted py-3">Aucun message.</td></tr>
                <?php endif; ?>
                <?php foreach ($marquees as $m): ?>
                <tr>
                    <td style="color:<?= htmlspecialchars($m['text_color']) ?>;">
                        <?= htmlspecialchars(mb_substr($m['message'],0,60)) ?><?= strlen($m['message'])>60?'…':'' ?>
                    </td>
                    <td class="text-center"><span style="background:<?= htmlspecialchars($m['text_color']) ?>;width:20px;height:20px;display:inline-block;border-radius:3px;border:1px solid #444;"></span></td>
                    <td class="text-center text-muted"><?= $m['speed'] ?></td>
                    <td class="text-center text-muted" style="font-size:0.65rem;"><?= $m['end_date'] ? date('d M Y', strtotime($m['end_date'])) : '—' ?></td>
                    <td class="text-center"><?= $m['is_active'] ? '<span class="text-success">✓</span>' : '<span class="text-muted">✗</span>' ?></td>
                    <td class="text-center">
                        <form method="POST" class="d-inline">
                            <input type="hidden" name="marquee_id" value="<?= $m['id'] ?>">
                            <input type="hidden" name="new_active" value="<?= $m['is_active']?0:1 ?>">
                            <button type="submit" name="toggle_marquee" class="btn btn-xs btn-outline-secondary py-0"><?= $m['is_active']?'Désactiver':'Activer' ?></button>
                        </form>
                        <form method="POST" class="d-inline">
                            <input type="hidden" name="marquee_id" value="<?= $m['id'] ?>">
                            <button type="submit" name="delete_marquee" class="btn btn-xs btn-outline-danger py-0"
                                    onclick="return confirm('Supprimer ?')">X️</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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