<?php
require_once('session.php');

$id = $_GET['cuid'];
$sql_1 = mysqli_query($conn,"SELECT * FROM `tb_transaksi` WHERE cuid = '$id'") or die(mysqli_error($conn));
$s1 = mysqli_fetch_array($sql_1);

$usersID = $s1['userID'];
$amounts = (int)$s1['total'];

// 🔹 API config
$agent_code  = "terate22";
$agent_token = "770cf7d8671955a7b1caa8761756f6af";
$headerArray = ['Content-Type: application/json'];

if($s1['status'] == 0){
    // 🔹 ambil data user untuk user_code API
    $query = "SELECT * FROM tb_user WHERE cuid='$usersID' LIMIT 1";
    $result = mysqli_query($conn, $query);
    $data   = mysqli_fetch_assoc($result);
    $ext    = $data['extplayer'];

    // 🔹 1. Kembalikan saldo ke lokal
    mysqli_query($conn,"UPDATE `tb_balance` 
                        SET `pending` = pending - '$amounts',
                            `active`  = active + '$amounts'
                        WHERE `userID` = '$usersID'") or die(mysqli_error($conn));

    // 🔹 2. Update status transaksi jadi rejected
    $note = mysqli_real_escape_string($conn, ($s1['note'] ?? '') . " | Withdraw Rejected at ".date('Y-m-d H:i:s')." (rollback by $agent_code)");
    mysqli_query($conn,"UPDATE `tb_transaksi` 
                        SET `status` = 3, `note` = '$note' 
                        WHERE `cuid` = '$id'") or die(mysqli_error($conn));

    // 🔹 3. API DEPOSIT → kembalikan saldo ke server provider
    $postArray = [
        "agent_code"  => $agent_code,
        "agent_token" => $agent_token,
        "user_code"   => $ext,
        "amount"      => $amounts
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://api.88xgame.net/api/v2/user_deposit');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postArray));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);

    $res = curl_exec($ch);
    $decode = json_decode($res, true);
    curl_close($ch);

    // 🔹 log hasil API
    file_put_contents("log_reject_wd.txt", date('c')." | REJECT USER=$ext | AMOUNT=$amounts | API_RES=".json_encode($decode)."\n", FILE_APPEND);

    header('location:../request_wd/?notif=rejected');
    exit();
}

header('location:../request_wd/');
?>
