<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/auth.php';

// Handle adding a game
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_game') {
    $name = trim($_POST['name']);
    $categories = isset($_POST['categories']) ? implode(',', (array)$_POST['categories']) : '';
    $link = trim($_POST['link']);
    $rtp = floatval($_POST['rtp']);
    $sort_order = intval($_POST['sort_order']);
    $is_popular = isset($_POST['is_popular']) ? 1 : 0;
    $is_top_rated = isset($_POST['is_top_rated']) ? 1 : 0;
    $is_best_choice = isset($_POST['is_best_choice']) ? 1 : 0;
    $badge_text = trim($_POST['badge_text']);
    $badge_color = trim($_POST['badge_color']);
    
    $image_url = '';
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = __DIR__ . '/../uploads/games/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        if (in_array($ext, $allowed)) {
            $filename = uniqid('game_') . '.' . $ext;
            if (move_uploaded_file($_FILES['image']['tmp_name'], $upload_dir . $filename)) {
                $image_url = '/uploads/games/' . $filename;
            }
        }
    }
    
    if (!empty($name) && !empty($image_url) && !empty($link)) {
        $stmt = $pdo->prepare("INSERT INTO games (name, categories, image_url, link, rtp, sort_order, is_popular, is_top_rated, is_best_choice, badge_text, badge_color) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$name, $categories, $image_url, $link, $rtp, $sort_order, $is_popular, $is_top_rated, $is_best_choice, $badge_text, $badge_color]);
        header("Location: games.php?msg=Game+Added");
        exit;
    } else {
        header("Location: games.php?msg=Error+Adding+Game+(Image+may+be+missing+or+invalid)");
        exit;
    }
}

// Handle editing a game
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'edit_game') {
    $id = intval($_POST['game_id']);
    $name = trim($_POST['name']);
    $categories = isset($_POST['categories']) ? implode(',', (array)$_POST['categories']) : '';
    $link = trim($_POST['link']);
    $rtp = floatval($_POST['rtp']);
    $sort_order = intval($_POST['sort_order']);
    $is_popular = isset($_POST['is_popular']) ? 1 : 0;
    $is_top_rated = isset($_POST['is_top_rated']) ? 1 : 0;
    $is_best_choice = isset($_POST['is_best_choice']) ? 1 : 0;
    $badge_text = trim($_POST['badge_text']);
    $badge_color = trim($_POST['badge_color']);
    
    // Fetch existing game
    $st = $pdo->prepare("SELECT image_url FROM games WHERE id = ?");
    $st->execute([$id]);
    $existing = $st->fetch();
    $image_url = $existing ? $existing['image_url'] : '';

    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = __DIR__ . '/../uploads/games/';
        if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
        $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        if (in_array($ext, $allowed)) {
            $filename = uniqid('game_') . '.' . $ext;
            if (move_uploaded_file($_FILES['image']['tmp_name'], $upload_dir . $filename)) {
                $image_url = '/uploads/games/' . $filename;
            }
        }
    }
    
    if (!empty($name) && !empty($link)) {
        $stmt = $pdo->prepare("UPDATE games SET name=?, categories=?, image_url=?, link=?, rtp=?, sort_order=?, is_popular=?, is_top_rated=?, is_best_choice=?, badge_text=?, badge_color=? WHERE id=?");
        $stmt->execute([$name, $categories, $image_url, $link, $rtp, $sort_order, $is_popular, $is_top_rated, $is_best_choice, $badge_text, $badge_color, $id]);
        header("Location: games.php?msg=Game+Updated");
        exit;
    }
}

// Handle deleting a game
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_game') {
    $id = intval($_POST['id']);
    $pdo->prepare("DELETE FROM games WHERE id = ?")->execute([$id]);
    header("Location: games.php?msg=Game+Deleted");
    exit;
}

// Fetch single game if editing
$edit_game = null;
if (isset($_GET['edit_id'])) {
    $edit_stmt = $pdo->prepare("SELECT * FROM games WHERE id = ?");
    $edit_stmt->execute([intval($_GET['edit_id'])]);
    $edit_game = $edit_stmt->fetch(PDO::FETCH_ASSOC);
}

// Get all games
$games_stmt = $pdo->query("SELECT * FROM games ORDER BY sort_order ASC, id DESC");
$games = $games_stmt ? $games_stmt->fetchAll(PDO::FETCH_ASSOC) : [];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Games Library — PakClub Admin</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{background:#0b0e18;color:#e8eaf0;font-family:'Segoe UI',sans-serif;display:flex;min-height:100vh}
.main{flex:1;overflow-x:hidden}
.topbar{background:#111827;border-bottom:1px solid rgba(255,255,255,.07);padding:16px 28px;display:flex;align-items:center;justify-content:space-between}
.topbar h2{font-size:20px;font-weight:700;color:#fff}
.content{padding:24px 28px}
.card{background:#1e2130;border:1px solid rgba(255,255,255,.07);border-radius:14px;overflow:hidden;overflow-x:auto;margin-bottom:24px}
.card-header{padding:16px 20px;border-bottom:1px solid rgba(255,255,255,.07);background:#181b28;display:flex;justify-content:space-between;align-items:center}
.card-title{font-size:16px;font-weight:600;color:#fff}
.card-body{padding:20px}

.form-group{margin-bottom:15px}
.form-group label{display:block;margin-bottom:6px;font-size:13px;color:#9ca3af;font-weight:500}
.form-control{width:100%;background:#0f1117;border:1px solid rgba(255,255,255,.1);border-radius:8px;padding:10px 14px;color:#fff;font-size:14px;outline:none;font-family:inherit}
.form-control:focus{border-color:#f26d0f}
.grid-2{display:grid;grid-template-columns:1fr 1fr;gap:15px}
.grid-3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:15px}
.grid-4{display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:15px}

.checkbox-wrap{display:flex;gap:15px;margin:15px 0 25px;flex-wrap:wrap}
.checkbox-item{display:flex;align-items:center;gap:6px;font-size:14px;color:#d1d5db;cursor:pointer}
.checkbox-item input{width:16px;height:16px;accent-color:#f26d0f}

.btn{padding:10px 18px;border-radius:10px;border:none;cursor:pointer;font-size:14px;font-weight:600;display:inline-flex;align-items:center;gap:7px;transition:opacity .2s;text-decoration:none}
.btn:hover{opacity:.85}
.btn-orange{background:#f26d0f;color:#fff}
.btn-blue{background:#3b82f6;color:#fff}
.btn-red{background:#ef4444;color:#fff}
.btn-gray{background:#374151;color:#fff}
.btn-sm{padding:6px 12px;font-size:12px;border-radius:7px}

table{width:100%;border-collapse:collapse;font-size:13px;min-width:800px;}
th{padding:11px 16px;color:#4b5563;font-size:11px;text-transform:uppercase;letter-spacing:.7px;border-bottom:1px solid rgba(255,255,255,.06);text-align:left;font-weight:600}
td{padding:12px 16px;border-bottom:1px solid rgba(255,255,255,.04);color:#c9ccd6;vertical-align:middle}
tr:last-child td{border-bottom:none}
tr:hover td{background:rgba(255,255,255,.02)}

.badge{padding:4px 8px;border-radius:4px;font-size:11px;font-weight:700;text-transform:uppercase}
.bg-danger{background:rgba(239,68,68,.15);color:#ef4444}
.bg-warning{background:rgba(245,158,11,.15);color:#f59e0b}
.bg-success{background:rgba(34,197,94,.15);color:#22c55e}
.bg-info{background:rgba(59,130,246,.15);color:#3b82f6}

.alert{padding:15px;background:rgba(34,197,94,.15);color:#22c55e;border-radius:10px;margin-bottom:20px;border:1px solid rgba(34,197,94,.3)}
</style>
</head>
<body>
<?php include 'sidebar.php'; ?>
<div class="main">
    <div class="topbar">
        <h2><i class="fa-solid fa-gamepad" style="color:#f26d0f;margin-right:10px"></i>Games Library</h2>
    </div>
    
    <div class="content">
        <?php if (isset($_GET['msg'])): ?>
            <div class="alert"><i class="fa-solid fa-check-circle"></i> <?php echo htmlspecialchars($_GET['msg']); ?></div>
        <?php endif; ?>

        <div class="card">
            <div class="card-header">
                <div class="card-title"><?php echo $edit_game ? 'Edit Game: ' . htmlspecialchars($edit_game['name']) : 'Add New Game'; ?></div>
            </div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data" action="games.php">
                    <?php if($edit_game): ?>
                        <input type="hidden" name="action" value="edit_game">
                        <input type="hidden" name="game_id" value="<?php echo $edit_game['id']; ?>">
                    <?php else: ?>
                        <input type="hidden" name="action" value="add_game">
                    <?php endif; ?>
                    
                    <div class="grid-2">
                        <div class="form-group">
                            <label>Game Name</label>
                            <input type="text" class="form-control" name="name" required placeholder="e.g. Aviator" value="<?php echo $edit_game ? htmlspecialchars($edit_game['name']) : ''; ?>">
                        </div>
                        <div class="form-group">
                            <label>Image Upload <?php if($edit_game) echo '<small style="color:#9ca3af">(Leave empty to keep current)</small>'; ?></label>
                            <input type="file" class="form-control" name="image" accept="image/*" <?php echo $edit_game ? '' : 'required'; ?> style="padding: 7px 14px;">
                            <?php if($edit_game && $edit_game['image_url']): ?>
                                <div style="margin-top: 8px;">
                                    <img src="<?php echo htmlspecialchars($edit_game['image_url']); ?>" style="height: 40px; border-radius: 4px;">
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div class="grid-2">
                        <div class="form-group">
                            <label>Game Link</label>
                            <input type="text" class="form-control" name="link" required placeholder="/Aviator/index.php" value="<?php echo $edit_game ? htmlspecialchars($edit_game['link']) : ''; ?>">
                        </div>
                        <div class="form-group">
                            <?php 
                            $selected_cats = $edit_game ? explode(',', $edit_game['categories']) : []; 
                            ?>
                            <label>Categories (Hold Ctrl to select multiple)</label>
                            <select multiple class="form-control" name="categories[]" required style="height:80px">
                                <option value="Popular" <?php echo in_array('Popular', $selected_cats) ? 'selected' : ''; ?>>Popular</option>
                                <option value="Top Rated" <?php echo in_array('Top Rated', $selected_cats) ? 'selected' : ''; ?>>Top Rated</option>
                                <option value="Best Choice" <?php echo in_array('Best Choice', $selected_cats) ? 'selected' : ''; ?>>Best Choice</option>
                                <option value="Lottery" <?php echo in_array('Lottery', $selected_cats) ? 'selected' : ''; ?>>Lottery</option>
                                <option value="Slots" <?php echo in_array('Slots', $selected_cats) ? 'selected' : ''; ?>>Slots</option>
                                <option value="Live Casino" <?php echo in_array('Live Casino', $selected_cats) ? 'selected' : ''; ?>>Live Casino</option>
                                <option value="Cards" <?php echo in_array('Cards', $selected_cats) ? 'selected' : ''; ?>>Cards</option>
                                <option value="Games" <?php echo in_array('Games', $selected_cats) ? 'selected' : ''; ?>>Games</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="grid-4">
                        <div class="form-group">
                            <label>RTP (%)</label>
                            <input type="number" step="0.01" class="form-control" name="rtp" required value="<?php echo $edit_game ? $edit_game['rtp'] : '98.00'; ?>">
                        </div>
                        <div class="form-group">
                            <label>Sort Order</label>
                            <input type="number" class="form-control" name="sort_order" required value="<?php echo $edit_game ? $edit_game['sort_order'] : '0'; ?>">
                        </div>
                        <div class="form-group">
                            <label>Badge Text</label>
                            <input type="text" class="form-control" name="badge_text" placeholder="e.g. Top1" value="<?php echo $edit_game ? htmlspecialchars($edit_game['badge_text']) : ''; ?>">
                        </div>
                        <div class="form-group">
                            <label>Badge Color</label>
                            <select class="form-control" name="badge_color">
                                <option value="badge-top" <?php echo ($edit_game && $edit_game['badge_color'] == 'badge-top') ? 'selected' : ''; ?>>Orange (top)</option>
                                <option value="badge-tb" <?php echo ($edit_game && $edit_game['badge_color'] == 'badge-tb') ? 'selected' : ''; ?>>Green (tb)</option>
                                <option value="badge-mg" <?php echo ($edit_game && $edit_game['badge_color'] == 'badge-mg') ? 'selected' : ''; ?>>Blue (mg)</option>
                                <option value="badge-jili" <?php echo ($edit_game && $edit_game['badge_color'] == 'badge-jili') ? 'selected' : ''; ?>>Purple (jili)</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="checkbox-wrap">
                        <label class="checkbox-item"><input type="checkbox" name="is_popular" <?php echo ($edit_game && $edit_game['is_popular']) ? 'checked' : ''; ?>> Is Popular</label>
                        <label class="checkbox-item"><input type="checkbox" name="is_top_rated" <?php echo ($edit_game && $edit_game['is_top_rated']) ? 'checked' : ''; ?>> Is Top Rated</label>
                        <label class="checkbox-item"><input type="checkbox" name="is_best_choice" <?php echo ($edit_game && $edit_game['is_best_choice']) ? 'checked' : ''; ?>> Is Best Choice</label>
                    </div>
                    
                    <button type="submit" class="btn btn-orange"><i class="fa-solid <?php echo $edit_game ? 'fa-save' : 'fa-plus'; ?>"></i> <?php echo $edit_game ? 'Update Game' : 'Add Game'; ?></button>
                    <?php if($edit_game): ?>
                        <a href="games.php" class="btn btn-gray" style="margin-left:8px;">Cancel</a>
                    <?php endif; ?>
                </form>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                <div class="card-title">Existing Games</div>
            </div>
            <table>
                <thead>
                    <tr>
                        <th>Order</th>
                        <th>Image</th>
                        <th>Name</th>
                        <th>Categories</th>
                        <th>RTP</th>
                        <th>Tags</th>
                        <th>Badge</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($games as $g): ?>
                    <tr>
                        <td><?php echo $g['sort_order']; ?></td>
                        <td><img src="<?php echo htmlspecialchars($g['image_url']); ?>" style="width:40px;height:40px;object-fit:cover;border-radius:8px;border:1px solid rgba(255,255,255,0.1)"></td>
                        <td style="font-weight:600;color:#fff"><?php echo htmlspecialchars($g['name']); ?></td>
                        <td><?php echo htmlspecialchars($g['categories']); ?></td>
                        <td style="color:#22c55e"><?php echo $g['rtp']; ?>%</td>
                        <td>
                            <?php if($g['is_popular']) echo '<span class="badge bg-danger">Pop</span> '; ?>
                            <?php if($g['is_top_rated']) echo '<span class="badge bg-warning">Top</span> '; ?>
                            <?php if($g['is_best_choice']) echo '<span class="badge bg-success">Best</span> '; ?>
                        </td>
                        <td>
                            <?php if($g['badge_text']): ?>
                                <span class="badge bg-info"><?php echo htmlspecialchars($g['badge_text']); ?></span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div style="display:flex;gap:6px">
                                <a href="games.php?edit_id=<?php echo $g['id']; ?>" class="btn btn-blue btn-sm"><i class="fa-solid fa-pen"></i> Edit</a>
                                <form method="POST" style="margin:0;">
                                    <input type="hidden" name="action" value="delete_game">
                                    <input type="hidden" name="id" value="<?php echo $g['id']; ?>">
                                    <button type="submit" class="btn btn-red btn-sm" onclick="return confirm('Delete this game?');"><i class="fa-solid fa-trash"></i> Delete</button>
                                </form>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if(empty($games)): ?>
                    <tr><td colspan="8" style="text-align:center;padding:30px;color:#9ca3af">No games found. Please add one.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

    </div>
</div>
</body>
</html>