<?php
// admin/admin_games.php
require '../config/db.php';
// Asegúrate de que la ruta al addon sea correcta según tu estructura
require '../inc/addons/game_system/functions.php'; 


// Seguridad: Solo Admin
if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
    header("Location: ../index.php"); exit;
}

$message = "";

// --- LÓGICA PARA ELIMINAR (NUEVO) ---
if (isset($_GET['delete_game'])) {
    $id = (int)$_GET['delete_game'];
    try {
        // Desactivamos llaves foráneas para limpiar repetidos sin errores
        $pdo->exec("SET FOREIGN_KEY_CHECKS = 0");
        
        $stmt = $pdo->prepare("DELETE FROM games WHERE id = ?");
        if ($stmt->execute([$id])) {
            $message = "Game removed successfully!";
        }
        
        $pdo->exec("SET FOREIGN_KEY_CHECKS = 1");
    } catch (Exception $e) {
        $message = "Error deleting: " . $e->getMessage();
    }
}

// Lógica para AGREGAR juego
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_game'])) {
    $name = trim($_POST['name']);
    $slug = g_create_slug($name); 

    $stmt = $pdo->prepare("INSERT INTO games (name, slug, is_active) VALUES (?, ?, 1)");
    if ($stmt->execute([$name, $slug])) {
        $message = "Game '$name' added successfully!";
    }
}

// Obtenemos todos los juegos (incluso los inactivos para poder borrarlos)
$games = $pdo->query("SELECT * FROM games ORDER BY name ASC")->fetchAll();
include '../includes/header.php';
?>

<div class="admin-container" style="max-width: 800px; margin: 50px auto; padding: 20px; color: white;">
    <h2 style="color: var(--primary); font-weight: 900; text-transform: uppercase; letter-spacing: 1px;">
        <i class="fa-solid fa-gamepad"></i> Game System Management
    </h2>
    
    <?php if($message): ?>
        <div style="background: rgba(0,255,136,0.1); padding: 15px; border-radius: 8px; border: 1px solid var(--primary); color: var(--primary); margin-bottom: 25px; font-weight: bold;">
            <i class="fa-solid fa-circle-check"></i> <?php echo $message; ?>
        </div>
    <?php endif; ?>

    <div style="background: #161b22; padding: 25px; border-radius: 15px; border: 1px solid #30363d; margin-bottom: 35px; box-shadow: 0 10px 30px rgba(0,0,0,0.3);">
        <form method="POST">
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">
                <div>
                    <label style="font-size: 11px; color: #8b949e; font-weight: 900; text-transform: uppercase;">Game Name</label>
                    <input type="text" id="game_name" name="name" class="v-input" placeholder="e.g. Albion Online" 
                           style="width: 100%; background: #0d1117; border: 1px solid #30363d; color: white; padding: 12px; border-radius: 8px; outline: none;" 
                           required onkeyup="updateSlug()">
                </div>
                <div>
                    <label style="font-size: 11px; color: #8b949e; font-weight: 900; text-transform: uppercase;">URL SLUG (Preview)</label>
                    <input type="text" id="game_slug" class="v-input" readonly 
                           style="width: 100%; background: #000; border: 1px solid #30363d; color: #555; padding: 12px; border-radius: 8px; cursor: not-allowed;">
                </div>
            </div>
            <button type="submit" name="add_game" class="v-btn-publish" 
                    style="width: 100%; background: var(--primary); color: black; border: none; padding: 14px; border-radius: 8px; font-weight: 900; cursor: pointer; text-transform: uppercase;">
                <i class="fa-solid fa-plus"></i> ADD NEW GAME
            </button>
        </form>
    </div>

    <div id="game-list">
        <h3 style="font-size: 14px; color: #8b949e; text-transform: uppercase; margin-bottom: 15px;">Active Catalog</h3>
        <?php foreach($games as $game): ?>
            <div style="background: #161b22; padding: 18px; border: 1px solid #30363d; border-radius: 10px; margin-bottom: 12px; display: flex; justify-content: space-between; align-items: center; transition: 0.3s;">
                <div style="display: flex; flex-direction: column;">
                    <span style="font-size: 16px; font-weight: 800; color: white;"><?php echo htmlspecialchars($game['name']); ?></span>
                    <small style="color: #555; font-weight: 600;">/games/<?php echo htmlspecialchars($game['slug']); ?></small>
                </div>
                
                <div style="display: flex; gap: 15px; align-items: center;">
                    <i class="fa-solid fa-pen-to-square" style="cursor: pointer; color: #444;" title="Edit"></i>
                    
                    <a href="admin_games.php?delete_game=<?php echo $game['id']; ?>" 
                       onclick="return confirm('¿Eliminar este juego? Esto limpiará los repetidos.')"
                       style="color: #ff4d4d; font-size: 18px; transition: 0.2s;">
                        <i class="fa-solid fa-trash-can"></i>
                    </a>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<script>
function updateSlug() {
    let name = document.getElementById('game_name').value;
    let slug = name.toLowerCase()
                   .normalize("NFD").replace(/[\u0300-\u036f]/g, "") // Quitar acentos
                   .replace(/ /g, '-')
                   .replace(/[^\w-]+/g, '');
    document.getElementById('game_slug').value = slug;
}
</script>