<?php
include 'db/koneksi.php';
include 'api/nexus.php';
include 'api/sgx.php';
header('Content-Type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', 1);

if (session_status() == PHP_SESSION_NONE) session_start();

$logFile = __DIR__ . '/api_result.log';
function writeLog($msg, $file) {
    $time = date("Y-m-d H:i:s");
    file_put_contents($file, "[$time] $msg\n", FILE_APPEND);
}

$nama_pengguna = $_SESSION['username'] ?? null;
$ext = $_SESSION['extplayer'] ?? null;

if (!$nama_pengguna) {
    echo json_encode([
        'ok' => false,
        'message' => 'Belum login'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $nexusRaw = $nx->info_member($ext);
    $nexus = json_decode($nexusRaw);
    writeLog("NEXUS API Raw: " . $nexusRaw, $logFile);

    if (!isset($nexus->status) || $nexus->status != 1) {
        writeLog("NEXUS API ERROR: " . $nexusRaw, $logFile);
        exit("Gagal ambil saldo Nexus");
    }
    $saldo_nexus = (float)($nexus->user->balance ?? 0);

    $sgxRaw = $SGX->info_member($ext);
    $sgx = json_decode($sgxRaw);
    writeLog("SGX API Raw: " . $sgxRaw, $logFile);

    if (!isset($sgx->status) || $sgx->status != 200) {
        writeLog("SGX API ERROR: " . $sgxRaw, $logFile);
        exit("Gagal ambil saldo SGX");
    }
    $saldo_sgx = (float)($sgx->data->balance ?? 0);

    $stmt = $koneksi->prepare("SELECT saldo_nexus, saldo_sgx FROM tb_user WHERE username = ?");
    $stmt->bind_param("s", $nama_pengguna);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    $last_telo = (float)($res['saldo_nexus'] ?? $saldo_nexus);
    $last_sgx  = (float)($res['saldo_sgx'] ?? $saldo_sgx);

    $delta_telo = $saldo_nexus - $last_telo;
    $delta_sgx  = $saldo_sgx - $last_sgx;

    writeLog("SYNC LOG [$nama_pengguna]: LastNexus=$last_telo, LastSgx=$last_sgx, CurrNexus=$saldo_nexus, CurrSgx=$saldo_sgx, DeltaNexus=$delta_telo, DeltaSgx=$delta_sgx", $logFile);

    $finalBalance = $saldo_nexus; // default
    if (abs($delta_telo) > 0 && abs($delta_telo) >= abs($delta_sgx)) {
        $finalBalance = $saldo_nexus;
        if ($saldo_nexus > $saldo_sgx) {
            $res = $SGX->deposit_member($ext, $saldo_nexus - $saldo_sgx);
            writeLog("SYNC ACTION: TELO naik +" . ($saldo_nexus - $saldo_sgx) . " → SGX ikut DEPOSIT. Result=$res", $logFile);
        } elseif ($saldo_nexus < $saldo_sgx) {
            $res = $SGX->withdraw_member($ext, $saldo_sgx - $saldo_nexus);
            writeLog("SYNC ACTION: TELO turun -" . ($saldo_sgx - $saldo_nexus) . " → SGX ikut WITHDRAW. Result=$res", $logFile);
        }
    } elseif (abs($delta_sgx) > 0 && abs($delta_sgx) > abs($delta_telo)) {
        $finalBalance = $saldo_sgx;
        if ($saldo_sgx > $saldo_nexus) {
            $res = $nx->deposit_member($ext, $saldo_sgx - $saldo_nexus);
            writeLog("SYNC ACTION: SGX naik +" . ($saldo_sgx - $saldo_nexus) . " → NEXUS ikut DEPOSIT. Result=$res", $logFile);
        } elseif ($saldo_sgx < $saldo_nexus) {
            $res = $nx->withdraw_member($ext, $saldo_nexus - $saldo_sgx);
            writeLog("SYNC ACTION: SGX turun -" . ($saldo_nexus - $saldo_sgx) . " → NEXUS ikut WITHDRAW. Result=$res", $logFile);
        }
    } else {
        writeLog("INFO: Tidak ada perubahan signifikan [$nama_pengguna].", $logFile);
    }

    // 🔹 Update database dan session agar nilainya SAMA
    $update = $koneksi->prepare("UPDATE tb_user SET saldo_nexus=?, saldo_sgx=?, saldo=? WHERE username=?");
    $update->bind_param("ddds", $finalBalance, $finalBalance, $finalBalance, $nama_pengguna);
    $update->execute();
    $update->close();

    $_SESSION['saldo'] = $finalBalance;

    writeLog("SYNC DONE [$nama_pengguna]: FinalBalance=$finalBalance", $logFile);

    //echo "IDR" . number_format($finalBalance, 0, ',', '.');
    echo json_encode([
        'ok' => true,
        'balance' => $finalBalance,
        'formatted' => 'IDR ' . number_format($finalBalance, 0, ',', '.')
    ], JSON_UNESCAPED_UNICODE);

} catch (Exception $e) {
    writeLog("SYNC ERROR [$nama_pengguna]: " . $e->getMessage(), $logFile);
    echo "Terjadi kesalahan sinkronisasi";
}
