<?php
// Database connection include karo
include dirname(__DIR__, 3) . "/includes/db.php";
date_default_timezone_set("Asia/Kolkata");

// ==========================================
// 0. AJAX API: Fetch Result & Game Details
// ==========================================
if (isset($_GET['action'])) {
    header('Content-Type: application/json');
    
    // AJAX: Fetch Result for Date/Game
    if ($_GET['action'] == 'get_result') {
        $game_id = $_GET['game_id'] ?? 0;
        $draw_date = $_GET['date'] ?? '';
        $stmt = $db->prepare("SELECT open_digits, close_digits, note_open FROM results WHERE game_id = ? AND draw_date = ? LIMIT 1");
        $stmt->execute([$game_id, $draw_date]);
        $data = $stmt->fetch(PDO::FETCH_ASSOC);
        echo json_encode($data ? ['status' => 'found', 'data' => $data] : ['status' => 'not_found']);
        exit;
    }
    
    // AJAX: Fetch Game Details for Edit
    if ($_GET['action'] == 'get_game') {
        $game_id = $_GET['game_id'] ?? 0;
        $stmt = $db->prepare("SELECT * FROM games WHERE game_id = ? LIMIT 1");
        $stmt->execute([$game_id]);
        $data = $stmt->fetch(PDO::FETCH_ASSOC);
        echo json_encode($data ? ['status' => 'found', 'data' => $data] : ['status' => 'not_found']);
        exit;
    }
}

$message = "";

// ==========================================
// 1. BACKEND LOGIC (Handling Form Submissions)
// ==========================================

// Action: Add / Update Result
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'add_result') {
    $game_id = $_POST['game_id'];
    $draw_date = $_POST['draw_date'];
    $open_digits = $_POST['open_digits'];
    $close_digits = $_POST['close_digits'];
    $note = $_POST['note_open'] ?? '';

    $check = $db->prepare("SELECT id FROM results WHERE game_id = ? AND draw_date = ?");
    $check->execute([$game_id, $draw_date]);
    
    if ($check->rowCount() > 0) {
        $stmt = $db->prepare("UPDATE results SET open_digits=?, close_digits=?, note_open=? WHERE game_id=? AND draw_date=?");
        if ($stmt->execute([$open_digits, $close_digits, $note, $game_id, $draw_date])) {
            $message = "<div class='alert success'>Result Updated Successfully!</div>";
        }
    } else {
        $stmt = $db->prepare("INSERT INTO results (game_id, draw_date, open_digits, close_digits, note_open) VALUES (?, ?, ?, ?, ?)");
        if ($stmt->execute([$game_id, $draw_date, $open_digits, $close_digits, $note])) {
            $message = "<div class='alert success'>New Result Added Successfully!</div>";
        }
    }
}

// Action: Update SEO Pages (charts_pages)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'update_seo') {
    $seo_id = $_POST['seo_id'] ?? '';
    $slug = $_POST['slug'];
    $title = $_POST['title'];
    $desc = $_POST['description'];
    $content = $_POST['content'];
    $content2 = $_POST['content2'];
    $schema_data = $_POST['schema_data'] ?? '';

    if (!empty($seo_id)) {
        // ID mili, matlab Edit ho raha hai -> UPDATE chalega
        $stmt = $db->prepare("UPDATE charts_pages SET slug=?, title=?, description=?, content=?, content2=?, schema_data=?, updated_at=NOW() WHERE id=?");
        $stmt->execute([$slug, $title, $desc, $content, $content2, $schema_data, $seo_id]);
        $message = "<div class='alert success'>SEO Data Updated for $slug!</div>";
    } else {
        // ID nahi mili, matlab Add New hai -> Duplicate check aur INSERT chalega
        $check = $db->prepare("SELECT id FROM charts_pages WHERE slug = ?");
        $check->execute([$slug]);

        if ($check->rowCount() > 0) {
            $message = "<div class='alert danger'>Error: Ye Slug pehle se exist karta hai!</div>";
        } else {
            $stmt = $db->prepare("INSERT INTO charts_pages (slug, title, description, content, content2, schema_data, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())");
            $stmt->execute([$slug, $title, $desc, $content, $content2, $schema_data]);
            $message = "<div class='alert success'>New SEO Page Created!</div>";
        }
    }
}

// Action: Add / Update Full Game (Config)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'save_game') {
    $game_id = $_POST['game_id'] ?? '';
    $title = $_POST['title'];
    $alias = !empty($_POST['alias']) ? $_POST['alias'] : strtolower(str_replace(' ', '-', $title));
    $time_open = !empty($_POST['time_open']) ? $_POST['time_open'] : null;
    $time_close = !empty($_POST['time_close']) ? $_POST['time_close'] : null;
    $game_day = $_POST['game_day'] ?: 7;
    
    // Checkboxes
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    $is_holiday = isset($_POST['is_holiday']) ? 1 : 0;
    $highlight = isset($_POST['highlight']) ? 1 : 0;
    $auto_gues_status = isset($_POST['auto_gues_status']) ? 1 : 0;
    $guess_status = isset($_POST['guess_status']) ? 1 : 0;
    
    $color = $_POST['color'] ?? '';
    $chart_url = $_POST['chart_url'] ?? '';
    $waiting_start_minutes = $_POST['waiting_start_minutes'] ?: 30;
    $result_show_minutes = $_POST['result_show_minutes'] ?: 10;
    $post_time_min = $_POST['post_time_min'] ?: 20;
    $post_time_max = $_POST['post_time_max'] ?: 25;

    if (empty($game_id)) {
        // Add New Game
        $sql = "INSERT INTO games (title, alias, time_open, time_close, game_day, is_holiday, is_active, chart_url, highlight, auto_gues_status, guess_status, color, waiting_start_minutes, result_show_minutes, post_time_min, post_time_max, jodi_result, panel_result) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '', '')";
        $stmt = $db->prepare($sql);
        $stmt->execute([$title, $alias, $time_open, $time_close, $game_day, $is_holiday, $is_active, $chart_url, $highlight, $auto_gues_status, $guess_status, $color, $waiting_start_minutes, $result_show_minutes, $post_time_min, $post_time_max]);
        $message = "<div class='alert success'>New Game Created Successfully!</div>";
    } else {
        // Update Existing Game
        $sql = "UPDATE games SET title=?, alias=?, time_open=?, time_close=?, game_day=?, is_holiday=?, is_active=?, chart_url=?, highlight=?, auto_gues_status=?, guess_status=?, color=?, waiting_start_minutes=?, result_show_minutes=?, post_time_min=?, post_time_max=? WHERE game_id=?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$title, $alias, $time_open, $time_close, $game_day, $is_holiday, $is_active, $chart_url, $highlight, $auto_gues_status, $guess_status, $color, $waiting_start_minutes, $result_show_minutes, $post_time_min, $post_time_max, $game_id]);
        $message = "<div class='alert success'>Game Updated Successfully!</div>";
    }
}

// Action: Delete Game
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] == 'delete_game') {
    $del_id = $_POST['game_id'];
    $stmt = $db->prepare("DELETE FROM games WHERE game_id = ?");
    if($stmt->execute([$del_id])){
        $message = "<div class='alert success'>Game Deleted Successfully!</div>";
    }
}

// Fetch Data for Display
$games_query = $db->query("SELECT game_id, title, alias, is_active FROM games ORDER BY title ASC");
$all_games = $games_query->fetchAll(PDO::FETCH_ASSOC);

$seo_query = $db->query("SELECT * FROM charts_pages ORDER BY id DESC LIMIT 50");
$seo_pages = $seo_query->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Satta Matka - Master Admin</title>
    <style>
        :root {
            --primary: #4e73df; --secondary: #858796; --success: #1cc88a; --danger: #e74a3b; --warning: #f6c23e;
            --dark: #20232a; --light: #f8f9fc; --border: #e3e6f0;
        }
        * { box-sizing: border-box; font-family: 'Segoe UI', Tahoma, sans-serif; }
        body { margin: 0; background-color: #f4f6f9; color: #333; padding-bottom: 70px; }
        
        .header { background: var(--primary); color: white; padding: 15px 20px; text-align: center; box-shadow: 0 2px 4px rgba(0,0,0,0.1); position: sticky; top: 0; z-index: 100;}
        .header h2 { margin: 0; font-size: 20px; }

        .container { padding: 15px; max-width: 800px; margin: auto; }
        
        .alert { padding: 10px 15px; border-radius: 5px; margin-bottom: 15px; color: #fff; font-weight: bold; }
        .alert.success { background-color: var(--success); }
        .alert.danger { background-color: var(--danger); }

        .card { background: white; border-radius: 8px; padding: 20px; box-shadow: 0 4px 6px rgba(0,0,0,0.05); margin-bottom: 20px; }
        .card h3 { margin-top: 0; color: var(--primary); border-bottom: 2px solid var(--border); padding-bottom: 10px; display: flex; justify-content: space-between; align-items: center;}
        
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 5px; font-weight: 600; font-size: 14px; color: #555;}
        .form-control { width: 100%; padding: 10px; border: 1px solid var(--border); border-radius: 5px; font-size: 16px; transition: 0.3s; }
        .form-control:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 5px rgba(78,115,223,0.3); }
        textarea.form-control { resize: vertical; min-height: 80px; }
        
        .grid-2 { display: grid; grid-template-columns: 1fr; gap: 10px; }
        .checkbox-group { display: flex; flex-wrap: wrap; gap: 15px; padding: 10px; background: var(--light); border-radius: 5px; border: 1px solid var(--border); }
        .checkbox-group label { font-weight: normal; cursor: pointer; display: flex; align-items: center; gap: 5px; }

        .btn { width: 100%; padding: 12px; background: var(--primary); color: white; border: none; border-radius: 5px; font-size: 16px; font-weight: bold; cursor: pointer; transition: 0.3s; margin-top: 5px;}
        .btn:active { transform: scale(0.98); }
        .btn-success { background: var(--success); }
        .btn-warning { background: var(--warning); color: #333; }
        .btn-danger { background: var(--danger); width: auto; padding: 6px 12px; font-size: 14px; border:none; border-radius:3px; color:white; cursor:pointer;}
        .btn-edit { background: var(--primary); width: auto; padding: 6px 12px; color: white; font-size: 14px; border: none; border-radius: 3px; cursor: pointer; }

        .table-responsive { overflow-x: auto; }
        table { width: 100%; border-collapse: collapse; margin-top: 10px; font-size: 14px; }
        th, td { padding: 10px; border: 1px solid var(--border); text-align: left; }
        th { background: var(--light); color: var(--dark); }

        .bottom-nav { position: fixed; bottom: 0; left: 0; width: 100%; background: white; display: flex; justify-content: space-around; box-shadow: 0 -2px 10px rgba(0,0,0,0.1); padding: 10px 0; z-index: 1000; }
        .nav-item { text-align: center; color: var(--secondary); cursor: pointer; flex: 1; font-weight: bold; font-size: 14px; padding: 5px;}
        .nav-item.active { color: var(--primary); border-bottom: 3px solid var(--primary); padding-bottom: 2px;}
        .nav-icon { display: block; font-size: 20px; margin-bottom: 3px; }

        .tab-content { display: none; animation: fadeIn 0.3s; }
        .tab-content.active { display: block; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }

        @media (min-width: 600px) {
            .grid-2 { grid-template-columns: 1fr 1fr; }
        }

        @media (min-width: 768px) {
            body { padding-bottom: 0; display: flex; }
            .bottom-nav { position: static; flex-direction: column; width: 200px; height: 100vh; justify-content: flex-start; padding-top: 20px; border-right: 1px solid var(--border); box-shadow: none; }
            .nav-item { padding: 15px; text-align: left; border-bottom: none; display: flex; align-items: center; gap: 10px; }
            .nav-item.active { border-left: 4px solid var(--primary); border-bottom: none; background: var(--light); }
            .nav-icon { margin: 0; }
            .main-wrapper { flex: 1; height: 100vh; overflow-y: auto; }
        }
    </style>
</head>
<body>

    <nav class="bottom-nav">
        <div class="nav-item active" onclick="switchTab('resultsTab')">
            <span class="nav-icon">📊</span> Results
        </div>
        <div class="nav-item" onclick="switchTab('seoTab')">
            <span class="nav-icon">🔍</span> SEO
        </div>
        <div class="nav-item" onclick="switchTab('settingsTab')">
            <span class="nav-icon">⚙️</span> Config
        </div>
    </nav>

    <div class="main-wrapper">
        <div class="header">
            <h2>⚙️ Matka Admin Control</h2>
        </div>

        <div class="container">
            <?= $message ?>

            <div id="resultsTab" class="tab-content active">
                <div class="card">
                    <h3>Declare Daily Result</h3>
                    <form method="POST">
                        <input type="hidden" name="action" value="add_result">
                        
                        <div class="form-group">
                            <label>Select Game</label>
                            <select name="game_id" id="gameSelect" class="form-control" onchange="fetchResult()" required>
                                <option value="">-- Select Market --</option>
                                <?php foreach($all_games as $g): ?>
                                    <option value="<?= $g['game_id'] ?>"><?= htmlspecialchars($g['title']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Draw Date</label>
                            <input type="date" name="draw_date" id="dateSelect" class="form-control" value="<?= date('Y-m-d') ?>" onchange="fetchResult()" required>
                        </div>

                        <div class="grid-2">
                            <div class="form-group">
                                <label>Open Panel</label>
                                <input type="text" name="open_digits" id="open_digits" class="form-control" placeholder="***">
                            </div>
                            <div class="form-group">
                                <label>Close Panel</label>
                                <input type="text" name="close_digits" id="close_digits" class="form-control" placeholder="***">
                            </div>
                        </div>

                        <div class="form-group">
                            <label>Remark / Note</label>
                            <input type="text" name="note_open" id="note_open" class="form-control" placeholder="eg: Super Fast">
                        </div>

                        <button type="submit" class="btn btn-success">Save Result</button>
                    </form>
                </div>
            </div>

            <div id="seoTab" class="tab-content">
                <div class="card">
                    <h3 id="seo_form_title">Add New SEO Page</h3>
                    <form method="POST" id="seoForm">
                        <input type="hidden" name="action" value="update_seo">
                        <input type="hidden" name="seo_id" id="seo_id" value="">
                        <div class="form-group">
                            <label>Page Slug (eg: time-bazar-jodi)</label>
                            <input type="text" name="slug" id="seo_slug" class="form-control" required>
                        </div>
                        <div class="form-group">
                            <label>Meta Title</label>
                            <input type="text" name="title" id="seo_title" class="form-control" required>
                        </div>
                        <div class="form-group">
                            <label>Meta Description</label>
                            <textarea name="description" id="seo_desc" class="form-control" required></textarea>
                        </div>
                        <div class="form-group">
                            <label>Top Content (HTML)</label>
                            <textarea name="content" id="seo_content" class="form-control"></textarea>
                        </div>
                        <div class="form-group">
                            <label>Bottom Content (HTML)</label>
                            <textarea name="content2" id="seo_content2" class="form-control"></textarea>
                        </div>
                        <div class="form-group">
                            <label>Schema Data (JSON)</label>
                            <textarea name="schema_data" id="seo_schema" class="form-control"></textarea>
                        </div>
                        <button type="submit" class="btn btn-success" id="btn_save_seo">Save SEO Data</button>
                        <button type="button" class="btn btn-warning" onclick="resetSEOForm()" style="margin-top: 10px;">Reset to Add New</button>
                    </form>
                </div>

                <div class="card">
                    <h3>Recent SEO Pages</h3>
                    <div class="table-responsive">
                        <table>
                            <tr><th>Slug</th><th>Action</th></tr>
                            <?php foreach($seo_pages as $seo): ?>
                            <tr>
                                <td><?= htmlspecialchars($seo['slug']) ?></td>
                                <td>
                                    <button type="button" class="btn-edit"
                                            data-id="<?= $seo['id'] ?>"
                                            data-slug="<?= htmlspecialchars($seo['slug'], ENT_QUOTES) ?>"
                                            data-title="<?= htmlspecialchars($seo['title'], ENT_QUOTES) ?>"
                                            data-desc="<?= htmlspecialchars($seo['description'], ENT_QUOTES) ?>"
                                            data-c1="<?= htmlspecialchars($seo['content'], ENT_QUOTES) ?>"
                                            data-c2="<?= htmlspecialchars($seo['content2'], ENT_QUOTES) ?>"
                                            data-schema="<?= htmlspecialchars($seo['schema_data'] ?? '', ENT_QUOTES) ?>"
                                            onclick="editSEO(this)">Edit</button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </table>
                    </div>
                </div>
            </div>

            <div id="settingsTab" class="tab-content">
                
                <div class="card">
                    <h3 id="game_form_title">Add New Game</h3>
                    <form method="POST" id="gameForm">
                        <input type="hidden" name="action" value="save_game">
                        <input type="hidden" name="game_id" id="g_game_id" value="">
                        
                        <div class="grid-2">
                            <div class="form-group">
                                <label>Market Title</label>
                                <input type="text" name="title" id="g_title" class="form-control" required>
                            </div>
                            <div class="form-group">
                                <label>Alias (Slug)</label>
                                <input type="text" name="alias" id="g_alias" class="form-control" placeholder="Auto-generated if empty">
                            </div>
                        </div>

                        <div class="grid-2">
                            <div class="form-group">
                                <label>Open Time</label>
                                <input type="time" name="time_open" id="g_time_open" class="form-control">
                            </div>
                            <div class="form-group">
                                <label>Close Time</label>
                                <input type="time" name="time_close" id="g_time_close" class="form-control">
                            </div>
                        </div>

                        <div class="form-group">
                            <label>Status & Features Toggles</label>
                            <div class="checkbox-group">
                                <label><input type="checkbox" name="is_active" id="g_is_active" value="1" checked> Active Market</label>
                                <label><input type="checkbox" name="is_holiday" id="g_is_holiday" value="1"> Holiday</label>
                                <label><input type="checkbox" name="highlight" id="g_highlight" value="1"> Highlight</label>
                                <label><input type="checkbox" name="auto_gues_status" id="g_auto_gues_status" value="1"> Auto Guess</label>
                                <label><input type="checkbox" name="guess_status" id="g_guess_status" value="1"> Guessing</label>
                            </div>
                        </div>

                        <div class="grid-2">
                            <div class="form-group">
                                <label>Play Days (1-7)</label>
                                <input type="number" name="game_day" id="g_game_day" class="form-control" value="7" min="1" max="7">
                            </div>
                            <div class="form-group">
                                <label>Theme Color</label>
                                <input type="text" name="color" id="g_color" class="form-control" placeholder="eg: #ff0000">
                            </div>
                        </div>

                        <div class="grid-2">
                            <div class="form-group">
                                <label>Waiting Start (Min)</label>
                                <input type="number" name="waiting_start_minutes" id="g_wait_min" class="form-control" value="30">
                            </div>
                            <div class="form-group">
                                <label>Result Show (Min)</label>
                                <input type="number" name="result_show_minutes" id="g_res_min" class="form-control" value="10">
                            </div>
                            <div class="form-group">
                                <label>Post Min</label>
                                <input type="number" name="post_time_min" id="g_post_min" class="form-control" value="20">
                            </div>
                            <div class="form-group">
                                <label>Post Max</label>
                                <input type="number" name="post_time_max" id="g_post_max" class="form-control" value="25">
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label>Chart URL</label>
                            <input type="text" name="chart_url" id="g_chart_url" class="form-control">
                        </div>

                        <button type="submit" class="btn btn-success" id="btn_save_game">Save Game Configuration</button>
                        <button type="button" class="btn btn-warning" onclick="resetGameForm()" style="margin-top: 10px;">Reset to Add New</button>
                    </form>
                </div>

                <div class="card">
                    <h3>Manage Games</h3>
                    <div class="table-responsive">
                        <table>
                            <tr>
                                <th>Name</th>
                                <th>Active</th>
                                <th>Action</th>
                            </tr>
                            <?php foreach($all_games as $g): ?>
                            <tr>
                                <td><?= htmlspecialchars($g['title']) ?></td>
                                <td style="color: <?= $g['is_active'] ? 'green' : 'red' ?>; font-weight:bold;">
                                    <?= $g['is_active'] ? 'Yes' : 'No' ?>
                                </td>
                                <td style="display: flex; gap: 5px;">
                                    <button type="button" class="btn-edit" onclick="editGame(<?= $g['game_id'] ?>)">Edit</button>
                                    <form method="POST" onsubmit="return confirm('WARNING: Are you sure you want to delete this market entirely?');" style="margin:0;">
                                        <input type="hidden" name="action" value="delete_game">
                                        <input type="hidden" name="game_id" value="<?= $g['game_id'] ?>">
                                        <button type="submit" class="btn-danger">Delete</button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </table>
                    </div>
                </div>
            </div>

        </div>
    </div>

    <script>
        // Tab Switcher
        function switchTab(tabId) {
            document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active'));
            document.querySelectorAll('.nav-item').forEach(nav => nav.classList.remove('active'));
            document.getElementById(tabId).classList.add('active');
            event.currentTarget.classList.add('active');
            window.scrollTo(0, 0);
        }

        // AJAX: Fetch Result (Auto-fill Old/New Data)
        function fetchResult() {
            let game = document.getElementById('gameSelect').value;
            let date = document.getElementById('dateSelect').value;
            
            if(game && date) {
                fetch('?action=get_result&game_id=' + game + '&date=' + date)
                .then(response => response.json())
                .then(res => {
                    if(res.status === 'found') {
                        document.getElementById('open_digits').value = res.data.open_digits;
                        document.getElementById('close_digits').value = res.data.close_digits;
                        document.getElementById('note_open').value = res.data.note_open;
                    } else {
                        document.getElementById('open_digits').value = '';
                        document.getElementById('close_digits').value = '';
                        document.getElementById('note_open').value = '';
                    }
                })
                .catch(err => console.error("Error fetching result", err));
            }
        }

        // Quick Edit SEO Pages
        function editSEO(btn) {
            switchTab('seoTab');
            document.getElementById('seo_form_title').innerText = "Edit SEO Page";
            document.getElementById('btn_save_seo').innerText = "Update SEO Data";
            
            document.getElementById('seo_id').value = btn.getAttribute('data-id');
            document.getElementById('seo_slug').value = btn.getAttribute('data-slug');
            document.getElementById('seo_title').value = btn.getAttribute('data-title');
            document.getElementById('seo_desc').value = btn.getAttribute('data-desc');
            document.getElementById('seo_content').value = btn.getAttribute('data-c1');
            document.getElementById('seo_content2').value = btn.getAttribute('data-c2');
            document.getElementById('seo_schema').value = btn.getAttribute('data-schema');
            window.scrollTo(0,0);
        }

        // SEO Form Reset
        function resetSEOForm() {
            document.getElementById('seoForm').reset();
            document.getElementById('seo_id').value = '';
            document.getElementById('seo_schema').value = '';
            document.getElementById('seo_form_title').innerText = "Add New SEO Page";
            document.getElementById('btn_save_seo').innerText = "Save SEO Data";
        }

        // AJAX: Fetch Full Game Data for Config Edit
        function editGame(game_id) {
            switchTab('settingsTab');
            document.getElementById('game_form_title').innerText = "Edit Game: ID " + game_id;
            document.getElementById('g_game_id').value = game_id;
            document.getElementById('btn_save_game').innerText = "Update Game Configuration";
            
            fetch('?action=get_game&game_id=' + game_id)
            .then(res => res.json())
            .then(res => {
                if(res.status === 'found') {
                    let d = res.data;
                    document.getElementById('g_title').value = d.title || '';
                    document.getElementById('g_alias').value = d.alias || '';
                    document.getElementById('g_time_open').value = d.time_open || '';
                    document.getElementById('g_time_close').value = d.time_close || '';
                    document.getElementById('g_game_day').value = d.game_day || '7';
                    
                    document.getElementById('g_is_active').checked = (d.is_active == 1);
                    document.getElementById('g_is_holiday').checked = (d.is_holiday == 1);
                    document.getElementById('g_highlight').checked = (d.highlight == 1);
                    document.getElementById('g_auto_gues_status').checked = (d.auto_gues_status == 1);
                    document.getElementById('g_guess_status').checked = (d.guess_status == 1);
                    
                    document.getElementById('g_color').value = d.color || '';
                    document.getElementById('g_chart_url').value = d.chart_url || '';
                    document.getElementById('g_wait_min').value = d.waiting_start_minutes || '30';
                    document.getElementById('g_res_min').value = d.result_show_minutes || '10';
                    document.getElementById('g_post_min').value = d.post_time_min || '20';
                    document.getElementById('g_post_max').value = d.post_time_max || '25';
                    
                    window.scrollTo(0,0);
                }
            })
            .catch(err => console.error("Error fetching game", err));
        }

        // Reset Config Form
        function resetGameForm() {
            document.getElementById('gameForm').reset();
            document.getElementById('g_game_id').value = '';
            document.getElementById('game_form_title').innerText = "Add New Game";
            document.getElementById('btn_save_game').innerText = "Save Game Configuration";
        }
    </script>
</body>
</html>
