<?php

include '../db/koneksi.php';
include '../api/nexus.php';
include '../api/sgx.php';
session_start();

header('Content-Type: application/json');

if (!isset($_SESSION['username']) || !isset($_SESSION['extplayer'])) {
    echo json_encode(['status' => 'error', 'message' => 'Sesi login tidak valid.']);
    exit;
}

$extplayer   = $_SESSION['extplayer'];
$username    = $_SESSION['username'];
$bank_tujuan = $_POST['bank'] ?? '';
$amount = $_POST['amount'] ?? '0';

$cleanAmount = preg_replace('/[^0-9]/', '', $amount);
$jumlah = (int)$cleanAmount;

$min = 50000;
$max = 100000000;
if ($jumlah < $min) {
    echo json_encode(['status' => 'error', 'message' => 'Minimal withdraw adalah Rp ' . number_format($min, 0, ',', '.')]);
    exit;
}
if ($jumlah > $max) {
    echo json_encode(['status' => 'error', 'message' => 'Maksimal withdraw adalah Rp ' . number_format($max, 0, ',', '.')]);
    exit;
}

$q = mysqli_query($koneksi, "SELECT * FROM tb_user WHERE extplayer = '$extplayer'");
if (!$q || mysqli_num_rows($q) == 0) {
    echo json_encode(['status' => 'error', 'message' => 'User tidak ditemukan.']);
    exit;
}

$d = mysqli_fetch_assoc($q);
$saldo = intval($d['saldo']);
$bank_tujun = $d['bank'].' - '. $d['nama_rekening']. ' - '. $d['nomor_rekening'];
if ($jumlah > $saldo) {
    echo json_encode(['status' => 'error', 'message' => 'Saldo tidak mencukupi.']);
    exit;
}

$ref = 'WD' . date('YmdHis') . strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 6));
$sql = "INSERT INTO tb_withdraw (extplayer, username, ref, jumlah, bank_asal, status, created_at, updated_at)
        VALUES ('$extplayer', '$username', '$ref', '$jumlah', '$bank_tujuan', 'Pending', NOW(), NOW())";

if (mysqli_query($koneksi, $sql)) {
    mysqli_query($koneksi, "UPDATE tb_user SET saldo = saldo - $jumlah WHERE extplayer = '$extplayer'");
    $nx->withdraw_member($extplayer, $jumlah);
    $SGX->withdraw_member($extplayer, $jumlah);

    echo json_encode(['status' => 'success', 'message' => 'Permintaan withdraw berhasil diajukan. Menunggu konfirmasi admin.']);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Gagal menyimpan data withdraw: ' . mysqli_error($koneksi)]);
}
