<?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;
}

$game_id = $_GET['id'] ?? null;

if (!$game_id) {
    header("Location: games.php");
    exit();
}

// Fetch the game details
$stmt = $conn->prepare("SELECT g.*, gc.category FROM games g LEFT JOIN game_categories gc ON g.game_id = gc.game_id WHERE g.game_id = ?");
$stmt->bind_param("i", $game_id);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
    $game = $result->fetch_assoc();
} else {
    echo "Game not found!";
    exit();
}
$stmt->close();

// Handle form submission to update the game
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $game_name = $_POST['game_name'];
    $game_description = $_POST['game_description'];
    $release_date = $_POST['release_date'];
    $game_type = $_POST['game_type'];
    $package_name = $_POST['package_name'];
    $category = $_POST['category'];
    $is_recommended = isset($_POST['is_recommended']) ? 1 : 0;

    $game_icon = $game['game_icon'];
    $download_link = $game['download_link'];
    $hero_video = $game['hero_video'];

    // Handle Hero Slider Video
    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 Update
    try {
        if (isset($_FILES['game_icon']) && $_FILES['game_icon']['error'] === UPLOAD_ERR_OK) {
            $iconUpload = handleFileUpload($_FILES['game_icon'], '../../assets/icons/', ['png', 'jpg', 'jpeg', 'webp']);
            if ($iconUpload['status'] === 'success') {
                $game_icon = $iconUpload['fileName'];
            } else {
                throw new Exception("Icon Error: " . $iconUpload['message']);
            }
        } elseif (isset($_FILES['game_icon']) && $_FILES['game_icon']['error'] !== UPLOAD_ERR_NO_FILE) {
            // Handle other upload errors for icon
            $iconUpload = handleFileUpload($_FILES['game_icon'], '../../assets/icons/');
            throw new Exception("Icon Upload Error: " . $iconUpload['message']);
        }

        // Handle APK/Link Update
        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']);
            }
        } elseif ($game_type === 'native' && isset($_FILES['download_file']) && $_FILES['download_file']['error'] !== UPLOAD_ERR_NO_FILE) {
            $apkUpload = handleFileUpload($_FILES['download_file'], '../../uploads/', ['apk']);
            throw new Exception("APK Upload Error: " . $apkUpload['message']);
        } elseif ($game_type === 'instant') {
            $download_link = $_POST['download_url'];
        }

        if (empty($message)) {
            $update_stmt = $conn->prepare("UPDATE games SET game_name = ?, game_description = ?, game_icon = ?, download_link = ?, release_date = ?, game_type = ?, package_name = ?, is_recommended = ?, hero_video = ? WHERE game_id = ?");
            if (!$update_stmt) {
                throw new Exception("Prepare failed: " . $conn->error);
            }
            
            $update_stmt->bind_param("sssssssssi", $game_name, $game_description, $game_icon, $download_link, $release_date, $game_type, $package_name, $is_recommended, $hero_video, $game_id);

            if ($update_stmt->execute()) {
                // Update or Insert category
                $conn->query("DELETE FROM game_categories WHERE game_id = $game_id");
                
                if (!empty($category)) {
                    $cat_stmt = $conn->prepare("INSERT INTO game_categories (game_id, category) VALUES (?, ?)");
                    if ($cat_stmt) {
                        $cat_stmt->bind_param("is", $game_id, $category);
                        $cat_stmt->execute();
                        $cat_stmt->close();
                    }
                }

                header("Location: games.php?msg=updated");
                exit();
            } else {
                throw new Exception("Update failed: " . $update_stmt->error);
            }
            $update_stmt->close();
        }
    } catch (Exception $e) {
        $message = "<div class='alert alert-danger'>Error: " . $e->getMessage() . "</div>";
    }
}
?>

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Game - <?php echo htmlspecialchars($game['game_name']); ?></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 {
            padding: 30px;
        }

        .btn-update {
            background: linear-gradient(135deg, #0d6efd, #0b5ed7);
            border: none;
            padding: 12px;
            font-weight: bold;
        }
    </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="manage_videos.php">Manage Videos</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 pb-5">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2>Edit Game: <?php echo htmlspecialchars($game['game_name']); ?></h2>
                    <a href="games.php" class="btn btn-secondary">← Back to List</a>
                </div>

                <?php echo $message; ?>

                <div class="row">
                    <div class="col-md-8">
                        <div class="card p-4 shadow-sm border-0">
                            <form method="POST" enctype="multipart/form-data">
                                <div class="row">
                                    <div class="col-md-12 mb-3">
                                        <label for="game_name" class="form-label fw-bold">Game Name</label>
                                        <input type="text" class="form-control form-control-lg" id="game_name" name="game_name"
                                            value="<?php echo htmlspecialchars($game['game_name']); ?>" required>
                                    </div>
                                </div>

                                <div class="mb-3">
                                    <label for="game_description" class="form-label fw-bold">Game Description</label>
                                    <textarea class="form-control" id="game_description" name="game_description" rows="5"
                                        required><?php echo htmlspecialchars($game['game_description']); ?></textarea>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="release_date" class="form-label fw-bold">Release Date</label>
                                        <input type="date" class="form-control" id="release_date" name="release_date"
                                            value="<?php echo $game['release_date']; ?>" required>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="category" class="form-label fw-bold">App Section</label>
                                        <select name="category" id="app_section" class="form-select" onchange="toggleHeroVideoField()">
                                            <option value="">None (Standard List)</option>
                                            <option value="slider" <?php if ($game['category'] == 'slider') echo 'selected'; ?>>Hero Slider (Top Banner)</option>
                                            <option value="trending" <?php if ($game['category'] == 'trending') echo 'selected'; ?>>Trending Games</option>
                                            <option value="instant" <?php if ($game['category'] == 'instant') echo 'selected'; ?>>Instant Games (Home Section)</option>
                                            <option value="editor_choice" <?php if ($game['category'] == 'editor_choice') echo 'selected'; ?>>Editor's Choice</option>
                                            <option value="upcoming" <?php if ($game['category'] == 'upcoming') echo 'selected'; ?>>Upcoming Titles</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="mb-3 <?php if ($game['category'] != 'slider') echo 'd-none'; ?>" id="hero_video_field">
                                    <label for="hero_video_file" class="form-label fw-bold text-primary">Hero Slider Promotional Video</label>
                                    <input type="file" class="form-control border-primary" id="hero_video_file" name="hero_video_file" accept="video/*">
                                    <?php if (!empty($game['hero_video'])): ?>
                                        <div class="mt-2 p-2 bg-light rounded shadow-sm border">
                                            <small class="text-success">Current video: <strong><?php echo $game['hero_video']; ?></strong></small>
                                        </div>
                                    <?php endif; ?>
                                </div>

                                <hr class="my-4">

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="game_type" class="form-label fw-bold">Game Type</label>
                                        <select name="game_type" id="game_type" class="form-select" onchange="toggleTypeFields()">
                                            <option value="native" <?php if ($game['game_type'] == 'native') echo 'selected'; ?>>Native (APK)</option>
                                            <option value="instant" <?php if ($game['game_type'] == 'instant') echo 'selected'; ?>>Instant (Web Link)</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="package_name" class="form-label fw-bold">Package Name</label>
                                        <input type="text" class="form-control" id="package_name" name="package_name"
                                            value="<?php echo htmlspecialchars($game['package_name']); ?>" placeholder="com.company.game">
                                    </div>
                                </div>

                                <div class="mb-3 <?php if ($game['game_type'] != 'native') echo 'd-none'; ?>" id="apk_field">
                                    <label for="download_file" class="form-label fw-bold">Update APK File</label>
                                    <input type="file" class="form-control" id="download_file" name="download_file" accept=".apk">
                                    <?php if ($game['game_type'] == 'native' && !empty($game['download_link'])): ?>
                                        <div class="mt-2 p-2 bg-light rounded shadow-sm border">
                                            <small class="text-success"><i class="bi bi-file-earmark-check"></i> Current file: <strong><?php echo $game['download_link']; ?></strong></small>
                                        </div>
                                    <?php endif; ?>
                                </div>

                                <div class="mb-3 <?php if ($game['game_type'] != 'instant') echo 'd-none'; ?>" id="url_field">
                                    <label for="download_url" class="form-label fw-bold">Game Website URL</label>
                                    <input type="url" class="form-control" id="download_url" name="download_url"
                                        value="<?php echo ($game['game_type'] == 'instant') ? $game['download_link'] : ''; ?>" placeholder="https://game-link.com">
                                </div>

                                <div class="mt-4">
                                    <button type="submit" class="btn btn-primary btn-lg w-100 btn-update">Save Changes</button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <div class="col-md-4">
                        <!-- Stats Card -->
                        <div class="card p-4 shadow-sm border-0 mb-4 bg-white">
                            <h5 class="mb-3 fw-bold">Game Stats</h5>
                            <div class="d-flex justify-content-between mb-2">
                                <span class="text-muted">Plays:</span>
                                <span class="badge bg-primary rounded-pill"><?php echo number_format($game['plays'] ?? 0); ?></span>
                            </div>
                            <div class="d-flex justify-content-between">
                                <span class="text-muted">Downloads:</span>
                                <span class="badge bg-success rounded-pill"><?php echo number_format($game['downloads'] ?? 0); ?></span>
                            </div>
                        </div>

                        <!-- Visibility/Promo Card -->
                        <div class="card p-4 shadow-sm border-0 mb-4 bg-white">
                            <h5 class="mb-3 fw-bold">Visibility</h5>
                            <div class="form-check form-switch mb-3">
                                <input type="checkbox" class="form-check-input" id="is_recommended_sidebar" 
                                    onchange="document.getElementById('is_recommended').checked = this.checked;"
                                    <?php if ($game['is_recommended']) echo 'checked'; ?>>
                                <label class="form-check-label" for="is_recommended_sidebar">Recommended for You</label>
                            </div>
                            <!-- Hidden real checkbox for the form -->
                            <input type="checkbox" name="is_recommended" id="is_recommended" class="d-none" <?php if ($game['is_recommended']) echo 'checked'; ?>>
                            
                            <small class="text-muted">Recommended games appear in the "Recommended for You" section on the home page.</small>
                        </div>

                        <!-- Current Icon Card -->
                        <div class="card p-4 shadow-sm border-0 bg-white">
                            <h5 class="mb-3 fw-bold">Game Icon</h5>
                            <div class="text-center mb-3">
                                <?php
                                $icon = get_admin_icon($game['game_icon']);
                                ?>
                                <img src="<?php echo $icon; ?>" width="120" class="rounded shadow-sm border">
                            </div>
                            <label for="game_icon" class="form-label btn btn-outline-primary btn-sm w-100">Change Icon</label>
                            <!-- Hidden input in the main form, modified to work with JS correctly -->
                            <input type="file" id="game_icon" name="game_icon" class="d-none" accept="image/*">
                            <input type="file" id="game_icon_quick" class="d-none" onchange="document.getElementById('game_icon').files = this.files;">
                        </div>
                    </div>
                </div>
            </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>
