<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once '../config.php';

// Auth Check
if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit;
}

global $pdo;
$message = '';
$msg_type = 'success';

// ==========================================
// AUTO-GENERATE PHP FILE FUNCTION
// ==========================================
function generateGameFile($game_file_name) {
    if(empty($game_file_name)) return;
    
    $games_folder = __DIR__ . '/../games/';
    if (!file_exists($games_folder)) {
        @mkdir($games_folder, 0777, true);
    }
    
    $new_file_path = $games_folder . $game_file_name . '.php';
    
    if(!file_exists($new_file_path)) {
        $content = "<?php\n";
        $content .= "session_start();\n";
        $content .= "require_once __DIR__ . '/../config.php';\n";
        $content .= "\$game_id = isset(\$_GET['id']) ? (int)\$_GET['id'] : 0;\n";
        $content .= "?>\n";
        $content .= "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n";
        $content .= "    <meta charset=\"UTF-8\">\n";
        $content .= "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n";
        $content .= "    <title>Play Game</title>\n";
        $content .= "    <link href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css\" rel=\"stylesheet\">\n";
        $content .= "    <style>body { background-color: #0f172a; color: #fff; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }</style>\n";
        $content .= "</head>\n<body>\n";
        $content .= "    <div class=\"text-center\">\n";
        $content .= "        <h2 class=\"text-warning fw-bold\">" . strtoupper(str_replace('_', ' ', $game_file_name)) . "</h2>\n";
        $content .= "        <p class=\"text-muted\">Game ID: <?php echo \$game_id; ?></p>\n";
        $content .= "        <hr class=\"border-secondary\">\n";
        $content .= "        <div class=\"alert alert-info bg-dark border-info text-info d-inline-block shadow\">\n";
        $content .= "            File Automatically Generated at <b>/games/".$game_file_name.".php</b><br>Write your game logic here.\n";
        $content .= "        </div><br>\n";
        $content .= "        <a href=\"../index.php\" class=\"btn btn-danger mt-3 fw-bold px-4 rounded-pill\">Exit Game</a>\n";
        $content .= "    </div>\n";
        $content .= "</body>\n</html>";
        
        file_put_contents($new_file_path, $content);
    }
}

// ==========================================
// 1. DELETE GAME
// ==========================================
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    $stmt = $pdo->prepare("SELECT image FROM games WHERE id = ?");
    $stmt->execute([$id]);
    $img = $stmt->fetchColumn();
    
    if($img && $img != 'default-game.png' && file_exists("../assets/images/games/" . $img)) {
        unlink("../assets/images/games/" . $img);
    }
    
    $pdo->prepare("DELETE FROM games WHERE id = ?")->execute([$id]);
    $message = "Game Deleted Permanently!";
    $msg_type = 'error';
}

// ==========================================
// 2. ADD NEW GAME
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_game'])) {
    $name = trim($_POST['name']);
    $slug = strtolower(str_replace(' ', '-', $name)) . '-' . rand(100,999);
    $category_id = $_POST['category_id'];
    $type = $_POST['type']; 
    
    $game_file_input = !empty($_POST['game_file']) ? strtolower(trim($_POST['game_file'])) : '';
    $game_file_input = str_replace('.php', '', $game_file_input);
    $game_file = preg_replace('/[^a-z0-9_]/', '', $game_file_input);
    
    $imageName = 'default-game.png';
    
    if (!empty($_FILES['image']['name'])) {
        $targetDir = "../assets/images/games/";
        if (!file_exists($targetDir)) mkdir($targetDir, 0777, true);
        $imageName = time() . '_' . preg_replace('/[^a-zA-Z0-9.]/', '_', basename($_FILES['image']['name']));
        move_uploaded_file($_FILES['image']['tmp_name'], $targetDir . $imageName);
    }

    $stmt = $pdo->prepare("INSERT INTO games (category_id, name, slug, type, game_file, image, is_active) VALUES (?, ?, ?, ?, ?, ?, 1)");
    $stmt->execute([$category_id, $name, $slug, $type, $game_file, $imageName]);
    
    if(!empty($game_file)) generateGameFile($game_file);
    
    $message = "New Game Added Successfully!";
}

// ==========================================
// 3. EDIT / UPDATE GAME
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_game'])) {
    $id = $_POST['game_id'];
    $name = trim($_POST['name']);
    $category_id = $_POST['category_id'];
    $type = $_POST['type'];
    
    $game_file_input = !empty($_POST['game_file']) ? strtolower(trim($_POST['game_file'])) : '';
    $game_file_input = str_replace('.php', '', $game_file_input);
    $game_file = preg_replace('/[^a-z0-9_]/', '', $game_file_input);

    if (!empty($_FILES['image']['name'])) {
        $targetDir = "../assets/images/games/";
        if (!file_exists($targetDir)) mkdir($targetDir, 0777, true);
        $imageName = time() . '_' . preg_replace('/[^a-zA-Z0-9.]/', '_', basename($_FILES['image']['name']));
        move_uploaded_file($_FILES['image']['tmp_name'], $targetDir . $imageName);
        
        $stmt = $pdo->prepare("UPDATE games SET name=?, category_id=?, type=?, game_file=?, image=? WHERE id=?");
        $stmt->execute([$name, $category_id, $type, $game_file, $imageName, $id]);
    } else {
        $stmt = $pdo->prepare("UPDATE games SET name=?, category_id=?, type=?, game_file=? WHERE id=?");
        $stmt->execute([$name, $category_id, $type, $game_file, $id]);
    }
    
    if(!empty($game_file)) generateGameFile($game_file);

    $message = "Game Updated Successfully!";
}

// ==========================================
// FETCH DATA FOR DISPLAY
// ==========================================
$categories = $pdo->query("SELECT id, name FROM categories WHERE is_active = 1")->fetchAll();
$games = $pdo->query("
    SELECT games.*, categories.name as cat_name 
    FROM games 
    LEFT JOIN categories ON games.category_id = categories.id 
    ORDER BY games.id DESC
")->fetchAll();

$pageTitle = "Manage Games";
require_once 'includes/header.php';
?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
    body { background-color: #f4f7f6; }
    .game-img { width: 55px; height: 55px; object-fit: cover; border-radius: 12px; box-shadow: 0 4px 10px rgba(0,0,0,0.1); border: 2px solid #fff;}
    .fallback-box { width: 55px; height: 55px; border-radius: 12px; background: linear-gradient(135deg, #74b9ff, #0984e3); display: flex; align-items: center; justify-content: center; color: white; border: 2px solid #fff; box-shadow: 0 4px 10px rgba(0,0,0,0.1);}
    
    /* Modern Cards */
    .card-modern { border: none; border-radius: 16px; box-shadow: 0 10px 30px rgba(0,0,0,0.04); overflow: hidden; background: #fff;}
    .card-modern-header { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 15px 20px; border: none; }
    
    /* Inputs */
    .form-control, .form-select { border-radius: 10px; border: 1px solid #e2e8f0; padding: 10px 15px; font-size: 14px; background-color: #f8fafc; }
    .form-control:focus, .form-select:focus { background-color: #fff; box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.15); border-color: #667eea;}
    
    /* Responsive Table */
    .table-hover tbody tr:hover { background-color: #f8fafc; transform: scale(1.002); transition: 0.2s;}
    .table td, .table th { padding: 15px; vertical-align: middle; border-bottom: 1px solid #f1f5f9;}
    
    .btn-gradient { background: linear-gradient(135deg, #00b09b, #96c93d); color: white; border: none;}
    .btn-gradient:hover { background: linear-gradient(135deg, #96c93d, #00b09b); color: white; transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,176,155,0.3);}
</style>

<?php if($message): ?>
<script>
    document.addEventListener("DOMContentLoaded", function() {
        Swal.fire({
            toast: true, position: 'top-end', icon: '<?= $msg_type ?>', 
            title: '<?= addslashes($message) ?>', showConfirmButton: false, timer: 3000
        });
    });
</script>
<?php endif; ?>

<div class="container-fluid px-3 py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="fw-bold text-dark mb-0"><i class="fas fa-gamepad text-primary me-2"></i> Games Directory</h4>
    </div>

    <div class="card card-modern mb-5">
        <div class="card-modern-header d-flex align-items-center">
            <h6 class="m-0 fw-bold"><i class="fas fa-plus-circle me-2"></i> Add New Game</h6>
        </div>
        <div class="card-body p-4">
            <form method="POST" enctype="multipart/form-data" class="row g-3 align-items-start">
                <input type="hidden" name="add_game" value="1">
                
                <div class="col-xl-2 col-lg-3 col-md-6 col-12">
                    <label class="form-label fw-bold text-muted small text-uppercase">Game Name *</label>
                    <input type="text" name="name" class="form-control fw-bold" placeholder="e.g. Aviator Pro" required>
                </div>
                
                <div class="col-xl-2 col-lg-3 col-md-6 col-12">
                    <label class="form-label fw-bold text-muted small text-uppercase">Category *</label>
                    <select name="category_id" class="form-select fw-bold" required>
                        <option value="">Select...</option>
                        <?php foreach($categories as $cat): ?>
                            <option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-xl-2 col-lg-3 col-md-6 col-12">
                    <label class="form-label fw-bold text-muted small text-uppercase">Game Engine *</label>
                    <select name="type" class="form-select fw-bold" required>
                        <option value="wingo">Wingo (Color)</option>
                        <option value="aviator">Aviator (Crash)</option>
                        <option value="slots">Slots</option>
                        <option value="custom">Other Custom</option>
                    </select>
                </div>

                <div class="col-xl-2 col-lg-3 col-md-6 col-12">
                    <label class="form-label fw-bold text-danger small text-uppercase">File Name (Auto-Create)</label>
                    <input type="text" name="game_file" class="form-control fw-bold" placeholder="e.g. mines">
                </div>
                
                <div class="col-xl-2 col-lg-6 col-md-6 col-12">
                    <label class="form-label fw-bold text-muted small text-uppercase">Thumbnail *</label>
                    <input type="file" name="image" class="form-control" accept="image/png, image/jpeg, image/webp" required>
                </div>
                
                <div class="col-xl-2 col-lg-6 col-md-6 col-12 mt-md-4 pt-md-2 mt-4">
                    <button type="submit" class="btn btn-gradient w-100 fw-bold py-2 rounded-pill shadow-sm">
                        <i class="fas fa-plus me-1"></i> Add Game
                    </button>
                </div>
            </form>
            <div class="mt-3 text-muted bg-light p-2 rounded-3 border" style="font-size: 12px;">
                <i class="fas fa-info-circle text-danger me-1"></i> <b>Pro Tip:</b> Type <b>mines</b> in File Name, and the system will automatically create <code>/games/mines.php</code> for you!
            </div>
        </div>
    </div>

    <div class="card card-modern">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle m-0">
                    <thead class="table-light">
                        <tr>
                            <th class="ps-4 text-muted small text-uppercase">Game</th>
                            <th class="text-muted small text-uppercase">Name & Category</th>
                            <th class="text-muted small text-uppercase">Engine</th>
                            <th class="text-muted small text-uppercase">File Route</th>
                            <th class="pe-4 text-end text-muted small text-uppercase">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(!empty($games)): foreach($games as $g): ?>
                        <tr>
                            <td class="ps-4">
                                <?php if(!empty($g['image']) && $g['image'] != 'default-game.png'): ?>
                                    <img src="../assets/images/games/<?= htmlspecialchars($g['image']) ?>" class="game-img" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
                                    <div class="fallback-box" style="display:none;"><i class="fas fa-gamepad"></i></div>
                                <?php else: ?>
                                    <div class="fallback-box"><i class="fas fa-gamepad"></i></div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="fw-bold text-dark fs-6"><?= htmlspecialchars($g['name']) ?></div>
                                <span class="badge bg-secondary bg-opacity-10 text-secondary border mt-1">
                                    <i class="fas fa-tag me-1"></i> <?= htmlspecialchars($g['cat_name'] ?? 'Uncategorized') ?>
                                </span>
                            </td>
                            <td><span class="badge bg-primary bg-opacity-10 text-primary border text-uppercase px-3 py-2 rounded-pill"><?= htmlspecialchars($g['type']) ?></span></td>
                            <td>
                                <code class="text-danger fw-bold bg-danger bg-opacity-10 px-2 py-1 rounded">/games/<?= htmlspecialchars(!empty($g['game_file']) ? $g['game_file'] : $g['type']) ?>.php</code>
                            </td>
                            <td class="pe-4 text-end">
                                <button class="btn btn-light border text-primary fw-bold btn-sm rounded-pill px-3 shadow-sm edit-btn me-1 hover-lift"
                                    data-id="<?= $g['id'] ?>"
                                    data-name="<?= htmlspecialchars($g['name']) ?>"
                                    data-cat="<?= $g['category_id'] ?>"
                                    data-type="<?= $g['type'] ?>"
                                    data-file="<?= htmlspecialchars($g['game_file'] ?? '') ?>">
                                    <i class="fas fa-edit"></i> Edit
                                </button>
                                
                                <button class="btn btn-light border text-danger fw-bold btn-sm rounded-pill px-3 shadow-sm hover-lift" onclick="confirmDelete(<?= $g['id'] ?>)">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; else: ?>
                        <tr><td colspan="5" class="text-center text-muted py-5"><i class="fas fa-box-open mb-3 display-4 opacity-25 d-block"></i>No Games found in database.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="editGameModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg rounded-4 overflow-hidden">
            <div class="modal-header bg-light border-0 py-3 px-4">
                <h5 class="modal-title fw-bold text-dark"><i class="fas fa-pen-square text-primary me-2"></i> Edit Game Details</h5>
                <button type="button" class="btn-close shadow-none" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" enctype="multipart/form-data">
                <div class="modal-body p-4">
                    <input type="hidden" name="edit_game" value="1">
                    <input type="hidden" name="game_id" id="edit_game_id">
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold text-muted small text-uppercase">Game Name</label>
                        <input type="text" name="name" id="edit_name" class="form-control fw-bold" required>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold text-muted small text-uppercase">Category</label>
                            <select name="category_id" id="edit_category_id" class="form-select fw-bold" required>
                                <?php foreach($categories as $cat): ?>
                                    <option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold text-muted small text-uppercase">Game Engine</label>
                            <select name="type" id="edit_type" class="form-select fw-bold" required>
                                <option value="wingo">Wingo (Color)</option>
                                <option value="aviator">Aviator (Crash)</option>
                                <option value="slots">Slots</option>
                                <option value="custom">Other Custom</option>
                            </select>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold text-danger small text-uppercase">File Name (URL Route)</label>
                        <input type="text" name="game_file" id="edit_game_file" class="form-control fw-bold border-danger border-opacity-50" placeholder="e.g. mines">
                        <small class="text-muted d-block mt-1" style="font-size: 11px;">Changing this will create a new file if it doesn't exist.</small>
                    </div>
                    
                    <div class="mb-2">
                        <label class="form-label fw-bold text-muted small text-uppercase">Upload New Thumbnail</label>
                        <input type="file" name="image" class="form-control" accept="image/png, image/jpeg, image/jpg, image/webp">
                        <small class="text-muted d-block mt-1" style="font-size: 11px;">Leave empty to keep the current image.</small>
                    </div>
                </div>
                <div class="modal-footer bg-light border-0 py-3 px-4">
                    <button type="button" class="btn btn-light border fw-bold rounded-pill px-4" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary fw-bold rounded-pill px-4 shadow-sm"><i class="fas fa-save me-1"></i> Update Game</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
// ==========================================
// FIXED EDIT MODAL LOGIC (Using Data Attributes)
// ==========================================
document.addEventListener('DOMContentLoaded', function() {
    const editButtons = document.querySelectorAll('.edit-btn');
    
    editButtons.forEach(button => {
        button.addEventListener('click', function() {
            // Get data from attributes (Safest method)
            const id = this.getAttribute('data-id');
            const name = this.getAttribute('data-name');
            const catId = this.getAttribute('data-cat');
            const type = this.getAttribute('data-type');
            const file = this.getAttribute('data-file');
            
            // Set values in modal
            document.getElementById('edit_game_id').value = id;
            document.getElementById('edit_name').value = name;
            document.getElementById('edit_category_id').value = catId;
            document.getElementById('edit_type').value = type;
            document.getElementById('edit_game_file').value = file;
            
            // Show modal safely
            var myModal = new bootstrap.Modal(document.getElementById('editGameModal'));
            myModal.show();
        });
    });
});

// Nice Delete Confirmation
function confirmDelete(id) {
    Swal.fire({
        title: 'Delete Game?',
        text: "You won't be able to revert this!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#e74c3c',
        cancelButtonColor: '#95a5a6',
        confirmButtonText: 'Yes, delete it!',
        borderRadius: '16px'
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = 'games.php?delete=' + id;
        }
    })
}
</script>

<style>
    .hover-lift { transition: transform 0.2s ease, box-shadow 0.2s ease; }
    .hover-lift:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0,0,0,0.1) !important; }
</style>

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