<?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";

$input = json_decode(file_get_contents("php://input"), true);
$action  = $input['action'] ?? '';
$email   = trim($input['email'] ?? '');

if ($email === "") {
    echo json_encode(["success" => false, "message" => "Email missing"]);
    exit;
}

// Helper: Generate OTP
function generateOTP($length = 6) {
    return str_pad(rand(0, pow(10, $length) - 1), $length, "0", STR_PAD_LEFT);
}

//////////////////////////////////////////////////////////////
// STEP 1: INITIATE IB WITHDRAW
//////////////////////////////////////////////////////////////
if ($action === "initiate_ib_withdraw") {

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

    if ($amount <= 0) {
        echo json_encode(["success" => false, "message" => "Enter valid amount"]);
        exit;
    }

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

    // Generate OTP + reference
    $otp        = generateOTP();
    $otp_expiry = time() + 600; // 10 minutes
    $random_ref = bin2hex(random_bytes(8));

    // INSERT pending record
    $stmt = $conn->prepare("
        INSERT INTO pending_ib_withdrawals 
        (email, amount, walletaddress, network, reference, otp, otp_expiry)
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->bind_param(
        "sdssssi",
        $email,
        $amount,
        $walletaddress,
        $network,
        $random_ref,
        $otp,
        $otp_expiry
    );

    if (!$stmt->execute()) {
        echo json_encode(["success" => false, "message" => "Failed to store OTP", "sql_error" => $stmt->error]);
        exit;
    }

    $pending_id = $stmt->insert_id;

    echo json_encode([
        "success"    => true,
        "message"    => "OTP sent successfully",
        "pending_id" => $pending_id,
        "otp"        => $otp // remove in production
    ]);
    exit;
}

//////////////////////////////////////////////////////////////
// STEP 2: VERIFY OTP + CREATE FINAL WITHDRAW RECORD
//////////////////////////////////////////////////////////////
if ($action === "verify_ib_otp") {

    $pending_id = intval($input['pending_id'] ?? 0);
    $otp_input  = trim($input['otp'] ?? '');

    if ($pending_id <= 0 || $otp_input === "") {
        echo json_encode(["success" => false, "message" => "Missing OTP or Pending ID"]);
        exit;
    }

    // Fetch pending entry
    $stmt = $conn->prepare("SELECT * FROM pending_ib_withdrawals WHERE id = ? AND email = ?");
    $stmt->bind_param("is", $pending_id, $email);
    $stmt->execute();
    $res = $stmt->get_result();

    if ($res->num_rows === 0) {
        echo json_encode(["success" => false, "message" => "Invalid request or already used"]);
        exit;
    }

    $row = $res->fetch_assoc();

    // Check expiry
    if (time() > $row['otp_expiry']) {
        $conn->query("DELETE FROM pending_ib_withdrawals WHERE id = $pending_id");
        echo json_encode(["success" => false, "message" => "OTP expired"]);
        exit;
    }

    // Check OTP
    if ($otp_input !== $row['otp']) {
        echo json_encode(["success" => false, "message" => "Invalid OTP"]);
        exit;
    }

    $insert = $conn->prepare("
    INSERT INTO ib_withdraw_request
    (email, trade_ids, total_commission, walletaddress, network, `type`, random, status)
    VALUES (?, ?, ?, ?, ?, ?, ?, 0)
");

$empty_trade_ids = "";
$withdraw_type   = "IB Commission";

$insert->bind_param(
    "ssdssss",
    $row['email'],        // email
    $empty_trade_ids,     // trade_ids
    $row['amount'],       // total_commission
    $row['walletaddress'],// walletaddress
    $row['network'],      // network
    $withdraw_type,       // type
    $row['reference']     // random
);


    if (!$insert->execute()) {
        echo json_encode([
            "success"   => false,
            "message"   => "Failed to store withdrawal",
            "sql_error" => $insert->error
        ]);
        exit;
    }

    $request_id = $conn->insert_id;

    // DELETE pending record
    $conn->query("DELETE FROM pending_ib_withdrawals WHERE id = $pending_id");

    echo json_encode([
        "success"   => true,
        "message"   => "IB Withdrawal request submitted",
        "request_id"=> $request_id,
        "amount"    => $row['amount'],
        "reference" => $row['reference']
    ]);
    exit;
}

//////////////////////////////////////////////////////////////

echo json_encode(["success" => false, "message" => "Invalid action"]);
exit;
?>
