<?php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

include_once __DIR__ . "/config.php";
include_once __DIR__ . "/connection.php";

// Get input JSON
$input = json_decode(file_get_contents("php://input"), true);

$email = trim($input['email'] ?? '');
$amount = floatval($input['amount'] ?? 0);
$walletaddress = trim($input['walletaddress'] ?? '');
$network = trim($input['network'] ?? '');

// Validation
if (!$email) {
    echo json_encode(["success" => false, "message" => "IB email is required"]);
    exit;
}

if ($amount <= 0) {
    echo json_encode(["success" => false, "message" => "Amount must be greater than 0"]);
    exit;
}

if (!$walletaddress) {
    echo json_encode(["success" => false, "message" => "Wallet address is required"]);
    exit;
}

if (!$network) {
    echo json_encode(["success" => false, "message" => "Network is required"]);
    exit;
}

// Generate random reference for the reques
$random = bin2hex(random_bytes(8));

// Insert withdraw request into ib_withdraw_request table
$insert_stmt = $conn->prepare("INSERT INTO ib_withdraw_request 
    (email, total_commission, walletaddress, network, random, status)
    VALUES (?, ?, ?, ?, ?, 0)");
$insert_stmt->bind_param(
    "sdsss",
    $email,
    $amount,
    $walletaddress,
    $network,
    $random
);

$executed = $insert_stmt->execute();
$insert_stmt->close();

if ($executed) {
    echo json_encode([
        "success" => true,
        "message" => "Withdrawal request created successfully",
        "withdraw_amount" => $amount
    ], JSON_PRETTY_PRINT);
} else {
    echo json_encode(["success" => false, "message" => "Failed to create withdrawal request"]);
}
?>
