<?php
include 'koneksi.php';

// === KONFIGURASI CHAOSAPI ===
$apiUrl = "https://api.dyonvip.site/v2/GetGamelist.aspx";
$agent_code = "zulhayker";
$secret_key = "22c4b849b6602e3d4c29ead4bf1e6e5b";

// === GANTI PROVIDER SESUAI YANG INGIN DIAMBIL ===
$provider = "PG"; // contoh: PR, PG, HB, CQ, EP

// === PERSIAPAN DATA POST ===
$postData = [
    "agent_code"   => $agent_code,
    "secret_key"   => $secret_key,
    "provider_code" => $provider
];

// === REQUEST KE CHAOSAPI ===
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);

// === PROSES RESPONSE ===
if (isset($data['status']) && $data['status'] === 'success' && !empty($data['games'])) {
    foreach ($data['games'] as $game) {
        $game_code     = mysqli_real_escape_string($call, $game['game_code']);
        $game_name     = mysqli_real_escape_string($call, $game['game_name']);
        $game_provider = mysqli_real_escape_string($call, $game['game_provider']);
        $game_type     = mysqli_real_escape_string($call, $game['game_type']);
        $game_image    = mysqli_real_escape_string($call, $game['game_image']);
        $game_status   = (int)$game['game_status'];
        $provider_api  = 'CHAOSAPI';

        // Insert atau Update
        $sql = "
            INSERT INTO tb_game (game_code, game_name, game_provider, game_type, game_image, game_status, provider_api)
            VALUES ('$game_code', '$game_name', '$game_provider', '$game_type', '$game_image', '$game_status', '$provider_api')
            ON DUPLICATE KEY UPDATE 
                game_name='$game_name',
                game_provider='$game_provider',
                game_type='$game_type',
                game_image='$game_image',
                game_status='$game_status',
                provider_api='$provider_api'
        ";
        mysqli_query($call, $sql);
    }

    echo "Provider $provider: berhasil diperbarui (" . count($data['games']) . " game).<br>";
} else {
    echo "Provider $provider: gagal mengambil data atau tidak ada game.<br>";
    if (isset($data['msg'])) {
        echo "Pesan: " . $data['msg'] . "<br>";
    }
}

echo "Proses selesai.";
?>
