<?php
// admin/categories.php
require '../config/db.php';


// Security Check using 'role'
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') { 
    header("Location: ../index.php"); 
    exit; 
}

// --- ACTIONS HANDLER ---

// 1. Create Category
if (isset($_POST['add_category'])) {
    $name = $_POST['name'];
    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name)));
    $game_id = ($_POST['game_id'] == 'global') ? null : $_POST['game_id'];

    $stmt = $pdo->prepare("INSERT INTO categories (name, slug, game_id) VALUES (?, ?, ?)");
    $stmt->execute([$name, $slug, $game_id]);
    header("Location: categories.php?status=created");
    exit;
}

// 2. Update Category
if (isset($_POST['edit_category'])) {
    $id = $_POST['cat_id'];
    $name = $_POST['new_name'];
    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name)));

    $stmt = $pdo->prepare("UPDATE categories SET name = ?, slug = ? WHERE id = ?");
    $stmt->execute([$name, $slug, $id]);
    header("Location: categories.php?status=updated");
    exit;
}

// 3. Delete Category
if (isset($_GET['delete'])) {
    $stmt = $pdo->prepare("DELETE FROM categories WHERE id = ?");
    $stmt->execute([$_GET['delete']]);
    header("Location: categories.php?status=deleted");
    exit;
}

// --- DATA FETCHING ---
$categories = $pdo->query("
    SELECT c.*, COALESCE(g.name, 'GLOBAL / ALL GAMES') as game_name 
    FROM categories c 
    LEFT JOIN games g ON c.game_id = g.id 
    ORDER BY g.name ASC, c.name ASC
")->fetchAll();

$games = $pdo->query("SELECT id, name FROM games ORDER BY name ASC")->fetchAll();

include '../includes/header.php';
?>

<style>
    :root {
        --v-bg: #0d1117;
        --v-card: #161b22;
        --v-accent: #00ff88;
        --v-border: #30363d;
        --v-text-gray: #8b949e;
        --v-yellow: #ffcc00;
        --v-red: #ff4d4d;
    }

    body { background-color: var(--v-bg); color: white; font-family: 'Inter', sans-serif; }
    
    .v-container { max-width: 1200px; margin: 50px auto; padding: 0 20px; }
    
    .v-header { display: flex; justify-content: space-between; align-items: flex-end; margin-bottom: 40px; }
    .v-title { margin: 0; font-family: 'Syncopate', sans-serif; font-size: 24px; font-weight: 900; letter-spacing: -1px; }
    .v-title span { color: var(--v-accent); }

    .v-card { background: var(--v-card); border: 1px solid var(--v-border); border-radius: 12px; padding: 25px; margin-bottom: 30px; }
    
    .v-input { 
        background: #0d1117; border: 1px solid var(--v-border); color: white; 
        padding: 12px 15px; border-radius: 8px; font-size: 14px; width: 100%; transition: 0.3s;
    }
    .v-input:focus { border-color: var(--v-accent); outline: none; box-shadow: 0 0 10px rgba(0, 255, 136, 0.1); }

    .v-btn-primary { 
        background: var(--v-accent); color: #0d1117; border: none; padding: 12px 25px; 
        border-radius: 8px; font-weight: 800; cursor: pointer; text-transform: uppercase; font-size: 12px; transition: 0.3s;
    }
    .v-btn-primary:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0, 255, 136, 0.3); }

    .v-table { width: 100%; border-collapse: collapse; margin-top: 10px; }
    .v-table th { padding: 15px; color: var(--v-text-gray); font-size: 10px; text-transform: uppercase; letter-spacing: 1px; border-bottom: 1px solid var(--v-border); }
    .v-table td { padding: 18px 15px; border-bottom: 1px solid var(--v-border); vertical-align: middle; }

    .badge-global { background: rgba(0, 255, 136, 0.1); color: var(--v-accent); padding: 4px 10px; border-radius: 6px; font-size: 10px; font-weight: 800; }
    .badge-game { background: rgba(56, 139, 253, 0.1); color: #388bfd; padding: 4px 10px; border-radius: 6px; font-size: 10px; font-weight: 800; }

    .action-link { text-decoration: none; font-size: 12px; font-weight: 700; transition: 0.2s; }
    .delete-link { color: var(--v-red); opacity: 0.7; }
    .delete-link:hover { opacity: 1; text-shadow: 0 0 10px rgba(255, 77, 77, 0.3); }
</style>

<div class="v-container">
    
    <div class="v-header">
        <div>
            <h1 class="v-title">CATEGORY <span>MANAGER</span></h1>
            <p style="color: var(--v-text-gray); font-size: 13px; margin-top: 5px;">Configure global and specific item tags</p>
        </div>
        <a href="index.php" class="action-link" style="color: var(--v-accent);">
            <i class="fa-solid fa-arrow-left"></i> BACK TO DASHBOARD
        </a>
    </div>

    <div class="v-card">
        <form method="POST" style="display: grid; grid-template-columns: 1fr 1fr auto; gap: 20px; align-items: flex-end;">
            <div>
                <label style="display: block; font-size: 10px; color: var(--v-text-gray); margin-bottom: 8px; text-transform: uppercase; font-weight: 800;">Name</label>
                <input type="text" name="name" class="v-input" placeholder="e.g. Accounts, Currency..." required>
            </div>
            <div>
                <label style="display: block; font-size: 10px; color: var(--v-text-gray); margin-bottom: 8px; text-transform: uppercase; font-weight: 800;">Target Game</label>
                <select name="game_id" class="v-input">
                    <option value="global">GLOBAL (ALL GAMES)</option>
                    <?php foreach($games as $g): ?>
                        <option value="<?= $g['id'] ?>"><?= htmlspecialchars($g['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <button type="submit" name="add_category" class="v-btn-primary">Add Category</button>
        </form>
    </div>

    <div class="v-card" style="padding: 0; overflow: hidden;">
        <table class="v-table">
            <thead>
                <tr>
                    <th style="text-align: left;">Scope</th>
                    <th style="text-align: left;">Category Name</th>
                    <th style="text-align: left;">System Slug</th>
                    <th style="text-align: right;">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($categories as $c): ?>
                <tr onmouseover="this.style.background='rgba(255,255,255,0.01)'" onmouseout="this.style.background='transparent'">
                    <td>
                        <span class="<?= $c['game_id'] ? 'badge-game' : 'badge-global' ?>">
                            <?= htmlspecialchars($c['game_name']) ?>
                        </span>
                    </td>
                    <td>
                        <form method="POST" style="display: flex; align-items: center; gap: 10px;">
                            <input type="hidden" name="cat_id" value="<?= $c['id'] ?>">
                            <input type="text" name="new_name" value="<?= htmlspecialchars($c['name']) ?>" 
                                   class="v-input" 
                                   style="background: transparent; border: 1px solid transparent; padding: 5px; width: auto; font-weight: 600;"
                                   onfocus="this.style.background='#0d1117'; this.style.borderColor='var(--v-border)'"
                                   onblur="if(this.value == '<?= addslashes($c['name']) ?>') { this.style.background='transparent'; this.style.borderColor='transparent'; }">
                            <button type="submit" name="edit_category" style="background: none; border: none; color: var(--v-text-gray); cursor: pointer;" title="Update Name">
                                <i class="fa-solid fa-floppy-disk"></i>
                            </button>
                        </form>
                    </td>
                    <td style="font-family: monospace; color: var(--v-text-gray); font-size: 13px;">
                        /<?= $c['slug'] ?>
                    </td>
                    <td style="text-align: right;">
                        <a href="categories.php?delete=<?= $c['id'] ?>" class="action-link delete-link" onclick="return confirm('Delete this category? Products might lose their assignment.')">
                            <i class="fa-solid fa-trash-can"></i> DELETE
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

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