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

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

$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_trophy'])) {
        $title    = trim(htmlspecialchars($_POST['title']));
        $desc     = trim(htmlspecialchars($_POST['description']));
        $reqType  = in_array($_POST['requirement_type'],['win_count','win_percent','interaction','reliability']) ? $_POST['requirement_type'] : 'win_count';
        $reqVal   = max(1,(int)$_POST['requirement_value']);
        $iconPath = '';
        $iconEmoji = trim($_POST['icon_emoji'] ?? '');

        // Upload image si fourni
        if (isset($_FILES['icon']) && $_FILES['icon']['size'] > 0) {
            $f   = $_FILES['icon'];
            $ext = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
            if (in_array($ext,['png','jpg','jpeg','gif','svg','webp'])) {
                $dir = __DIR__ . '/uploads/trophees/';
                if (!is_dir($dir)) mkdir($dir,0755,true);
                $fname = 'trophy_'.time().'.'.$ext;
                if (move_uploaded_file($f['tmp_name'],$dir.$fname)) $iconPath = 'uploads/trophees/'.$fname;
            }
        }
        // Si pas d'image mais emoji fourni, l'utiliser comme icon_path (sera affiché directement)
        if (empty($iconPath) && !empty($iconEmoji)) {
            $iconPath = 'emoji:' . $iconEmoji;
        }

        try {
            $pdo->prepare("INSERT INTO trophy_levels (title,description,icon_path,requirement_type,requirement_value) VALUES (?,?,?,?,?)")
                ->execute([$title,$desc,$iconPath,$reqType,$reqVal]);
            $msg = "Trophée ajouté !";
        } catch (Exception $e) {
            $msg = "Erreur : " . $e->getMessage();
        }
    }

    if (isset($_POST['delete_trophy'])) {
        try {
            $pdo->prepare("DELETE FROM trophy_levels WHERE id=?")->execute([(int)$_POST['trophy_id']]);
            $msg = "Trophée supprimé.";
        } catch (Exception $e) { $msg = "Erreur : " . $e->getMessage(); }
    }
}

try {
    $trophies = $pdo->query("SELECT * FROM trophy_levels ORDER BY requirement_value ASC")->fetchAll();
} catch (Exception $e) {
    $trophies = [];
    $msg = "Table trophy_levels absente. Exécute db_migrations.sql d'abord.";
}

include 'header.php';
?>

<div class="container mt-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 TROPHEES</h5>

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

    <!-- Ajouter un trophée -->
    <div class="card bg-dark border-warning shadow mb-4">
        <div class="card-header bg-transparent border-warning py-2 fw-bold small text-warning">Ajouter un trophee</div>
        <div class="card-body">
            <form method="POST" enctype="multipart/form-data">
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="small text-white d-block mb-1">Titre</label>
                        <input type="text" name="title" class="form-control form-control-sm" placeholder="Ex: Premier Sang" required>
                    </div>
                    <div class="col-md-8">
                        <label class="small text-white d-block mb-1">Description</label>
                        <input type="text" name="description" class="form-control form-control-sm" placeholder="Ex: A lancé son premier défi." required>
                    </div>
                    <div class="col-md-4">
                        <label class="small text-white d-block mb-1">Type de condition</label>
                        <select name="requirement_type" class="form-select form-select-sm">
                            <option value="win_count">Nombre de victoires</option>
                            <option value="win_percent">% de victoires</option>
                            <option value="interaction">Points interaction</option>
                            <option value="reliability">Score de fiabilité</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="small text-white d-block mb-1">Valeur requise</label>
                        <input type="number" name="requirement_value" class="form-control form-control-sm" value="1" min="1" required>
                    </div>
                    <div class="col-md-5">
                        <label class="small text-white d-block mb-1">Icône — Emoji OU image</label>
                        <div class="input-group input-group-sm mb-1">
                            <span class="input-group-text bg-dark border-secondary text-muted" style="font-size:0.65rem;">Emoji</span>
                            <input type="text" name="icon_emoji" class="form-control form-control-sm text-center" placeholder="ex: ★ ✓ A" maxlength="5" id="emojiInput" oninput="document.getElementById('emojiPreview').innerText=this.value">
                            <span id="emojiPreview" style="font-size:1.4rem;padding:0 8px;line-height:1;display:flex;align-items:center;"></span>
                        </div>
                        <input type="file" name="icon" class="form-control form-control-sm" accept="image/*">
                        <small class="text-muted" style="font-size:0.6rem;">Emoji OU image (l'image a priorité)</small>
                    </div>
                </div>
                <div class="mt-3 text-end">
                    <button type="submit" name="add_trophy" class="btn btn-warning btn-sm fw-bold px-4">AJOUTER</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Liste des trophées -->
    <div class="card bg-dark border-secondary shadow">
        <div class="card-header bg-secondary py-2 fw-bold small text-white">Liste (<?= count($trophies) ?>)</div>
        <div class="table-responsive">
            <table class="table table-dark table-hover table-sm small mb-0">
                <thead><tr><th>Icône</th><th>Titre</th><th>Description</th><th>Condition</th><th>Valeur</th><th></th></tr></thead>
                <tbody>
                <?php if (empty($trophies)): ?>
                    <tr><td colspan="6" class="text-center text-muted py-3">Aucun trophée.</td></tr>
                <?php endif; ?>
                <?php foreach ($trophies as $t): ?>
                <tr>
                    <td>
                        <?php
                        $ip = $t['icon_path'] ?? '';
                        if (!empty($ip) && strpos($ip, 'emoji:') === 0) {
                            echo '<span style="font-size:1.4rem;">' . htmlspecialchars(substr($ip, 6)) . '</span>';
                        } elseif (!empty($ip) && @file_exists(__DIR__.'/'.$ip)) {
                            echo '<img src="' . htmlspecialchars($ip) . '" style="width:28px;height:28px;object-fit:contain;border-radius:3px;">';
                        } else {
                            echo '<span class="text-muted">-</span>';
                        }
                        ?>
                    </td>
                    <td class="fw-bold"><?= htmlspecialchars($t['title']) ?></td>
                    <td class="text-muted"><?= htmlspecialchars($t['description']) ?></td>
                    <td><span class="badge bg-secondary" style="font-size:0.6rem;"><?= $t['requirement_type'] ?></span></td>
                    <td class="text-success"><?= $t['requirement_value'] ?></td>
                    <td>
                        <form method="POST">
                            <input type="hidden" name="trophy_id" value="<?= $t['id'] ?>">
                            <button type="submit" name="delete_trophy" class="btn btn-xs btn-outline-danger py-0"
                                    onclick="return confirm('Supprimer ce trophee ?')">Supprimer</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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