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

// === UPDATE DATA GAME ===
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']);
    $provider_name  = mysqli_real_escape_string($koneksi, $_POST['provider_name']);
    $game_provider  = mysqli_real_escape_string($koneksi, $_POST['game_provider']);
    $game_type      = mysqli_real_escape_string($koneksi, $_POST['game_type']);
    $game_image     = mysqli_real_escape_string($koneksi, $_POST['game_image']);
    $game_status    = (int)$_POST['game_status'];
    $seq            = (int)$_POST['seq'];
    $source         = mysqli_real_escape_string($koneksi, $_POST['source']);

    $queryUpdate = "
        UPDATE tb_game 
        SET 
            provider_name='$provider_name',
            game_provider='$game_provider',
            game_name='$game_name',
            game_code='$game_code',
            game_type='$game_type',
            game_image='$game_image',
            game_status='$game_status',
            seq='$seq',
            source='$source'
        WHERE id='$id'
    ";

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

// === PAGINATION & SEARCH ===
$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 = str_replace(['%', '_'], ['\%', '\_'], $search);
    $where = "WHERE LOWER(game_name) LIKE LOWER('%$search_safe%') 
              OR LOWER(game_code) LIKE LOWER('%$search_safe%') 
              OR LOWER(provider_name) LIKE LOWER('%$search_safe%')";
}

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

$query = "SELECT * FROM tb_game $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">Provider</th>
                    <th class="text-center">Game Provider</th>
                    <th class="text-center">Nama Game</th>
                    <th class="text-center">Game Code</th>
                    <th class="text-center">Tipe</th>
                    <th class="text-center">Gambar</th>
                    <th class="text-center">Status</th>
                    <th class="text-center">Seq</th>
                    <th class="text-center">Source</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['game_status'];
                        $status_class = ($status == 1) ? 'text-success' : 'text-danger'; ?>
                        
                        <tr>
                            <td class="text-center"><?= $no++; ?></td>
                            <td class="text-center"><?= htmlspecialchars($data['provider_name']); ?></td>
                            <td class="text-center"><?= htmlspecialchars($data['game_provider']); ?></td>
                            <td class="text-center"><?= htmlspecialchars($data['game_name']); ?></td>
                            <td class="text-center"><?= htmlspecialchars($data['game_code']); ?></td>
                            <td class="text-center"><?= htmlspecialchars($data['game_type']); ?></td>
                            <td class="text-center">
                                <img src="<?= htmlspecialchars($data['game_image']); ?>" alt="Game" class="img-fluid rounded" style="width:80px;">
                            </td>
                            <td class="<?= $status_class; ?> text-center">
                                <?= ($status == 1) ? 'Aktif' : 'Non-Aktif'; ?>
                            </td>
                            <td class="text-center"><?= htmlspecialchars($data['seq']); ?></td>
                            <td class="text-center"><?= htmlspecialchars($data['source']); ?></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 Edit -->
                        <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">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 class="form-label">Provider Name</label>
                                                <input type="text" class="form-control" name="provider_name" value="<?= htmlspecialchars($data['provider_name']); ?>" required>
                                            </div>

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

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

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

                                            <div class="mb-3">
                                                <label class="form-label">Game Type</label>
                                                <input type="text" class="form-control" name="game_type" value="<?= htmlspecialchars($data['game_type']); ?>">
                                            </div>

                                            <div class="mb-3">
                                                <label class="form-label">Game Image URL</label>
                                                <input type="url" class="form-control" name="game_image" value="<?= htmlspecialchars($data['game_image']); ?>">
                                            </div>

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

                                            <div class="mb-3">
                                                <label class="form-label">Sequence</label>
                                                <input type="number" class="form-control" name="seq" value="<?= htmlspecialchars($data['seq']); ?>">
                                            </div>

                                            <div class="mb-3">
                                                <label class="form-label">Source</label>
                                                <input type="text" class="form-control" name="source" value="<?= htmlspecialchars($data['source']); ?>">
                                            </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</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                <?php
                    }
                } else {
                    echo "<tr><td colspan='11' class='text-center text-danger'>Tidak ada data game ditemukan.</td></tr>";
                } ?>
            </tbody>
        </table>
    </div>

    <?php if ($totalPages > 1): ?>
    <nav class="mt-4" aria-label="Page navigation">
        <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;
            for ($i = max(1, $page - $showPages); $i <= min($totalPages, $page + $showPages); $i++) {
                $active = ($i == $page) ? 'active' : '';
                echo "<li class='page-item $active'>
                        <button type='button' class='page-link' onclick='changePage($i)'>$i</button>
                      </li>";
            }
            ?>
            <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>
