<?php
error_reporting(E_ALL);
require_once('session.php');
// Memuat class HGI
require_once('../../config/class.hgi.php'); 

$usersID = mysqli_real_escape_string($conn, $_POST['userID']);
$jumlah = mysqli_real_escape_string($conn, $_POST['nominal']);

// Membersihkan format Rupiah (titik) menjadi angka murni
$amount_str = str_replace('.', '', $jumlah);
$amounts = (float) $amount_str;
$jenis = $_POST['jenis'];

// Ambil data user dari database lokal
$getUser = mysqli_query($conn, "SELECT * FROM `tb_user` WHERE cuid = '$usersID'") or die(mysqli_error($conn));
$gu = mysqli_fetch_array($getUser);
$usernya = $gu['username'];

// Inisialisasi API HGI
$hgi = new HypergateAPI();

// Ambil saldo saat ini dari database lokal
$getBalance = mysqli_query($conn, "SELECT * FROM `tb_balance` WHERE userID = '$usersID'") or die(mysqli_error($conn));
$gb = mysqli_fetch_array($getBalance);
$saldoAktif = $gb['active'];

if ($jenis == 0) {
    // --- PROSES TAMBAH SALDO (DEPOSIT HGI) ---
    $newSaldo = $saldoAktif + $amounts;
    
    // 1. Update ke API HGI
    $res = $hgi->deposit($usernya, (int)$amounts);
    
    if ($res['status'] == 1) {
        // 2. Update Database Lokal jika API Berhasil
        mysqli_query($conn, "UPDATE `tb_balance` SET active = $newSaldo WHERE userID = '$usersID'") or die(mysqli_error($conn));
        header('location:../saldomember.php?notif=1');
        exit;
    } else {
        die("Error HGI Deposit: " . $res['msg']);
    }

} else {
    // --- PROSES KURANG SALDO (WITHDRAW HGI) ---
    $newSaldos = $saldoAktif - $amounts;
    $newSaldo = ($newSaldos < 0) ? 0 : $newSaldos;

    // 1. Update ke API HGI
    $res = $hgi->withdraw($usernya, (int)$amounts);

    if ($res['status'] == 1) {
        // 2. Update Database Lokal jika API Berhasil
        mysqli_query($conn, "UPDATE `tb_balance` SET active = $newSaldo WHERE userID = '$usersID'") or die(mysqli_error($conn));
        header('location:../saldomember.php?notif=1');
        exit;
    } else {
        die("Error HGI Withdraw: " . $res['msg']);
    }
}
?>