<?php
include "config/koneksi.php"; // koneksi ke database

// Request ke API
$postArray = [
    'agent_code'  => 'kingjp',
    'agent_token' => 'e3a31bed75bf563f606eb4adfe12c29a',
    'game_type'   => 'slot' // bisa diganti "casino"
];

$jsonData = json_encode($postArray);

$headerArray = ['Content-Type: application/json'];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.88xgame.net/api/v2/provider_list');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    die("Curl Error: " . curl_error($ch));
}
curl_close($ch);

$result = json_decode($response, true);

// Debug
// echo "<pre>"; print_r($result); echo "</pre>";

if (isset($result['providers']) && is_array($result['providers'])) {
    foreach ($result['providers'] as $prov) {
        $code  = mysqli_real_escape_string($conn, $prov['code']);
        $name  = mysqli_real_escape_string($conn, $prov['name']);
        $gtype = mysqli_real_escape_string($conn, $prov['type']);
        $back  = mysqli_real_escape_string($conn, $prov['backoffice']);

        // Cek apakah provider sudah ada
        $cek = mysqli_query($conn, "SELECT id FROM tb_provider WHERE provider_code='$code' LIMIT 1");
        if (mysqli_num_rows($cek) > 0) {
            mysqli_query($conn, "UPDATE tb_provider 
                SET provider_name='$name', game_type='$gtype', status=1 
                WHERE provider_code='$code'");
        } else {
            mysqli_query($conn, "INSERT INTO tb_provider 
                (provider_code, provider_name, game_type, status) 
                VALUES ('$code','$name','$gtype',1)");
        }
    }
    echo "✅ Provider list berhasil disimpan ke database.";
} else {
    echo "❌ Gagal ambil data dari API.";
}
?>
