<?php
/**
 * File: update_gamelist.php
 * Berfungsi untuk sinkronisasi data game dari API ke tabel tb_gamelist
 */

require_once 'config/koneksi.php'; 
require_once 'config/class.hgi.php';

// Memastikan variabel koneksi menggunakan $conn
if (!$conn) {
    die("Koneksi database gagal: " . mysqli_connect_error());
}

$api = new HypergateAPI();
$message = "";

if (isset($_POST['sync_games'])) {
    // Memanggil API dengan limit 9999 sesuai instruksi Anda
    $response = $api->game_list(null, null, 1, 9999);
    
    if ($response && isset($response['status']) && $response['status'] == 1) {
        $countSuccess = 0;
        
        foreach ($response['games'] as $game) {
            // Mapping data dari respon API ke kolom database
            $game_code     = mysqli_real_escape_string($conn, $game['game_id']);
            $game_name     = mysqli_real_escape_string($conn, $game['name']);
            $provider_code = mysqli_real_escape_string($conn, $game['provider_code']);
            $game_category = mysqli_real_escape_string($conn, $game['game_type']);
            $banner        = mysqli_real_escape_string($conn, $game['image_url']);
            $status        = mysqli_real_escape_string($conn, $game['status']);
            
            // Generate RTP acak antara 80 sampai 98
            $game_rtp      = rand(80, 98);

            // Query INSERT dengan ON DUPLICATE KEY UPDATE berdasarkan UNIQUE KEY 'game_code'
            $sql = "INSERT INTO tb_gamelist 
                    (game_code, game_name, provider_code, game_category, banner, game_rtp, status, created_at, updated_at) 
                    VALUES 
                    ('$game_code', '$game_name', '$provider_code', '$game_category', '$banner', '$game_rtp', '$status', NOW(), NOW())
                    ON DUPLICATE KEY UPDATE 
                    game_name     = VALUES(game_name),
                    provider_code = VALUES(provider_code),
                    game_category = VALUES(game_category),
                    banner        = VALUES(banner),
                    status        = VALUES(status),
                    updated_at    = NOW()";
            
            if (mysqli_query($conn, $sql)) {
                $countSuccess++;
            }
        }
        $message = "<div class='alert alert-success'><strong>Sukses!</strong> Berhasil menyinkronkan $countSuccess data game.</div>";
    } else {
        $msg = $response['msg'] ?? "Gagal terhubung ke API";
        $message = "<div class='alert alert-danger'><strong>Error:</strong> $msg</div>";
    }
}

// Mengambil 100 data terbaru dari database untuk laporan visual
$query_db = mysqli_query($conn, "SELECT * FROM tb_gamelist ORDER BY id DESC LIMIT 100");
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sync Game List - Hypergate API</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background-color: #f1f3f5; }
        .header-box { background: #fff; border-radius: 12px; padding: 30px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
        .table-container { background: #fff; border-radius: 12px; padding: 20px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
        .game-banner { width: 80px; height: auto; border-radius: 5px; }
    </style>
</head>
<body>

<div class="container py-5">
    <div class="row justify-content-center">
        <div class="col-lg-11">
            
            <div class="header-box text-center mb-4">
                <h2 class="fw-bold">Game List Synchronizer</h2>
                <p class="text-muted">Gunakan halaman ini untuk memperbarui database <code>tb_gamelist</code> langsung dari API.</p>
                
                <form method="POST" class="mt-4">
                    <button type="submit" name="sync_games" class="btn btn-dark btn-lg px-5 shadow-sm">
                        Mulai Update Game List
                    </button>
                </form>
                
                <div class="mt-4 text-start">
                    <?php echo $message; ?>
                </div>
            </div>

            <div class="table-container">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 class="mb-0">Data Terbaru (Max 100)</h5>
                    <span class="badge bg-primary">Total Database: <?php echo mysqli_num_rows(mysqli_query($conn, "SELECT id FROM tb_gamelist")); ?></span>
                </div>
                <div class="table-responsive">
                    <table class="table table-striped table-hover align-middle">
                        <thead class="table-light">
                            <tr>
                                <th>Banner</th>
                                <th>Game Name</th>
                                <th>Provider</th>
                                <th>Category</th>
                                <th>RTP</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(mysqli_num_rows($query_db) > 0): ?>
                                <?php while($row = mysqli_fetch_assoc($query_db)): ?>
                                <tr>
                                    <td>
                                        <img src="<?php echo $row['banner']; ?>" alt="banner" class="game-banner border">
                                    </td>
                                    <td>
                                        <div class="fw-bold"><?php echo $row['game_name']; ?></div>
                                        <small class="text-muted">Code: <?php echo $row['game_code']; ?></small>
                                    </td>
                                    <td><span class="badge bg-secondary"><?php echo $row['provider_code']; ?></span></td>
                                    <td><?php echo strtoupper($row['game_category']); ?></td>
                                    <td><span class="text-success fw-bold"><?php echo $row['game_rtp']; ?>%</span></td>
                                    <td>
                                        <?php echo ($row['status'] == 1) ? '<span class="text-success">● Aktif</span>' : '<span class="text-danger">● Nonaktif</span>'; ?>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="6" class="text-center py-4">Belum ada data di tabel <code>tb_gamelist</code></td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>