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

require_once __DIR__ . '/../main/API/functions.php';
require_once __DIR__ . '/../function/connect.php';

/*
|--------------------------------------------------------------------------
| AUTO PROVIDER LIST
|--------------------------------------------------------------------------
*/
$providers = [ 
    'GG SOFT',
    '',
    '',
    '',
    '',
    '', 
    '',
    '',
    '', 
    '',
    '',
    '',
    '',
    '',
    '',
    '',
    '',
    '',
    '',
    ''
];

echo "<h2>🚀 IMPORT SEMUA GAME API</h2>";

foreach ($providers as $provider) {

    echo "<h3>📦 Provider: $provider</h3>";

    $res = $SGX->gamelist($provider);

    // CEK RESPONSE
    if (!$res || !isset($res['status']) || $res['status'] != 1) {
        echo "❌ Gagal ambil data dari API<br>";
        continue;
    }

    /*
    |--------------------------------------------------------------------------
    | FLEXIBLE KEY
    |--------------------------------------------------------------------------
    */
    $games = $res['games'] ?? $res['data'] ?? $res['game_list'] ?? [];

    if (empty($games)) {
        echo "⚠️ Tidak ada data game<br>";
        continue;
    }

    /*
    |--------------------------------------------------------------------------
    | DEBUG (AKTIFKAN JIKA MAU CEK STRUKTUR)
    |--------------------------------------------------------------------------
    */
    /*
    echo "<pre>";
    print_r($games[0]);
    echo "</pre>";
    die;
    */

    foreach ($games as $game) {

        // ===============================
        // AMBIL DATA DASAR
        // ===============================
        $game_code = mysqli_real_escape_string($koneksi, $game['game_code'] ?? '');
        $game_name = mysqli_real_escape_string($koneksi, $game['game_name'] ?? '');

        if (empty($game_code)) continue;

        // ===============================
        // AMBIL GAMBAR (FIX ALL API)
        // ===============================
        $image = '';

        // PRIORITAS KEY UMUM API
        $possibleKeys = ['image', 'img', 'icon', 'game_icon', 'thumbnail'];

        foreach ($possibleKeys as $key) {

            if (isset($game[$key])) {

                // jika string langsung
                if (is_string($game[$key]) && !empty($game[$key])) {
                    $image = $game[$key];
                    break;
                }

                // jika array (nested)
                if (is_array($game[$key])) {
                    foreach ($game[$key] as $imgVal) {
                        if (is_string($imgVal) && !empty($imgVal)) {
                            $image = $imgVal;
                            break 2;
                        }
                    }
                }
            }
        }

        // FALLBACK: scan semua field termasuk nested
        if (empty($image)) {

            foreach ($game as $val) {

                // cek nested array
                if (is_array($val)) {
                    foreach ($val as $subVal) {
                        if (is_string($subVal) && strpos($subVal, 'http') !== false) {
                            $image = $subVal;
                            break 2;
                        }
                    }
                }

                // cek string biasa
                if (is_string($val) && strpos($val, 'http') !== false) {
                    $image = $val;
                    break;
                }
            }
        }

        $image = mysqli_real_escape_string($koneksi, $image);

        // ===============================
        // AMBIL GAME TYPE
        // ===============================
        $game_type = '';

        if (isset($game['game_type'])) {
            $game_type = $game['game_type'];
        } elseif (isset($game['gameType'])) {
            $game_type = $game['gameType'];
        } elseif (isset($game['type'])) {
            $game_type = $game['type'];
        }

        $game_type = mysqli_real_escape_string($koneksi, $game_type);

        // ===============================
        // STATUS
        // ===============================
        $status = 'active';

        // ===============================
        // CEK DUPLIKAT
        // ===============================
        $cek = mysqli_query($koneksi, "SELECT id FROM games WHERE game_code='$game_code'");

        if (mysqli_num_rows($cek) > 0) {

            // UPDATE
            mysqli_query($koneksi, "
                UPDATE games SET 
                    game_name='$game_name',
                    images='$image',
                    provider='$provider',
                    game_type='$game_type',
                    status_game='$status'
                WHERE game_code='$game_code'
            ");

            echo "♻️ Update: $game_name <br>";

        } else {

            // INSERT
            mysqli_query($koneksi, "
                INSERT INTO games 
                (game_code, game_name, images, provider, game_type, status_game)
                VALUES
                ('$game_code','$game_name','$image','$provider','$game_type','$status')
            ");

            echo "✅ Insert: $game_name <br>";
        }
    }
}

echo "<br><b>✅ SELESAI IMPORT GAME</b>";