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

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

// Créer/modifier la table
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS site_appearance (
        id            INT AUTO_INCREMENT PRIMARY KEY,
        theme_name    VARCHAR(50)  DEFAULT 'Défaut sombre',
        bg_color      VARCHAR(7)   DEFAULT '#0a0a0a',
        primary_color VARCHAR(7)   DEFAULT '#0d6efd',
        accent_color  VARCHAR(7)   DEFAULT '#0dcaf0',
        text_color    VARCHAR(7)   DEFAULT '#e0e0e0',
        font_family   VARCHAR(50)  DEFAULT 'Orbitron',
        card_bg       VARCHAR(7)   DEFAULT '#1a1a2e',
        border_color  VARCHAR(7)   DEFAULT '#333333',
        is_active     TINYINT(1)   DEFAULT 1,
        is_default    TINYINT(1)   DEFAULT 0,
        created_at    TIMESTAMP    DEFAULT CURRENT_TIMESTAMP
    )");
    $pdo->exec("ALTER TABLE site_appearance ADD COLUMN IF NOT EXISTS is_default TINYINT(1) DEFAULT 0");
    $pdo->exec("ALTER TABLE site_appearance ADD COLUMN IF NOT EXISTS created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP");
    $pdo->exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS theme_id INT DEFAULT NULL");
} catch (Exception $e) {}

// Thèmes prédéfinis à insérer si absents
$presets = [
    ['Défaut sombre',     '#0a0a0a', '#0d6efd', '#0dcaf0', '#e0e0e0', 'Orbitron', '#1a1a2e', '#333333', 1],
    ['Nuit violette',     '#0d0715', '#7c3aed', '#a78bfa', '#e0e0e0', 'Orbitron', '#1a0d2e', '#3d1f6e', 0],
    ['Rouge feu',         '#0f0505', '#dc3545', '#ff6b6b', '#f0e0e0', 'Rajdhani', '#2a0f0f', '#6b1a1a', 0],
    ['Vert néon',         '#050f08', '#28a745', '#00ff88', '#d0ffe0', 'Exo 2',    '#0d2a15', '#1a5c2a', 0],
    ['Or & Noir',         '#0a0800', '#d4af37', '#ffc107', '#ffe090', 'Orbitron', '#1a1500', '#3d3000', 0],
    ['Bleu océan',        '#030d1a', '#0d6efd', '#00b4d8', '#caf0f8', 'Exo 2',    '#051525', '#0a3055', 0],
];

$existing = (int)$pdo->query("SELECT COUNT(*) FROM site_appearance")->fetchColumn();
if ($existing === 0) {
    foreach ($presets as $i => $p) {
        $pdo->prepare("INSERT INTO site_appearance (theme_name,bg_color,primary_color,accent_color,text_color,font_family,card_bg,border_color,is_default) VALUES (?,?,?,?,?,?,?,?,?)")
            ->execute($p);
    }
}

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

    // Définir comme thème par défaut du site
    if (isset($_POST['set_default'])) {
        $pdo->exec("UPDATE site_appearance SET is_default=0");
        $pdo->prepare("UPDATE site_appearance SET is_default=1 WHERE id=?")->execute([(int)$_POST['theme_id']]);
        $msg = "Thème par défaut mis à jour.";
    }

    // Créer un nouveau thème
    if (isset($_POST['create_theme'])) {
        $name   = trim(htmlspecialchars($_POST['theme_name'] ?? 'Nouveau thème'));
        $fields = ['bg_color','primary_color','accent_color','text_color','font_family','card_bg','border_color'];
        $vals   = array_map(fn($f) => htmlspecialchars($_POST[$f] ?? '#000000'), $fields);
        array_unshift($vals, $name);
        $pdo->prepare("INSERT INTO site_appearance (theme_name,bg_color,primary_color,accent_color,text_color,font_family,card_bg,border_color) VALUES (?,?,?,?,?,?,?,?)")
            ->execute($vals);
        $msg = "Thème \"$name\" créé !";
    }

    // Mettre à jour un thème existant
    if (isset($_POST['update_theme'])) {
        $id   = (int)$_POST['theme_id'];
        $name = trim(htmlspecialchars($_POST['theme_name'] ?? ''));
        $pdo->prepare("UPDATE site_appearance SET theme_name=?,bg_color=?,primary_color=?,accent_color=?,text_color=?,font_family=?,card_bg=?,border_color=? WHERE id=?")
            ->execute([$name, $_POST['bg_color'],$_POST['primary_color'],$_POST['accent_color'],$_POST['text_color'],$_POST['font_family'],$_POST['card_bg'],$_POST['border_color'], $id]);
        $msg = "Thème mis à jour.";
    }

    // Supprimer un thème
    if (isset($_POST['delete_theme'])) {
        $id = (int)$_POST['theme_id'];
        $isDefault = (int)$pdo->query("SELECT is_default FROM site_appearance WHERE id=$id")->fetchColumn();
        if ($isDefault) { $error = "Impossible de supprimer le thème par défaut."; }
        else { $pdo->prepare("DELETE FROM site_appearance WHERE id=?")->execute([$id]); $msg = "Thème supprimé."; }
    }
}

// Charger tous les thèmes
$themes = $pdo->query("SELECT * FROM site_appearance ORDER BY is_default DESC, id ASC")->fetchAll();
$defaultTheme = current(array_filter($themes, fn($t) => $t['is_default'])) ?: $themes[0];

$fonts = ['Orbitron','Exo 2','Rajdhani','Share Tech Mono','Press Start 2P','Roboto'];
$colorFields = [
    'bg_color'      => ['Arrière-plan principal', '#0a0a0a'],
    'card_bg'       => ['Fond des cartes',        '#1a1a2e'],
    'primary_color' => ['Couleur primaire',        '#0d6efd'],
    'accent_color'  => ['Couleur accent',          '#0dcaf0'],
    'text_color'    => ['Couleur du texte',        '#e0e0e0'],
    'border_color'  => ['Couleur des bordures',    '#333333'],
];

include 'header.php';
?>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<style>
.theme-card { border-radius:8px; overflow:hidden; cursor:pointer; transition:transform 0.15s,box-shadow 0.15s; }
.theme-card:hover { transform:translateY(-3px); box-shadow:0 8px 24px rgba(0,0,0,0.5); }
.theme-card.is-default { box-shadow:0 0 0 2px #ffc107; }
.color-swatch { width:24px; height:24px; border-radius:4px; border:1px solid rgba(255,255,255,0.1); display:inline-block; }
.lim-input { background:#0a0a14; border:1px solid #333; color:#ddd; border-radius:5px; padding:4px 8px; font-size:0.7rem; }
.lim-input:focus { outline:none; border-color:#0dcaf0; }
</style>

<div class="container-fluid mt-3 mb-5" style="max-width:1200px;">
    <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-palette me-2"></i>GESTION DES THÈMES</h4>
        <span class="badge bg-secondary ms-auto"><?= count($themes) ?> thème<?= count($themes)>1?'s':'' ?></span>
    </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; ?>

    <!-- Grille des thèmes -->
    <div class="row g-3 mb-5">
        <?php foreach ($themes as $t):
            $isDefault = (int)$t['is_default'];
        ?>
        <div class="col-md-4 col-lg-3">
            <div class="theme-card <?= $isDefault?'is-default':'' ?>" style="background:<?= htmlspecialchars($t['bg_color']) ?>;border:1px solid <?= htmlspecialchars($t['border_color']) ?>;">
                <!-- Aperçu du thème -->
                <div style="padding:12px;">
                    <div style="font-family:'<?= htmlspecialchars($t['font_family']) ?>',sans-serif;color:<?= htmlspecialchars($t['primary_color']) ?>;font-weight:700;font-size:0.8rem;margin-bottom:4px;">
                        <?= htmlspecialchars($t['theme_name']) ?>
                        <?php if ($isDefault): ?>
                        <span style="font-size:0.5rem;background:rgba(255,193,7,0.2);color:#ffc107;border:1px solid #ffc107;border-radius:8px;padding:1px 6px;margin-left:4px;">DÉFAUT</span>
                        <?php endif; ?>
                    </div>
                    <!-- Mini UI preview -->
                    <div style="background:<?= htmlspecialchars($t['card_bg']) ?>;border:1px solid <?= htmlspecialchars($t['border_color']) ?>;border-radius:5px;padding:8px;margin-bottom:8px;">
                        <div style="width:60%;height:4px;background:<?= htmlspecialchars($t['primary_color']) ?>;border-radius:2px;margin-bottom:6px;"></div>
                        <div style="width:100%;height:3px;background:<?= htmlspecialchars($t['accent_color']) ?>;border-radius:2px;margin-bottom:6px;"></div>
                        <div style="width:80%;height:3px;background:<?= htmlspecialchars($t['text_color']) ?>;opacity:0.3;border-radius:2px;"></div>
                    </div>
                    <!-- Swatches couleurs -->
                    <div style="display:flex;gap:4px;margin-bottom:10px;">
                        <?php foreach (['bg_color','primary_color','accent_color','text_color','card_bg','border_color'] as $cf): ?>
                        <span class="color-swatch" style="background:<?= htmlspecialchars($t[$cf]) ?>;" title="<?= $cf ?>"></span>
                        <?php endforeach; ?>
                        <span style="font-size:0.55rem;color:<?= htmlspecialchars($t['text_color']) ?>;opacity:0.6;margin-left:4px;line-height:24px;"><?= htmlspecialchars($t['font_family']) ?></span>
                    </div>
                    <!-- Actions -->
                    <div style="display:flex;gap:5px;">
                        <button onclick="openEditModal(<?= $t['id'] ?>)" style="flex:1;background:rgba(13,202,240,0.15);border:1px solid #0dcaf0;color:#0dcaf0;border-radius:4px;padding:3px;font-size:0.6rem;cursor:pointer;">✏️ Modifier</button>
                        <?php if (!$isDefault): ?>
                        <form method="POST" class="d-inline" style="flex:1;">
                            <input type="hidden" name="theme_id" value="<?= $t['id'] ?>">
                            <button type="submit" name="set_default" style="width:100%;background:rgba(255,193,7,0.15);border:1px solid #ffc107;color:#ffc107;border-radius:4px;padding:3px;font-size:0.6rem;cursor:pointer;">⭐ Défaut</button>
                        </form>
                        <form method="POST" class="d-inline" onsubmit="return confirm('Supprimer ce thème ?')">
                            <input type="hidden" name="theme_id" value="<?= $t['id'] ?>">
                            <button type="submit" name="delete_theme" style="background:rgba(220,53,69,0.15);border:1px solid #dc3545;color:#dc3545;border-radius:4px;padding:3px 6px;font-size:0.6rem;cursor:pointer;">✕</button>
                        </form>
                        <?php else: ?>
                        <span style="flex:1;text-align:center;font-size:0.58rem;color:#ffc107;padding:4px;opacity:0.7;">Actif sur le site</span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>

        <!-- Carte créer nouveau thème -->
        <div class="col-md-4 col-lg-3">
            <div class="theme-card" style="background:#050510;border:2px dashed #333;min-height:160px;display:flex;align-items:center;justify-content:center;" onclick="openCreateModal()">
                <div style="text-align:center;color:#444;">
                    <div style="font-size:2rem;margin-bottom:8px;">+</div>
                    <div style="font-size:0.7rem;">Créer un thème</div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal Modifier/Créer thème -->
<div id="themeModal" style="display:none;position:fixed;inset:0;z-index:9000;background:rgba(0,0,0,0.8);" onclick="if(event.target===this)closeModal()">
    <div style="margin:30px auto;width:min(700px,94vw);background:#0d0d1a;border:1px solid #0dcaf0;border-radius:10px;overflow:hidden;max-height:90vh;overflow-y:auto;">
        <div style="background:#050520;padding:12px 18px;border-bottom:1px solid #1a1a3a;display:flex;justify-content:space-between;align-items:center;">
            <span id="modalTitle" class="fw-bold text-info" style="font-size:0.8rem;letter-spacing:1px;">MODIFIER LE THÈME</span>
            <button onclick="closeModal()" style="background:none;border:none;color:#666;cursor:pointer;font-size:1rem;">✕</button>
        </div>
        <div style="padding:20px;">
            <form method="POST" id="themeForm">
                <input type="hidden" name="theme_id" id="formThemeId">
                <input type="hidden" name="action_type" id="formActionType">

                <div class="mb-3">
                    <label class="small text-muted d-block mb-1" style="font-size:0.65rem;">NOM DU THÈME</label>
                    <input type="text" name="theme_name" id="formThemeName" class="form-control form-control-sm bg-dark text-white border-secondary" required>
                </div>

                <div class="row g-3 mb-3">
                    <?php foreach ($colorFields as $field => [$label, $default]): ?>
                    <div class="col-6 col-md-4">
                        <label class="small text-muted d-block mb-1" style="font-size:0.62rem;"><?= strtoupper($label) ?></label>
                        <div class="d-flex gap-2 align-items-center">
                            <input type="color" name="<?= $field ?>" id="fc_<?= $field ?>"
                                   class="form-control form-control-color border-secondary"
                                   style="width:40px;height:30px;padding:2px;"
                                   value="<?= $default ?>"
                                   oninput="document.getElementById('ft_<?= $field ?>').value=this.value;updatePreview()">
                            <input type="text" id="ft_<?= $field ?>" value="<?= $default ?>"
                                   class="lim-input" style="width:80px;"
                                   oninput="document.getElementById('fc_<?= $field ?>').value=this.value;updatePreview()">
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>

                <div class="mb-4">
                    <label class="small text-muted d-block mb-1" style="font-size:0.62rem;">POLICE</label>
                    <select name="font_family" id="formFont" class="form-select form-select-sm bg-dark text-white border-secondary" onchange="updatePreview()">
                        <?php foreach ($fonts as $f): ?>
                        <option value="<?= $f ?>"><?= $f ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Aperçu en temps réel -->
                <div id="livePreview" style="border-radius:8px;overflow:hidden;margin-bottom:16px;border:1px solid #333;">
                    <div id="pv_bar" style="padding:10px 14px;">
                        <span id="pv_title" style="font-weight:700;font-size:0.85rem;">JETEGAGEQUE</span>
                    </div>
                    <div id="pv_body" style="padding:14px;">
                        <div id="pv_card" style="border-radius:6px;padding:10px;margin-bottom:10px;">
                            <div style="height:4px;border-radius:2px;margin-bottom:8px;" id="pv_accent"></div>
                            <div id="pv_text" style="font-size:0.75rem;">Aperçu du texte et des cartes</div>
                        </div>
                        <div style="display:flex;gap:6px;">
                            <div id="pv_btn1" style="padding:5px 12px;border-radius:5px;font-size:0.65rem;font-weight:700;">Bouton principal</div>
                            <div id="pv_btn2" style="padding:5px 12px;border-radius:5px;font-size:0.65rem;font-weight:700;border:1px solid;">Accent</div>
                        </div>
                    </div>
                </div>

                <div class="d-flex gap-2 justify-content-end">
                    <button type="button" onclick="closeModal()" class="btn btn-outline-secondary btn-sm">Annuler</button>
                    <button type="submit" id="formSubmitBtn" class="btn btn-info btn-sm fw-bold">
                        <i class="fa-solid fa-floppy-disk me-1"></i>Enregistrer
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
const allThemes = <?= json_encode(array_column($themes, null, 'id')) ?>;

function openEditModal(id) {
    const t = allThemes[id];
    document.getElementById('modalTitle').textContent = 'MODIFIER — ' + t.theme_name;
    document.getElementById('formThemeId').value = id;
    document.getElementById('formActionType').value = 'update';
    document.getElementById('formThemeName').value = t.theme_name;
    document.getElementById('formFont').value = t.font_family;
    // Couleurs
    const fields = ['bg_color','primary_color','accent_color','text_color','card_bg','border_color'];
    fields.forEach(f => {
        document.getElementById('fc_' + f).value = t[f] || '#000000';
        document.getElementById('ft_' + f).value = t[f] || '#000000';
    });
    document.getElementById('formSubmitBtn').textContent = 'Enregistrer';
    document.getElementById('themeForm').onsubmit = () => {
        document.querySelector('[name=action_type]').name = 'update_theme';
    };
    updatePreview();
    document.getElementById('themeModal').style.display = 'block';
}

function openCreateModal() {
    document.getElementById('modalTitle').textContent = 'CRÉER UN NOUVEAU THÈME';
    document.getElementById('formThemeId').value = '';
    document.getElementById('formThemeName').value = 'Nouveau thème';
    document.getElementById('formFont').value = 'Orbitron';
    const defaults = {bg_color:'#0a0a0a',primary_color:'#0d6efd',accent_color:'#0dcaf0',text_color:'#e0e0e0',card_bg:'#1a1a2e',border_color:'#333333'};
    Object.entries(defaults).forEach(([f,v]) => {
        document.getElementById('fc_' + f).value = v;
        document.getElementById('ft_' + f).value = v;
    });
    document.getElementById('themeForm').onsubmit = () => {
        document.querySelector('[name=action_type]').name = 'create_theme';
    };
    updatePreview();
    document.getElementById('themeModal').style.display = 'block';
}

function closeModal() {
    document.getElementById('themeModal').style.display = 'none';
}

function getVal(f) { return document.getElementById('fc_' + f)?.value || '#000000'; }

function updatePreview() {
    const bg      = getVal('bg_color');
    const card    = getVal('card_bg');
    const primary = getVal('primary_color');
    const accent  = getVal('accent_color');
    const text    = getVal('text_color');
    const border  = getVal('border_color');
    const font    = document.getElementById('formFont')?.value || 'Orbitron';

    document.getElementById('pv_bar').style.cssText    = `padding:10px 14px;background:${bg};border-bottom:2px solid ${accent};`;
    document.getElementById('pv_title').style.cssText  = `font-weight:700;font-size:0.85rem;color:${primary};font-family:'${font}',sans-serif;`;
    document.getElementById('pv_body').style.cssText   = `padding:14px;background:${bg};`;
    document.getElementById('pv_card').style.cssText   = `border-radius:6px;padding:10px;margin-bottom:10px;background:${card};border:1px solid ${border};`;
    document.getElementById('pv_accent').style.cssText = `height:4px;border-radius:2px;margin-bottom:8px;background:${accent};`;
    document.getElementById('pv_text').style.cssText   = `font-size:0.75rem;color:${text};`;
    document.getElementById('pv_btn1').style.cssText   = `padding:5px 12px;border-radius:5px;font-size:0.65rem;font-weight:700;background:${primary};color:#fff;`;
    document.getElementById('pv_btn2').style.cssText   = `padding:5px 12px;border-radius:5px;font-size:0.65rem;font-weight:700;border:1px solid ${accent};color:${accent};`;
}
</script>

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