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

require 'koneksi.php';

/* ===============================
   CONFIG
=============================== */
$SGX_URL   = 'https://sgxcenter.xyz/api';
$SGX_AGENT = 'herlan';
$SGX_SIGN  = '71f419baa20f770ace00398801fb8c4c';

$NX_URL    = 'https://api.nexusggr.com';
$NX_AGENT  = 'zullhayker';
$NX_TOKEN  = 'cd89fda2b27dfa5f5df63030d358a000';

/* ===============================
   SGX BLOCKED PROVIDERS
=============================== */
$SGX_BLOCKED = ['PR','PG','CQ','HB'];

/* ===============================
   CURL JSON HELPER
=============================== */
function postJson(string $url, array $payload): array
{
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
        CURLOPT_POSTFIELDS     => json_encode($payload),
        CURLOPT_TIMEOUT        => 30
    ]);

    $res = curl_exec($ch);
    if ($res === false) {
        die('CURL ERROR: '.curl_error($ch).PHP_EOL);
    }
    curl_close($ch);

    return json_decode($res, true) ?? [];
}

/* ===============================
   INSERT PROVIDER (RULE BASED)
=============================== */
function insertProvider(mysqli $db, array $p, string $api): bool
{
    $code   = mysqli_real_escape_string($db, $p['code']);
    $name   = mysqli_real_escape_string($db, $p['name']);
    $type   = mysqli_real_escape_string($db, strtoupper($p['type'] ?? ''));
    $status = (int)$p['status'];
    $image  = mysqli_real_escape_string($db, $p['image'] ?? '');
    $api    = mysqli_real_escape_string($db, $api);

    if ($api === 'NEXUSGGR') {
        // UNIQUE provider_code
        $cek = mysqli_query(
            $db,
            "SELECT id FROM tb_provider
             WHERE provider_code='$code'
             LIMIT 1"
        );
    } else {
        // SGX: UNIQUE provider_code + provider_type
        $cek = mysqli_query(
            $db,
            "SELECT id FROM tb_provider
             WHERE provider_code='$code'
               AND provider_type='$type'
               AND provider_api='SGX'
             LIMIT 1"
        );
    }

    if (mysqli_num_rows($cek) > 0) {
        return false;
    }

    mysqli_query(
        $db,
        "INSERT INTO tb_provider
         (provider_code, provider_name, provider_type, provider_status, provider_image, provider_api)
         VALUES
         ('$code','$name','$type',$status,'$image','$api')"
    );

    return true;
}

/* ===============================
   1️⃣ SYNC NEXUSGGR (PRIMARY)
=============================== */
echo "SYNC NEXUSGGR (PRIMARY)\n";

$nx = postJson($NX_URL, [
    'method'      => 'provider_list',
    'agent_code'  => $NX_AGENT,
    'agent_token' => $NX_TOKEN
]);

if (($nx['status'] ?? 0) != 1) {
    die("NEXUSGGR ERROR\n");
}

$nxInsert = $nxSkip = 0;

foreach ($nx['providers'] as $p) {
    insertProvider($call, $p, 'NEXUSGGR')
        ? $nxInsert++
        : $nxSkip++;
}

echo "NEXUSGGR INSERTED : $nxInsert\n";
echo "NEXUSGGR SKIPPED  : $nxSkip\n";

/* ===============================
   2️⃣ SYNC SGX (FILTERED)
=============================== */
echo "\nSYNC SGX (FILTERED)\n";

$sgx = postJson($SGX_URL, [
    'command'    => 'provider_list',
    'agent_code' => $SGX_AGENT,
    'signature'  => $SGX_SIGN
]);

if (($sgx['status'] ?? 0) != 200) {
    die("SGX ERROR\n");
}

$sgxInsert = $sgxSkip = 0;

foreach ($sgx['data']['providers'] as $p) {

    // ❌ BLOCK PROVIDER TERTENTU DARI SGX
    if (in_array($p['provider_code'], $SGX_BLOCKED, true)) {
        $sgxSkip++;
        continue;
    }

    $mapped = [
        'code'   => $p['provider_code'],
        'name'   => $p['provider_name'],
        'type'   => $p['provider_type'],
        'status' => $p['provider_status'],
        'image'  => $p['provider_image'] ?? ''
    ];

    insertProvider($call, $mapped, 'SGX')
        ? $sgxInsert++
        : $sgxSkip++;
}

echo "SGX INSERTED : $sgxInsert\n";
echo "SGX SKIPPED  : $sgxSkip\n";

echo "\nDONE UNIFIED PROVIDER SYNC (FINAL RULE)\n";
