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

$msg = ''; $error = '';
$uploadDir = __DIR__ . '/assets/chat_icons/';
if (!is_dir($uploadDir)) @mkdir($uploadDir, 0755, true);
$uploadUrl = 'assets/chat_icons/';

// Ajouter icône unique
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['add_icon'])) {
    $emoji = trim($_POST['emoji']??'');
    $label = trim(htmlspecialchars($_POST['label']??''));
    $tier  = in_array($_POST['required_tier']??'', ['free','premium','premium_plus','admin']) ? $_POST['required_tier'] : 'free';
    $pts   = max(0,(int)($_POST['required_points']??0));
    $cat   = trim(htmlspecialchars($_POST['category']??'general'));
    $order = (int)($_POST['sort_order']??0);

    $imgPath = null;
    // Upload image si fournie
    if (!empty($_FILES['icon_image']['name'])) {
        $ext = strtolower(pathinfo($_FILES['icon_image']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['png','jpg','jpeg','gif','webp'])) {
            $fname = 'icon_'.uniqid().'.'.$ext;
            if (move_uploaded_file($_FILES['icon_image']['tmp_name'], $uploadDir.$fname)) {
                $imgPath = $uploadUrl.$fname;
                $emoji   = ''; // Pas d'emoji si image
            }
        } else { $error = "Format non supporté (png,jpg,gif,webp)"; }
    }

    if (!$error && ($emoji || $imgPath)) {
        $pdo->prepare("INSERT INTO chat_icons (emoji,label,category,required_tier,required_points,sort_order,is_active,image_path) VALUES (?,?,?,?,?,?,1,?)")
            ->execute([$emoji,$label,$cat,$tier,$pts,$order,$imgPath]);
        $msg = "Icône ajoutée !";
    }
}

// Upload spritesheet
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['upload_sprite'])) {
    if (!empty($_FILES['sprite']['name'])) {
        $ext = strtolower(pathinfo($_FILES['sprite']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['png','jpg','jpeg'])) {
            $cols = max(1,(int)($_POST['sprite_cols']??10));
            $rows = max(1,(int)($_POST['sprite_rows']??9));
            $tier = in_array($_POST['sprite_tier']??'', ['free','premium','premium_plus','admin']) ? $_POST['sprite_tier'] : 'free';
            $cat  = trim(htmlspecialchars($_POST['sprite_cat']??'custom'));

            $tmp = $_FILES['sprite']['tmp_name'];
            $img = imagecreatefromstring(file_get_contents($tmp));
            if ($img) {
                $iw = imagesx($img); $ih = imagesy($img);
                $cw = intval($iw/$cols); $ch = intval($ih/$rows);
                $n = 0;
                for ($r=0; $r<$rows; $r++) {
                    for ($c=0; $c<$cols; $c++) {
                        $dest = imagecreatetruecolor(32,32);
                        imagealphablending($dest,false); imagesavealpha($dest,true);
                        imagecopyresampled($dest,$img,0,0,$c*$cw,$r*$ch,32,32,$cw,$ch);
                        $fname = 'sprite_'.uniqid().'_'.($n+1).'.png';
                        if (imagepng($dest, $uploadDir.$fname)) {
                            $pdo->prepare("INSERT INTO chat_icons (emoji,label,category,required_tier,sort_order,is_active,image_path) VALUES ('','Icône '.(?),?,?,?,1,?)")
                                ->execute([$n+1,$cat,$tier,$n,$uploadUrl.$fname]);
                            $n++;
                        }
                        imagedestroy($dest);
                    }
                }
                imagedestroy($img);
                $msg = "$n icônes extraites de la spritesheet !";
            } else { $error = "Impossible de lire l'image."; }
        } else { $error = "Format non supporté."; }
    }
}

// Supprimer / toggle
if (isset($_GET['delete']) && (int)$_GET['delete']) {
    $pdo->prepare("DELETE FROM chat_icons WHERE id=?")->execute([(int)$_GET['delete']]);
    header("Location: admin_chat_icons.php"); exit;
}
if (isset($_GET['toggle']) && (int)$_GET['toggle']) {
    $pdo->prepare("UPDATE chat_icons SET is_active=1-is_active WHERE id=?")->execute([(int)$_GET['toggle']]);
    header("Location: admin_chat_icons.php"); exit;
}

// S'assurer que image_path existe
try { $pdo->exec("ALTER TABLE chat_icons ADD COLUMN IF NOT EXISTS image_path VARCHAR(500) DEFAULT NULL"); } catch(Exception $e) {}

$icons = $pdo->query("SELECT * FROM chat_icons ORDER BY sort_order ASC, id ASC")->fetchAll();
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:1000px;">
    <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-face-smile me-2"></i>ICÔNES DU CHAT</h4>
        <span class="badge bg-secondary ms-auto"><?= count($icons) ?> icônes</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; ?>

    <div class="row g-4">
        <div class="col-lg-4">

            <!-- Ajouter icône unique -->
            <div class="card bg-dark border-info shadow mb-3">
                <div class="card-header py-2 text-info fw-bold small" style="background:#050520;letter-spacing:1px;">+ ICÔNE UNIQUE</div>
                <div class="card-body">
                    <form method="POST" enctype="multipart/form-data">
                        <div class="mb-2">
                            <label class="small text-muted" style="font-size:0.62rem;">EMOJI (OU IMAGE)</label>
                            <div class="d-flex gap-2">
                                <input type="text" name="emoji" class="form-control form-control-sm bg-dark text-white border-secondary" placeholder="😀" style="width:60px;">
                                <input type="file" name="icon_image" accept="image/*" class="form-control form-control-sm bg-dark text-white border-secondary">
                            </div>
                        </div>
                        <div class="row g-2 mb-2">
                            <div class="col-7"><label class="small text-muted" style="font-size:0.62rem;">LABEL</label><input type="text" name="label" class="form-control form-control-sm bg-dark text-white border-secondary" placeholder="Feu"></div>
                            <div class="col-5"><label class="small text-muted" style="font-size:0.62rem;">ORDRE</label><input type="number" name="sort_order" value="0" class="form-control form-control-sm bg-dark text-white border-secondary"></div>
                        </div>
                        <div class="row g-2 mb-2">
                            <div class="col-6"><label class="small text-muted" style="font-size:0.62rem;">GRADE MIN</label>
                                <select name="required_tier" class="form-select form-select-sm bg-dark text-white border-secondary">
                                    <option value="free">Free</option><option value="premium">Premium</option>
                                    <option value="premium_plus">Premium+</option><option value="admin">Admin</option>
                                </select>
                            </div>
                            <div class="col-6"><label class="small text-muted" style="font-size:0.62rem;">CATÉGORIE</label><input type="text" name="category" value="general" class="form-control form-control-sm bg-dark text-white border-secondary"></div>
                        </div>
                        <div class="mb-2"><label class="small text-muted" style="font-size:0.62rem;">PTS INTERACTION MIN</label><input type="number" name="required_points" value="0" class="form-control form-control-sm bg-dark text-white border-secondary"></div>
                        <button type="submit" name="add_icon" class="btn btn-info btn-sm w-100 fw-bold">Ajouter</button>
                    </form>
                </div>
            </div>

            <!-- Spritesheet -->
            <div class="card bg-dark border-warning shadow">
                <div class="card-header py-2 text-warning fw-bold small" style="background:#1a1200;letter-spacing:1px;">📋 SPRITESHEET (GRILLE)</div>
                <div class="card-body">
                    <form method="POST" enctype="multipart/form-data">
                        <div class="mb-2"><label class="small text-muted" style="font-size:0.62rem;">IMAGE GRILLE</label><input type="file" name="sprite" accept="image/*" class="form-control form-control-sm bg-dark text-white border-secondary" required></div>
                        <div class="row g-2 mb-2">
                            <div class="col-6"><label class="small text-muted" style="font-size:0.62rem;">COLONNES</label><input type="number" name="sprite_cols" value="10" min="1" class="form-control form-control-sm bg-dark text-white border-secondary"></div>
                            <div class="col-6"><label class="small text-muted" style="font-size:0.62rem;">RANGÉES</label><input type="number" name="sprite_rows" value="9" min="1" class="form-control form-control-sm bg-dark text-white border-secondary"></div>
                        </div>
                        <div class="row g-2 mb-2">
                            <div class="col-6"><label class="small text-muted" style="font-size:0.62rem;">GRADE</label>
                                <select name="sprite_tier" class="form-select form-select-sm bg-dark text-white border-secondary">
                                    <option value="free">Free</option><option value="premium">Premium</option><option value="premium_plus">Premium+</option>
                                </select>
                            </div>
                            <div class="col-6"><label class="small text-muted" style="font-size:0.62rem;">CATÉGORIE</label><input type="text" name="sprite_cat" value="trophees" class="form-control form-control-sm bg-dark text-white border-secondary"></div>
                        </div>
                        <button type="submit" name="upload_sprite" class="btn btn-warning btn-sm w-100 fw-bold text-dark">Découper et importer</button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Liste icônes -->
        <div class="col-lg-8">
            <div class="card bg-dark border-secondary shadow">
                <div class="card-header py-2 fw-bold small" style="background:#0a0a0a;color:#aaa;letter-spacing:1px;">ICÔNES ACTUELLES</div>
                <div class="card-body p-0" style="max-height:600px;overflow-y:auto;">
                    <div style="display:flex;flex-wrap:wrap;gap:4px;padding:10px;">
                    <?php foreach ($icons as $ic):
                        $active = (int)$ic['is_active'];
                        $tierC = ['free'=>'#aaa','premium'=>'#d4af37','premium_plus'=>'#a9a9a9','admin'=>'#dc3545'];
                        $tc = $tierC[$ic['required_tier']]??'#aaa';
                    ?>
                    <div style="width:64px;text-align:center;background:#0a0a12;border:1px solid <?=$active?'#1a1a2a':'#0d0d0d'?>;border-radius:6px;padding:6px 4px;opacity:<?=$active?1:0.4?>;">
                        <?php if ($ic['image_path']): ?>
                        <img src="<?=htmlspecialchars($ic['image_path'])?>" style="width:32px;height:32px;object-fit:contain;display:block;margin:0 auto 3px;">
                        <?php else: ?>
                        <div style="font-size:1.5rem;line-height:1;margin-bottom:3px;"><?=htmlspecialchars($ic['emoji']??'')?></div>
                        <?php endif; ?>
                        <div style="font-size:0.5rem;color:#555;margin-bottom:3px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><?=htmlspecialchars($ic['label']??'')?></div>
                        <div style="font-size:0.48rem;color:<?=$tc?>;"><?=strtoupper($ic['required_tier']??'')?></div>
                        <div style="display:flex;gap:2px;justify-content:center;margin-top:3px;">
                            <a href="?toggle=<?=$ic['id']?>" style="font-size:0.5rem;color:<?=$active?'#28a745':'#555'?>;text-decoration:none;" title="<?=$active?'Désactiver':'Activer'?>"><?=$active?'✓':'○'?></a>
                            <a href="?delete=<?=$ic['id']?>" onclick="return confirm('Supprimer ?')" style="font-size:0.5rem;color:#dc3545;text-decoration:none;" title="Supprimer">✕</a>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    <?php if (empty($icons)): ?><div style="color:#555;font-size:0.72rem;padding:20px;">Aucune icône. Ajoutez-en ci-contre.</div><?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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