<?php
// admin/manage_display.php
session_start();
require '../includes/db.php'; 

// --- ACTIONS & LOGIC ---

// 1. Create Category
if (isset($_POST['add_cat'])) {
    $name = $conn->real_escape_string($_POST['cat_name']);
    $prio = (int)$_POST['priority'];
    $conn->query("INSERT INTO front_categories (name, priority) VALUES ('$name', '$prio')");
    header("Location: manage_display.php"); exit;
}

// 2. Update Category (Name & Priority)
if (isset($_POST['update_cat'])) {
    $cat_id = (int)$_POST['cat_id'];
    $name = $conn->real_escape_string($_POST['cat_name']);
    $prio = (int)$_POST['priority'];
    $conn->query("UPDATE front_categories SET name='$name', priority='$prio' WHERE id=$cat_id");
    header("Location: manage_display.php"); exit;
}

// 3. Delete Entire Category
if (isset($_GET['del_cat'])) {
    $id = (int)$_GET['del_cat'];
    $conn->query("DELETE FROM front_categories WHERE id=$id");
    $conn->query("DELETE FROM front_category_games WHERE category_id=$id");
    header("Location: manage_display.php"); exit;
}

// 4. Clear All Games from Category
if (isset($_GET['clear_cat'])) {
    $id = (int)$_GET['clear_cat'];
    $conn->query("DELETE FROM front_category_games WHERE category_id=$id");
    header("Location: manage_display.php"); exit;
}

// 5. BULK ADD GAMES (Search Result -> Category)
if (isset($_POST['bulk_add_games'])) {
    if(!empty($_POST['games']) && !empty($_POST['target_cat'])) {
        $cat_id = (int)$_POST['target_cat'];
        $selected_games = $_POST['games']; // Array of game_uids

        foreach($selected_games as $game_uid) {
            $game_uid = $conn->real_escape_string($game_uid);
            // Check duplicate
            $chk = $conn->query("SELECT id FROM front_category_games WHERE category_id=$cat_id AND game_uid='$game_uid'");
            if($chk->num_rows == 0){
                $conn->query("INSERT INTO front_category_games (category_id, game_uid) VALUES ('$cat_id', '$game_uid')");
            }
        }
    }
    header("Location: manage_display.php"); exit;
}

// 6. Move Single Game
if (isset($_POST['move_game'])) {
    $map_id = (int)$_POST['map_id'];
    $new_cat_id = (int)$_POST['new_cat_id'];
    $conn->query("UPDATE front_category_games SET category_id=$new_cat_id WHERE id=$map_id");
    header("Location: manage_display.php"); exit;
}

// 7. Remove Single Game
if (isset($_GET['remove_game'])) {
    $id = (int)$_GET['remove_game'];
    $conn->query("DELETE FROM front_category_games WHERE id=$id");
    header("Location: manage_display.php"); exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Game Display Manager</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; background-color: #f3f4f6; }
        /* Mobile Responsive Table/Grid Tweaks */
        .game-img { object-fit: cover; aspect-ratio: 1/1; }
    </style>
</head>
<body class="text-gray-800">

<div class="flex h-screen overflow-hidden">
    
    <div class="hidden md:flex flex-col w-64 bg-gray-900 text-white">
        <?php include '../includes/sidebar_admin.php'; ?>
    </div>

    <div class="flex-1 flex flex-col overflow-hidden">
        
        <div class="md:hidden bg-gray-900 text-white p-4 flex justify-between items-center">
            <h1 class="font-bold">Game Manager</h1>
            <a href="dashboard.php" class="text-sm bg-blue-600 px-3 py-1 rounded">Back</a>
        </div>

        <div class="flex-1 overflow-y-auto p-4 lg:p-8">
            
            <div class="flex justify-between items-end mb-6 border-b pb-4">
                <div>
                    <h1 class="text-2xl font-bold text-gray-800">Frontend Game Manager</h1>
                    <p class="text-sm text-gray-500">Manage categories, priorities, and game allocations.</p>
                </div>
                <form method="post" class="flex gap-2 items-end">
                    <div>
                        <label class="text-xs font-bold text-gray-600">New Category</label>
                        <input type="text" name="cat_name" placeholder="Name (e.g. Slots)" class="border p-2 rounded text-sm w-40" required>
                    </div>
                    <div>
                        <label class="text-xs font-bold text-gray-600">Priority</label>
                        <input type="number" name="priority" placeholder="1" class="border p-2 rounded text-sm w-20" required>
                    </div>
                    <button type="submit" name="add_cat" class="bg-green-600 text-white px-4 py-2 rounded text-sm font-bold hover:bg-green-700">Create</button>
                </form>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-12 gap-6">
                
                <div class="lg:col-span-4 space-y-6">
                    <div class="bg-white p-4 rounded-lg shadow border-t-4 border-blue-600">
                        <h3 class="font-bold text-lg mb-3 flex items-center gap-2">
                            <i class="fas fa-search text-blue-600"></i> Search & Add Games
                        </h3>
                        
                        <form method="get" class="mb-4">
                            <div class="flex gap-2">
                                <input type="text" name="q" placeholder="Search game name..." class="w-full border p-2 rounded focus:ring-2 focus:ring-blue-500 outline-none" value="<?php echo $_GET['q'] ?? ''; ?>">
                                <button type="submit" class="bg-gray-800 text-white px-4 rounded hover:bg-black"><i class="fas fa-search"></i></button>
                            </div>
                        </form>

                        <?php if(isset($_GET['q']) && !empty($_GET['q'])): ?>
                            <form method="post">
                                <div class="max-h-[500px] overflow-y-auto border rounded bg-gray-50 p-2 mb-3">
                                    <?php 
                                    $q = $conn->real_escape_string($_GET['q']);
                                    $games = $conn->query("SELECT * FROM games WHERE name LIKE '%$q%' LIMIT 50");
                                    
                                    if($games->num_rows > 0):
                                        while($g = $games->fetch_assoc()): 
                                    ?>
                                        <div class="flex items-center gap-3 p-2 border-b last:border-0 hover:bg-white transition">
                                            <input type="checkbox" name="games[]" value="<?php echo $g['game_uid']; ?>" class="w-4 h-4 text-blue-600">
                                            <img src="<?php echo $g['image']; ?>" class="w-10 h-10 rounded object-cover bg-gray-200">
                                            <div class="flex-1 min-w-0">
                                                <p class="text-sm font-bold text-gray-800 truncate"><?php echo $g['name']; ?></p>
                                                <p class="text-xs text-gray-500"><?php echo $g['provider_id']; ?></p>
                                            </div>
                                        </div>
                                    <?php endwhile; else: ?>
                                        <p class="text-red-500 text-center py-4 text-sm">No games found.</p>
                                    <?php endif; ?>
                                </div>

                                <div class="bg-blue-50 p-3 rounded border border-blue-100">
                                    <label class="block text-xs font-bold text-gray-700 mb-1">Add Selected To:</label>
                                    <div class="flex gap-2">
                                        <select name="target_cat" class="w-full border p-2 rounded text-sm bg-white" required>
                                            <option value="">Select Category</option>
                                            <?php 
                                            $cats = $conn->query("SELECT * FROM front_categories ORDER BY priority ASC");
                                            while($c = $cats->fetch_assoc()){
                                                echo "<option value='{$c['id']}'>{$c['name']}</option>";
                                            }
                                            ?>
                                        </select>
                                        <button type="submit" name="bulk_add_games" class="bg-blue-600 text-white px-3 py-2 rounded text-sm font-bold whitespace-nowrap hover:bg-blue-700">
                                            <i class="fas fa-plus"></i> Add
                                        </button>
                                    </div>
                                </div>
                            </form>
                        <?php else: ?>
                            <p class="text-gray-400 text-sm text-center italic mt-10">Search for games to add them to categories.</p>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="lg:col-span-8 space-y-8">
                    
                    <?php 
                    // Fetch Categories again for display loop
                    $all_cats = $conn->query("SELECT * FROM front_categories ORDER BY priority ASC");
                    if($all_cats->num_rows > 0):
                        while($cat = $all_cats->fetch_assoc()): 
                            $cat_id = $cat['id'];
                    ?>
                        <div class="bg-white rounded-lg shadow-md border border-gray-200 overflow-hidden">
                            
                            <div class="bg-gray-100 p-3 flex flex-col md:flex-row justify-between items-center gap-3 border-b">
                                <form method="post" class="flex items-center gap-2 flex-1 w-full">
                                    <input type="hidden" name="cat_id" value="<?php echo $cat['id']; ?>">
                                    <div class="flex items-center gap-2 w-full md:w-auto">
                                        <span class="text-gray-500 font-mono text-xs">Prio:</span>
                                        <input type="number" name="priority" value="<?php echo $cat['priority']; ?>" class="w-12 p-1 border rounded text-center text-sm">
                                        <input type="text" name="cat_name" value="<?php echo $cat['name']; ?>" class="p-1 border rounded font-bold text-gray-800 flex-1 md:w-64 text-sm">
                                        <button type="submit" name="update_cat" class="text-blue-600 hover:text-blue-800" title="Save Changes"><i class="fas fa-save"></i></button>
                                    </div>
                                </form>
                                
                                <div class="flex gap-3 text-sm">
                                    <a href="?clear_cat=<?php echo $cat['id']; ?>" onclick="return confirm('Remove ALL games from this category?')" class="text-orange-500 hover:text-orange-700 flex items-center gap-1">
                                        <i class="fas fa-eraser"></i> Clear Games
                                    </a>
                                    <a href="?del_cat=<?php echo $cat['id']; ?>" onclick="return confirm('Delete category completely?')" class="text-red-500 hover:text-red-700 flex items-center gap-1 font-bold">
                                        <i class="fas fa-trash"></i> Delete
                                    </a>
                                </div>
                            </div>

                            <div class="p-4 bg-gray-50 min-h-[100px]">
                                <?php 
                                $c_games = $conn->query("
                                    SELECT fcg.id as map_id, fcg.category_id, g.name, g.image, g.game_uid 
                                    FROM front_category_games fcg 
                                    JOIN games g ON fcg.game_uid = g.game_uid 
                                    WHERE fcg.category_id = $cat_id
                                    ORDER BY fcg.id DESC
                                ");
                                
                                if($c_games->num_rows > 0):
                                ?>
                                    <div class="grid grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
                                        <?php while($item = $c_games->fetch_assoc()): ?>
                                            <div class="bg-white rounded border border-gray-200 p-2 relative group hover:shadow-lg transition">
                                                <img src="<?php echo $item['image']; ?>" class="w-full rounded game-img bg-gray-200">
                                                <p class="text-[10px] font-bold mt-1 truncate text-center"><?php echo $item['name']; ?></p>
                                                
                                                <div class="mt-2 flex gap-1">
                                                    <form method="post" class="flex-1">
                                                        <input type="hidden" name="map_id" value="<?php echo $item['map_id']; ?>">
                                                        <select name="new_cat_id" onchange="this.form.submit()" class="w-full text-[9px] border p-1 rounded bg-gray-100 hover:bg-gray-200 cursor-pointer">
                                                            <option value="">Move...</option>
                                                            <?php 
                                                            $all_cats_move = $conn->query("SELECT * FROM front_categories ORDER BY priority ASC");
                                                            while($mv = $all_cats_move->fetch_assoc()){
                                                                if($mv['id'] != $cat_id) {
                                                                    echo "<option value='{$mv['id']}'>to {$mv['name']}</option>";
                                                                }
                                                            }
                                                            ?>
                                                            <option value="" disabled>-----------</option>
                                                            <option name="move_game" value="<?php echo $cat_id; ?>">Stay Here</option>
                                                            <input type="hidden" name="move_game" value="1">
                                                        </select>
                                                    </form>
                                                    
                                                    <a href="?remove_game=<?php echo $item['map_id']; ?>" class="bg-red-100 text-red-600 w-6 h-6 flex items-center justify-center rounded hover:bg-red-600 hover:text-white transition" title="Remove Game">
                                                        <i class="fas fa-times text-xs"></i>
                                                    </a>
                                                </div>
                                            </div>
                                        <?php endwhile; ?>
                                    </div>
                                <?php else: ?>
                                    <div class="flex flex-col items-center justify-center py-6 text-gray-400 border-2 border-dashed border-gray-300 rounded">
                                        <i class="fas fa-ghost text-2xl mb-1"></i>
                                        <span class="text-sm">Empty Section</span>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endwhile; else: ?>
                        <div class="bg-white p-8 rounded shadow text-center">
                            <h2 class="text-xl font-bold text-gray-800">Welcome to Game Manager!</h2>
                            <p class="text-gray-500 mt-2">Start by creating a category (e.g. Popular, Slots) from the top form.</p>
                        </div>
                    <?php endif; ?>

                </div>
            </div>
        </div>
    </div>
</div>

</body>
</html>