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

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

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

// Créer table si absente
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS commandites (
        id          INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
        nom         VARCHAR(100) NOT NULL,
        slogan      VARCHAR(255) DEFAULT NULL,
        logo_url    VARCHAR(500) DEFAULT NULL,
        site_url    VARCHAR(500) DEFAULT NULL,
        couleur     VARCHAR(7) DEFAULT '#0dcaf0',
        niveau      ENUM('bronze','argent','or','platine') DEFAULT 'bronze',
        date_debut  DATE DEFAULT NULL,
        date_fin    DATE DEFAULT NULL,
        is_active   TINYINT(1) DEFAULT 1,
        afficher_marquise TINYINT(1) DEFAULT 0,
        afficher_dashboard TINYINT(1) DEFAULT 1,
        created_at  TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
} catch (Exception $e) {}

// Actions POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_commandite'])) {
        $nom    = trim(htmlspecialchars($_POST['nom'] ?? ''));
        $slogan = trim(htmlspecialchars($_POST['slogan'] ?? ''));
        $logo   = trim($_POST['logo_url'] ?? '');
        $site   = trim($_POST['site_url'] ?? '');
        $color  = preg_match('/^#[0-9a-fA-F]{6}$/', $_POST['couleur']??'') ? $_POST['couleur'] : '#0dcaf0';
        $niveau = in_array($_POST['niveau']??'', ['bronze','argent','or','platine']) ? $_POST['niveau'] : 'bronze';
        $debut  = !empty($_POST['date_debut']) ? $_POST['date_debut'] : null;
        $fin    = !empty($_POST['date_fin'])   ? $_POST['date_fin']   : null;
        $marquise = isset($_POST['afficher_marquise']) ? 1 : 0;
        $dash     = isset($_POST['afficher_dashboard']) ? 1 : 0;
        if ($nom) {
            $pdo->prepare("INSERT INTO commandites (nom,slogan,logo_url,site_url,couleur,niveau,date_debut,date_fin,afficher_marquise,afficher_dashboard) VALUES (?,?,?,?,?,?,?,?,?,?)")
                ->execute([$nom,$slogan,$logo,$site,$color,$niveau,$debut,$fin,$marquise,$dash]);
            $msg = "Commanditaire \"$nom\" ajouté !";
        } else { $error = "Le nom est requis."; }
    }
    if (isset($_POST['toggle_active'])) {
        $id  = (int)$_POST['cid'];
        $val = (int)$_POST['val'];
        $pdo->prepare("UPDATE commandites SET is_active=? WHERE id=?")->execute([$val, $id]);
        $msg = "Statut mis à jour.";
    }
    if (isset($_POST['delete_commandite'])) {
        $pdo->prepare("DELETE FROM commandites WHERE id=?")->execute([(int)$_POST['cid']]);
        $msg = "Commanditaire supprimé.";
    }
}

// Charger
try {
    $list = $pdo->query("SELECT * FROM commandites ORDER BY FIELD(niveau,'platine','or','argent','bronze'), nom ASC")->fetchAll();
} catch (Exception $e) { $list = []; }

$niveauColors = ['platine'=>'#e8e8ff','or'=>'#d4af37','argent'=>'#a9a9a9','bronze'=>'#cd7f32'];
$niveauLabels = ['platine'=>'🏆 PLATINE','or'=>'🥇 OR','argent'=>'🥈 ARGENT','bronze'=>'🥉 BRONZE'];

include 'header.php';
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">

<div class="container-fluid mt-3 mb-5" style="max-width:1100px;">
    <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 mb-0" style="color:#d4af37;letter-spacing:2px;">
            <i class="fa-solid fa-handshake me-2"></i>COMMANDITAIRES
        </h4>
    </div>

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

    <div class="row g-4">
        <!-- Formulaire ajout -->
        <div class="col-lg-5">
            <div class="card bg-dark shadow" style="border:1px solid #d4af37;">
                <div class="card-header py-2 fw-bold" style="background:#1a1200;border-bottom:1px solid #3a2a00;color:#d4af37;font-size:0.78rem;letter-spacing:1px;">
                    <i class="fa-solid fa-plus me-2"></i>AJOUTER UN COMMANDITAIRE
                </div>
                <div class="card-body">
                    <form method="POST">
                        <div class="mb-3">
                            <label class="small text-muted mb-1" style="font-size:0.65rem;">NOM *</label>
                            <input type="text" name="nom" class="form-control form-control-sm bg-dark text-white border-secondary" required placeholder="Ex: Brasserie Boréale">
                        </div>
                        <div class="mb-3">
                            <label class="small text-muted mb-1" style="font-size:0.65rem;">SLOGAN</label>
                            <input type="text" name="slogan" class="form-control form-control-sm bg-dark text-white border-secondary" placeholder="Ex: Le pari des vrais amateurs">
                        </div>
                        <div class="mb-3">
                            <label class="small text-muted mb-1" style="font-size:0.65rem;">URL DU LOGO</label>
                            <input type="url" name="logo_url" class="form-control form-control-sm bg-dark text-white border-secondary" placeholder="https://...">
                        </div>
                        <div class="mb-3">
                            <label class="small text-muted mb-1" style="font-size:0.65rem;">SITE WEB</label>
                            <input type="url" name="site_url" class="form-control form-control-sm bg-dark text-white border-secondary" placeholder="https://...">
                        </div>
                        <div class="row g-2 mb-3">
                            <div class="col-6">
                                <label class="small text-muted mb-1" style="font-size:0.65rem;">NIVEAU</label>
                                <select name="niveau" class="form-select form-select-sm bg-dark text-white border-secondary">
                                    <option value="bronze">🥉 Bronze</option>
                                    <option value="argent">🥈 Argent</option>
                                    <option value="or" selected>🥇 Or</option>
                                    <option value="platine">🏆 Platine</option>
                                </select>
                            </div>
                            <div class="col-6">
                                <label class="small text-muted mb-1" style="font-size:0.65rem;">COULEUR</label>
                                <input type="color" name="couleur" value="#d4af37" class="form-control form-control-sm form-control-color border-secondary" style="height:31px;">
                            </div>
                        </div>
                        <div class="row g-2 mb-3">
                            <div class="col-6">
                                <label class="small text-muted mb-1" style="font-size:0.65rem;">DÉBUT</label>
                                <input type="date" name="date_debut" class="form-control form-control-sm bg-dark text-white border-secondary">
                            </div>
                            <div class="col-6">
                                <label class="small text-muted mb-1" style="font-size:0.65rem;">FIN</label>
                                <input type="date" name="date_fin" class="form-control form-control-sm bg-dark text-white border-secondary">
                            </div>
                        </div>
                        <div class="mb-3">
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="checkbox" name="afficher_dashboard" id="chkDash" checked>
                                <label class="form-check-label small" for="chkDash" style="font-size:0.68rem;color:#ddd;">Dashboard</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="checkbox" name="afficher_marquise" id="chkMarq">
                                <label class="form-check-label small" for="chkMarq" style="font-size:0.68rem;color:#ddd;">Marquise</label>
                            </div>
                        </div>
                        <button type="submit" name="add_commandite" class="btn btn-sm w-100 fw-bold" style="background:rgba(212,175,55,0.2);border:1px solid #d4af37;color:#d4af37;">
                            <i class="fa-solid fa-plus me-1"></i>Ajouter
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Liste -->
        <div class="col-lg-7">
            <div class="card bg-dark border-secondary shadow">
                <div class="card-header py-2 fw-bold small" style="background:#0a0a0a;color:#d4af37;letter-spacing:1px;">
                    <i class="fa-solid fa-list me-2"></i>COMMANDITAIRES (<?= count($list) ?>)
                </div>
                <div class="card-body p-0">
                    <?php if (empty($list)): ?>
                    <div class="text-center text-muted py-4" style="font-size:0.75rem;">Aucun commanditaire pour le moment.</div>
                    <?php else: foreach ($list as $c):
                        $nc = $niveauColors[$c['niveau']] ?? '#aaa';
                        $nl = $niveauLabels[$c['niveau']] ?? $c['niveau'];
                        $active = (int)$c['is_active'];
                        $expired = $c['date_fin'] && strtotime($c['date_fin']) < time();
                    ?>
                    <div style="display:flex;align-items:center;gap:10px;padding:10px 14px;border-bottom:1px solid #111;<?= $expired?'opacity:0.5':'' ?>">
                        <!-- Logo -->
                        <div style="width:40px;height:40px;flex-shrink:0;border-radius:6px;overflow:hidden;background:#111;border:1px solid #222;display:flex;align-items:center;justify-content:center;">
                            <?php if ($c['logo_url']): ?>
                            <img src="<?= htmlspecialchars($c['logo_url']) ?>" style="width:100%;height:100%;object-fit:contain;" onerror="this.style.display='none'">
                            <?php else: ?>
                            <i class="fa-solid fa-handshake" style="color:#333;font-size:1rem;"></i>
                            <?php endif; ?>
                        </div>
                        <!-- Info -->
                        <div style="flex:1;min-width:0;">
                            <div style="display:flex;align-items:center;gap:6px;margin-bottom:2px;">
                                <span style="font-size:0.78rem;font-weight:700;color:<?= $nc ?>;"><?= htmlspecialchars($c['nom']) ?></span>
                                <span style="font-size:0.52rem;font-weight:700;color:<?= $nc ?>;background:rgba(0,0,0,0.3);border:1px solid <?= $nc ?>;border-radius:8px;padding:0 6px;"><?= $nl ?></span>
                                <?php if ($c['afficher_marquise']): ?><span style="font-size:0.5rem;background:rgba(13,202,240,0.15);border:1px solid #0dcaf0;color:#0dcaf0;border-radius:4px;padding:0 4px;">Marquise</span><?php endif; ?>
                                <?php if ($expired): ?><span style="font-size:0.5rem;background:rgba(220,53,69,0.2);color:#dc3545;border-radius:4px;padding:0 4px;">Expiré</span><?php endif; ?>
                            </div>
                            <?php if ($c['slogan']): ?>
                            <div style="font-size:0.62rem;color:#888;font-style:italic;"><?= htmlspecialchars($c['slogan']) ?></div>
                            <?php endif; ?>
                            <div style="font-size:0.58rem;color:#444;margin-top:2px;">
                                <?php if ($c['date_debut'] || $c['date_fin']): ?>
                                <?= $c['date_debut'] ? date('d/m/Y', strtotime($c['date_debut'])) : '...' ?> → <?= $c['date_fin'] ? date('d/m/Y', strtotime($c['date_fin'])) : '∞' ?>
                                <?php endif; ?>
                                <?php if ($c['site_url']): ?>
                                · <a href="<?= htmlspecialchars($c['site_url']) ?>" target="_blank" style="color:#555;font-size:0.58rem;">🔗 Site</a>
                                <?php endif; ?>
                            </div>
                        </div>
                        <!-- Actions -->
                        <div style="display:flex;flex-direction:column;gap:4px;flex-shrink:0;">
                            <form method="POST" class="d-inline">
                                <input type="hidden" name="cid" value="<?= $c['id'] ?>">
                                <input type="hidden" name="val" value="<?= $active ? 0 : 1 ?>">
                                <button type="submit" name="toggle_active"
                                        style="background:<?= $active?'rgba(40,167,69,0.15)':'rgba(108,117,125,0.15)' ?>;border:1px solid <?= $active?'#28a745':'#555' ?>;color:<?= $active?'#28a745':'#888' ?>;border-radius:4px;padding:2px 8px;font-size:0.6rem;cursor:pointer;width:100%;">
                                    <?= $active ? '✓ Actif' : '⏸ Inactif' ?>
                                </button>
                            </form>
                            <form method="POST" class="d-inline" onsubmit="return confirm('Supprimer ce commanditaire ?')">
                                <input type="hidden" name="cid" value="<?= $c['id'] ?>">
                                <button type="submit" name="delete_commandite"
                                        style="background:rgba(220,53,69,0.1);border:1px solid #dc3545;color:#dc3545;border-radius:4px;padding:2px 8px;font-size:0.6rem;cursor:pointer;width:100%;">
                                    ✕ Suppr.
                                </button>
                            </form>
                        </div>
                    </div>
                    <?php endforeach; endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

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