<?php
session_start();
if (!isset($_SESSION['admin'])) {
    header('Location: login.php');
    exit();
}
include 'db.php';
include 'upload_helper.php';

$message = '';

function get_admin_icon($path)
{
    if (empty($path))
        return '';
    if (filter_var($path, FILTER_VALIDATE_URL))
        return $path;
    $iconName = basename($path);
    return '../../assets/icons/' . $iconName;
}

if (isset($_POST['add_game'])) {
    $game_name = $_POST['game_name'];
    $game_description = $_POST['game_description'];
    $release_date = $_POST['release_date'];
    $game_type = $_POST['game_type'] ?? 'native';
    $package_name = $_POST['package_name'] ?? '';
    $category = $_POST['category'] ?? '';
    $is_recommended = isset($_POST['is_recommended']) ? 1 : 0;

    // Handle Icon Upload
    try {
        // Handle Hero Slider Video
        $hero_video = null;
        if ($category === 'slider' && isset($_FILES['hero_video_file']) && $_FILES['hero_video_file']['error'] === UPLOAD_ERR_OK) {
            $videoUpload = handleFileUpload($_FILES['hero_video_file'], '../../assets/videos/', ['mp4', 'webm', 'mov']);
            if ($videoUpload['status'] === 'success') {
                $hero_video = $videoUpload['fileName'];
            } else {
                throw new Exception("Hero Video Error: " . $videoUpload['message']);
            }
        }

        // Handle Icon Upload
        $iconUpload = handleFileUpload($_FILES['game_icon'], '../../assets/icons/', ['png', 'jpg', 'jpeg', 'webp']);
        if ($iconUpload['status'] === 'error') {
            throw new Exception("Icon Error: " . $iconUpload['message']);
        }
        $game_icon = $iconUpload['fileName'];

        // Handle Download Link / APK Upload
        $download_link = '';
        if ($game_type === 'native' && isset($_FILES['download_file']) && $_FILES['download_file']['error'] === UPLOAD_ERR_OK) {
            $apkUpload = handleFileUpload($_FILES['download_file'], '../../uploads/', ['apk']);
            if ($apkUpload['status'] === 'success') {
                $download_link = $apkUpload['fileName'];
            } else {
                throw new Exception("APK Error: " . $apkUpload['message']);
            }
        } else {
            $download_link = $_POST['download_url'] ?? '';
        }

        // Insert into games table
        $stmt = $conn->prepare("INSERT INTO games (game_name, game_description, game_icon, download_link, release_date, game_type, package_name, is_recommended, hero_video) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        if (!$stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }

        $stmt->bind_param("sssssssis", $game_name, $game_description, $game_icon, $download_link, $release_date, $game_type, $package_name, $is_recommended, $hero_video);

        if ($stmt->execute()) {
            $game_id = $stmt->insert_id;

            // If a category is selected, add to game_categories
            if (!empty($category)) {
                $stmt_cat = $conn->prepare("INSERT INTO game_categories (game_id, category) VALUES (?, ?)");
                if ($stmt_cat) {
                    $stmt_cat->bind_param("is", $game_id, $category);
                    if (!$stmt_cat->execute()) {
                        $message .= "<div class='alert alert-warning'>Game added, but category assignment failed: " . $stmt_cat->error . "</div>";
                    }
                    $stmt_cat->close();
                } else {
                    $message .= "<div class='alert alert-warning'>Game added, but category assignment failed: Table 'game_categories' missing or corrupted.</div>";
                }
            }

            if (empty($message)) {
                $message = "<div class='alert alert-success'>New game added successfully!</div>";
            }
        } else {
            throw new Exception("Execute failed: " . $stmt->error);
        }
        $stmt->close();
    } catch (Exception $e) {
        $message = "<div class='alert alert-danger'>Error: " . $e->getMessage() . "</div>";
    }
}

// Fetch games from the database
$gamesQuery = "SELECT * FROM games ORDER BY game_id DESC";
$gamesResult = $conn->query($gamesQuery);
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Games</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f0f4f8;
        }

        .sidebar {
            background-color: #343a40;
            min-height: 100vh;
            padding-top: 20px;
        }

        .sidebar a {
            color: #fff;
            text-decoration: none;
            padding: 10px;
            display: block;
            border-radius: 5px;
            margin: 5px;
            transition: background-color 0.3s;
        }

        .sidebar a:hover {
            background-color: #007bff;
        }

        .content {
            margin-left: 20px;
            padding: 30px;
        }

        h2,
        h4 {
            color: #343a40;
        }

        .game-table {
            margin-top: 20px;
        }

        .btn-success {
            margin-top: 10px;
        }
    </style>
</head>

<body>
    <div class="d-flex">
        <!-- Sidebar -->
        <div class="sidebar col-md-2">
            <h3 class="text-center text-white">Admin Panel</h3>
            <a href="index.php">Dashboard</a>
            <a href="games.php">Manage Games</a>
            <a href="game_categories.php">Manage Categories</a>
            <a href="leaderboard.php">Leaderboard</a>
            <a href="events.php">Manage Events</a>
            <a href="profile_management.php">Profile Management</a>
            <a href="logout.php">Logout</a>
        </div>

        <!-- Main Content -->
        <div class="content col-md-10">
            <div class="container py-5">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h2>Manage Games</h2>
                    <a href="repair_links.php" class="btn btn-info text-white">Repair Broken Links</a>
                </div>
                <?php echo $message; ?>

                <!-- Add Game Form -->
                <div class="card p-4 shadow-sm">
                    <form method="post" enctype="multipart/form-data">
                        <h4>Add New Game</h4>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="game_name" class="form-label">Game Name</label>
                                <input type="text" class="form-control" id="game_name" name="game_name" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="release_date" class="form-label">Release Date</label>
                                <input type="date" class="form-control" id="release_date" name="release_date" required>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="game_description" class="form-label">Game Description</label>
                            <textarea class="form-control" id="game_description" name="game_description" rows="3"
                                required></textarea>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="game_icon" class="form-label">Game Icon (Square Image)</label>
                                <input type="file" class="form-control" id="game_icon" name="game_icon" accept="image/*"
                                    required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="category" class="form-label">App Section</label>
                                <select name="category" id="app_section" class="form-select"
                                    onchange="toggleHeroVideoField()">
                                    <option value="">None (Standard List)</option>
                                    <option value="slider">Hero Slider (Top Banner)</option>
                                    <option value="trending">Trending Games</option>
                                    <option value="instant">Instant Games (Home Section)</option>
                                    <option value="editor_choice">Editor's Choice</option>
                                    <option value="upcoming">Upcoming Titles</option>
                                </select>
                            </div>
                        </div>
                        <div class="mb-3 d-none" id="hero_video_field">
                            <label for="hero_video_file" class="form-label text-primary"><strong>Hero Slider Promotional
                                    Video (Recommended)</strong></label>
                            <input type="file" class="form-control border-primary" id="hero_video_file"
                                name="hero_video_file" accept="video/*">
                            <small class="text-muted">This video will show on the left side of the Hero Slider.</small>
                        </div>
                        <div class="mb-3 form-check">
                            <input type="checkbox" class="form-check-input" id="is_recommended" name="is_recommended">
                            <label class="form-check-label" for="is_recommended">Mark as Recommended for You</label>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="game_type" class="form-label">Game Type</label>
                                <select name="game_type" id="game_type" class="form-select"
                                    onchange="toggleTypeFields()">
                                    <option value="native">Native (APK)</option>
                                    <option value="instant">Instant (Web Link)</option>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="package_name" class="form-label">Package Name (e.g. com.game.racer)</label>
                                <input type="text" class="form-control" id="package_name" name="package_name">
                            </div>
                        </div>
                        <div class="mb-3" id="apk_field">
                            <label for="download_file" class="form-label">Upload APK File</label>
                            <input type="file" class="form-control" id="download_file" name="download_file"
                                accept=".apk">
                        </div>
                        <div class="mb-3 d-none" id="url_field">
                            <label for="download_url" class="form-label">Game Website URL</label>
                            <input type="url" class="form-control" id="download_url" name="download_url">
                        </div>

                        <button type="submit" name="add_game" class="btn btn-success">Add Game</button>
                    </form>
                </div>

                <hr class="my-5">

                <!-- Existing Games Table -->
                <h4>Existing Games</h4>
                <div class="table-responsive">
                    <table class="table table-hover table-bordered bg-white rounded shadow-sm">
                        <thead class="table-dark">
                            <tr>
                                <th>Icon</th>
                                <th>Game Name</th>
                                <th>Type</th>
                                <th>Stats</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($game = $gamesResult->fetch_assoc()) {
                                ?>
                                <?php
                                $icon = get_admin_icon($game['game_icon']);
                                ?>
                                <tr class="align-middle">
                                    <td><img src="<?php echo $icon; ?>" alt="Icon" width="50" class="rounded"></td>
                                    <td>
                                        <strong><?php echo htmlspecialchars($game['game_name']); ?></strong>
                                        <?php if (isset($game['is_recommended']) && $game['is_recommended']): ?>
                                            <span class="badge bg-success ms-1">Recommended</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><span
                                            class="badge bg-secondary"><?php echo strtoupper($game['game_type']); ?></span>
                                    </td>
                                    <td>
                                        <small>Plays: <?php echo number_format($game['plays'] ?? 0); ?></small><br>
                                        <small>Downloads: <?php echo number_format($game['downloads'] ?? 0); ?></small>
                                    </td>
                                    <td>
                                        <a href="edit_game.php?id=<?php echo $game['game_id']; ?>"
                                            class="btn btn-sm btn-warning">Edit</a>
                                        <a href="delete_game.php?id=<?php echo $game['game_id']; ?>"
                                            class="btn btn-sm btn-danger"
                                            onclick="return confirm('Delete this game?')">Delete</a>
                                    </td>
                                </tr>
                            <?php } ?>
                        </tbody>
                    </table>
                </div>

                <a href="logout.php" class="btn btn-outline-danger mt-3">Logout</a>
            </div>
        </div>
    </div>

    <script>
        function toggleHeroVideoField() {
            const section = document.getElementById('app_section').value;
            const heroVideoField = document.getElementById('hero_video_field');
            if (section === 'slider') {
                heroVideoField.classList.remove('d-none');
            } else {
                heroVideoField.classList.add('d-none');
            }
        }

        function toggleTypeFields() {
            const type = document.getElementById('game_type').value;
            const apkField = document.getElementById('apk_field');
            const urlField = document.getElementById('url_field');
            if (type === 'native') {
                apkField.classList.remove('d-none');
                urlField.classList.add('d-none');
            } else {
                apkField.classList.add('d-none');
                urlField.classList.remove('d-none');
            }
        }
    </script>
</body>

</html>