<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

if ($c['level'] == "superadmin") {

    require_once __DIR__ . '/../../../../function/class.goldslot.php';

    // Ambil config dari database
    $config = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT api_token, callback_token FROM tb_goldslot_config LIMIT 1"));

    if (!$config || empty($config['api_token'])) {
        echo "<script>alert('Konfigurasi GoldSlotPalace belum diatur!'); window.location='?page=goldslot&sub=config';</script>";
        exit;
    }

    $goldslot = new GoldSlotPalace($config['api_token'], $config['callback_token']);

    // Ambil daftar provider
    $res = $goldslot->getProviders(1); // 1 = English

    if (!GoldSlotPalace::isSuccess($res)) {
        $errorMsg = GoldSlotPalace::getErrorMessage($res);
        $rawDebug = print_r($res, true);
        $rawDebug = str_replace(["\n", "\r", "'", '"'], [' ', ' ', "\'", '\"'], substr($rawDebug, 0, 500));
        echo "<script>alert('Gagal sync provider: $errorMsg\\n\\nRaw: $rawDebug'); window.location='?page=goldslot&sub=config';</script>";
        exit;
    }

    $providers = $res['data'] ?? [];
    $synced = 0;
    $failed = 0;

    if (!empty($providers)) {
        foreach ($providers as $prov) {
            $providerId   = (int)$prov['provider_id'];
            $providerName = mysqli_real_escape_string($koneksi, $prov['provider_name']);
            $localeName   = mysqli_real_escape_string($koneksi, $prov['locale_name'] ?? $prov['provider_name']);
            $status       = (int)$prov['status'];

            // Cek apakah sudah ada di database
            $check = mysqli_query($koneksi, "SELECT id FROM tb_goldslot_providers WHERE provider_id = '$providerId' LIMIT 1");

            if (mysqli_num_rows($check) > 0) {
                // Update
                $update = mysqli_query($koneksi, "
                    UPDATE tb_goldslot_providers SET 
                        provider_name = '$providerName',
                        locale_name   = '$localeName',
                        status        = '$status',
                        last_sync     = NOW()
                    WHERE provider_id = '$providerId'
                ");
            } else {
                // Insert baru
                $insert = mysqli_query($koneksi, "
                    INSERT INTO tb_goldslot_providers (provider_id, provider_name, locale_name, status, last_sync) 
                    VALUES ('$providerId', '$providerName', '$localeName', '$status', NOW())
                ");
            }

            $synced++;
        }
    }

    echo "<script>alert('Sync selesai! $synced provider berhasil disinkronisasi.'); window.location='?page=goldslot&sub=config';</script>";

} else {
    echo "<script>window.location='?page=dashboard';</script>";
}
?>