<?php
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include_once '../db/koneksi.php';

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['kode_admin'])) {
    echo '
    <script>
        alert("Terjadi kesalahan, harap masuk kembali!");
        window.location.replace("' . $alamat_admin . 'keluar.php");
    </script>
    ';
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update') {
    $id          = mysqli_real_escape_string($koneksi, $_POST['id']);
    $game_name   = mysqli_real_escape_string($koneksi, $_POST['game_name']);
    $game_code   = mysqli_real_escape_string($koneksi, $_POST['game_code']);
    $banner      = mysqli_real_escape_string($koneksi, $_POST['banner']);
    $provider    = mysqli_real_escape_string($koneksi, $_POST['provider']);
    $datatype    = mysqli_real_escape_string($koneksi, $_POST['datatype']);
    $status      = (int)$_POST['frbavailable'];
    $populer     = (int)$_POST['rekomendasi'];
    $poster      = mysqli_real_escape_string($koneksi, $_POST['poster']);
    $posisi      = (int)$_POST['posisi'];
    $tab      = mysqli_real_escape_string($koneksi, $_POST['tab']);

    $queryUpdate = "UPDATE tb_gamelist_sgx 
                    SET game_name='$game_name',
                        game_code='$game_code',
                        banner='$banner',
                        provider='$provider',
                        datatype='$datatype',
                        frbavailable='$status',
                        rekomendasi='$populer',
                        poster='$poster',
                        posisi='$posisi',
                        tab='$tab'
                    WHERE id='$id'";

    if (mysqli_query($koneksi, $queryUpdate)) {
        $_SESSION['success'] = "Data game berhasil diperbarui.";
        echo '<script>window.location.replace("'.$alamat_admin.'game-lists")</script>';
    } else {
        $_SESSION['error'] = "Gagal memperbarui data game: " . mysqli_error($koneksi);
    }
    exit();
}


$limit = 50;
$page = isset($_POST['page']) ? (int)$_POST['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

$search = isset($_POST['search']) ? mysqli_real_escape_string($koneksi, $_POST['search']) : '';

$where = "";
if (!empty($search)) {
    $search_safe = mysqli_real_escape_string($koneksi, $search);
    $search_safe = str_replace(['%', '_'], ['\%', '\_'], $search_safe);
    $where = "WHERE LOWER(game_name) LIKE LOWER('%$search_safe%') OR LOWER(game_code) LIKE LOWER('%$search_safe%') OR LOWER(provider) LIKE LOWER('%$search_safe%')";
}

$totalQuery = mysqli_query($koneksi, "SELECT COUNT(*) as total FROM tb_gamelist_sgx $where");
$totalData = mysqli_fetch_assoc($totalQuery)['total'];
$totalPages = ceil($totalData / $limit);

$query = "SELECT * FROM tb_gamelist_sgx $where ORDER BY id ASC LIMIT $limit OFFSET $offset";
$gamelist = mysqli_query($koneksi, $query);
?>

<div class="container-xxl flex-grow-1 container-p-y">

    <div class="row gy-4 mb-4">
        <div class="col-md-6">
            <h4 class="fw-bold mb-0 text-center text-md-start">Game List</h4>
        </div>
        <div class="col-md-6 text-center text-md-end">
            <span><?php echo ucapan() . ', ' . tanggalIndonesia(date('Y-m-d'), true) . ', '; ?></span>
            <span id="jam_sekarang">Jam </span>
        </div>
    </div>

    <?php if (isset($_SESSION['success'])): ?>
        <div class="alert alert-success"><?= $_SESSION['success']; unset($_SESSION['success']); ?></div>
    <?php elseif (isset($_SESSION['error'])): ?>
        <div class="alert alert-danger"><?= $_SESSION['error']; unset($_SESSION['error']); ?></div>
    <?php endif; ?>

    <div class="card table-responsive p-3">
         <form method="post" id="filterForm" class="mb-3 d-flex flex-wrap gap-2 justify-content-end">
            <input type="hidden" name="page" id="pageInput" value="<?= $page; ?>">
            <input type="text" name="search" class="form-control w-auto" placeholder="Cari game..." 
                value="<?= htmlspecialchars($search); ?>">
            <button type="submit" class="btn btn-primary">Search</button>
        </form>
        <table class="table table-hover align-middle">
            <thead class="table-light">
                <tr>
                    <th class="text-center">No.</th>
                    <th class="text-center">Nama Game</th>
                    <th class="text-center">Game Code</th>
                    <th class="text-center">Banner</th>
                    <th class="text-center">Provider</th>
                    <th class="text-center">Game Type</th>
                    <th class="text-center">Status</th>
                    <th class="text-center">Tab</th>
                    <th class="text-center">Populer</th>
                    <th class="text-center">Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php
                if (mysqli_num_rows($gamelist) > 0) {
                    $no = $offset + 1;
                    while ($data = mysqli_fetch_assoc($gamelist)) {
                        $id = $data['id'];
                        $status = $data['frbavailable'];
                        $populer = $data['rekomendasi'];
                        $status_class = ($status == 1) ? 'text-success' : 'text-danger';?>
                        <tr>
                            <td class="text-center"><?= $no++; ?></td>
                            <td class="text-center"><?= htmlspecialchars($data['game_name']); ?></td>
                            <td class="text-center"><?= htmlspecialchars($data['game_code']); ?></td>
                            <td class="text-center">
                                <img src="<?= htmlspecialchars($data['banner']); ?>" alt="Banner" class="img-fluid rounded" style="width: 80px;">
                            </td>
                            <td class="text-center"><?= htmlspecialchars($data['provider']); ?></td>
                            <td class="text-center"><?= htmlspecialchars($data['datatype']); ?></td>
                            <td class="<?= $status_class; ?> text-center">
                                <?= ($status == 1) ? 'Aktif' : 'Non-Aktif'; ?>
                            </td>
                            <td class="text-center"><?= htmlspecialchars($data['tab']); ?></td>
                            <td class="text-center"><?= ($populer == 1) ? 'Ya' : 'Tidak'; ?></td>
                            <td class="text-center">
                                <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#modalUbahGame<?= $id; ?>">
                                    <i class="mdi mdi-cog me-1"></i> Ubah
                                </button>
                            </td>
                        </tr>

                        <!-- Modal Ubah Game -->
                        <div class="modal fade" id="modalUbahGame<?= $id; ?>" tabindex="-1" aria-labelledby="modalUbahGameLabel<?= $id; ?>" aria-hidden="true">
                            <div class="modal-dialog modal-lg modal-dialog-centered">
                                <div class="modal-content">
                                    <form method="post">
                                        <div class="modal-header">
                                            <h5 class="modal-title" id="modalUbahGameLabel<?= $id; ?>">Ubah Game: <?= htmlspecialchars($data['game_name']); ?></h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                        </div>
                                        <div class="modal-body">
                                            <input type="hidden" name="action" value="update">
                                            <input type="hidden" name="id" value="<?= $id; ?>">

                                            <div class="mb-3">
                                                <label for="game_name_<?= $id; ?>" class="form-label">Nama Game</label>
                                                <input type="text" class="form-control" id="game_name_<?= $id; ?>" name="game_name" value="<?= htmlspecialchars($data['game_name']); ?>" required>
                                            </div>

                                            <div class="mb-3">
                                                <label for="game_code_<?= $id; ?>" class="form-label">Game Code</label>
                                                <input type="text" class="form-control" id="game_code_<?= $id; ?>" name="game_code" value="<?= htmlspecialchars($data['game_code']); ?>" required>
                                            </div>

                                            <div class="mb-3">
                                                <label for="banner_<?= $id; ?>" class="form-label">Banner URL</label>
                                                <input type="url" class="form-control" id="banner_<?= $id; ?>" name="banner" value="<?= htmlspecialchars($data['banner']); ?>" required>
                                            </div>

                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label for="poster<?= $id; ?>" class="form-label">Poster URL (Wajib diisi jika Game Populer)</label>
                                                    <input type="url" class="form-control" id="poster<?= $id; ?>" name="poster" value="<?= htmlspecialchars($data['poster'] ?? ''); ?>">
                                                </div>

                                                <div class="col-md-6 mb-3">
                                                    <label for="tab<?= $id; ?>" class="form-label">Tab (Wajib diisi untuk mengatur game launch)</label>
                                                    <select class="form-control" id="tab<?= $id; ?>" name="tab" value="<?= htmlspecialchars($data['tab'] ?? ''); ?>">
                                                        <option value="Slot">Slot</option>
                                                        <option value="Live Casino">Live Casino</option>
                                                        <option value="Tembak Ikan">Games</option>
                                                        <option value="Sportsbook">Sports</option>
                                                        <option value="Togel">Togel</option>
                                                    </select>
                                                </div>

                                                <div class="col-md-6 mb-3">
                                                    <label for="posisi<?= $id; ?>" class="form-label">Posisi (Wajib diisi jika Game Populer)</label>
                                                    <input type="number" class="form-control" id="posisi<?= $id; ?>" name="posisi" value="<?= htmlspecialchars($data['posisi'] ?? ''); ?>">
                                                </div>
                                            </div>

                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label for="provider_<?= $id; ?>" class="form-label">Provider</label>
                                                    <input type="text" class="form-control" id="provider_<?= $id; ?>" name="provider" value="<?= htmlspecialchars($data['provider']); ?>" required>
                                                </div>

                                                <div class="col-md-6 mb-3">
                                                    <label for="datatype_<?= $id; ?>" class="form-label">Game Type</label>
                                                    <input type="text" class="form-control" id="datatype_<?= $id; ?>" name="datatype" value="<?= htmlspecialchars($data['datatype']); ?>" required>
                                                </div>
                                            </div>

                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Status</label>
                                                    <select name="frbavailable" class="form-select">
                                                        <option value="1" <?= ($status == 1) ? 'selected' : ''; ?>>Aktif</option>
                                                        <option value="0" <?= ($status == 0) ? 'selected' : ''; ?>>Non-Aktif</option>
                                                    </select>
                                                </div>

                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Populer</label>
                                                    <select name="rekomendasi" class="form-select">
                                                        <option value="1" <?= ($populer == 1) ? 'selected' : ''; ?>>Ya</option>
                                                        <option value="0" <?= ($populer == 0) ? 'selected' : ''; ?>>Tidak</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                                            <button type="submit" class="btn btn-primary">Simpan Perubahan</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>

                <?php
                    }
                } else {
                    echo '<tr><td colspan="9" class="text-center text-muted">Tidak ada data</td></tr>';
                }
                ?>
            </tbody>
        </table>
    </div>

    <?php if ($totalPages > 1): ?>
    <nav aria-label="Page navigation" class="mt-4">
        <ul class="pagination justify-content-center">
            <li class="page-item <?= ($page <= 1) ? 'disabled' : ''; ?>">
                <button type="button" class="page-link" onclick="changePage(<?= $page - 1; ?>)">Previous</button>
            </li>

            <?php
            $showPages = 2;
            if ($page > ($showPages + 2)) {
                echo '<li class="page-item"><button type="button" class="page-link" onclick="changePage(1)">1</button></li>';
                echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
            }

            for ($i = max(1, $page - $showPages); $i <= min($totalPages, $page + $showPages); $i++) {
                $activeClass = ($i == $page) ? 'active' : '';
                echo '<li class="page-item ' . $activeClass . '">
                        <button type="button" class="page-link" onclick="changePage(' . $i . ')">' . $i . '</button>
                      </li>';
            }

            if ($page < $totalPages - ($showPages + 1)) {
                echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
                echo '<li class="page-item"><button type="button" class="page-link" onclick="changePage(' . $totalPages . ')">' . $totalPages . '</button></li>';
            }
            ?>

            <!-- Tombol Next -->
            <li class="page-item <?= ($page >= $totalPages) ? 'disabled' : ''; ?>">
                <button type="button" class="page-link" onclick="changePage(<?= $page + 1; ?>)">Next</button>
            </li>
        </ul>
    </nav>
    <?php endif; ?>
</div>

<script>
    function changePage(page) {
        document.getElementById('pageInput').value = page;
        document.getElementById('filterForm').submit();
    }
</script>
