<?php

session_start();

header("Access-Control-Allow-Origin: https://enerliths.com");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json");

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

require_once "../config/db.php";

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

$user_id = $data["user_id"] ?? null;
$withdraw_amount = floatval($data["amount"] ?? 0); // what user receives
$address = trim($data["address"] ?? "");

$network_fee = 1; // TRC20 fee

$total_deduct = $withdraw_amount + $network_fee;

if($total_deduct < 5){
    echo json_encode(["success"=>false,"error"=>"Minimum withdrawal is $5"]);
    exit;
}

if(!$user_id){
    echo json_encode([
        "success"=>false,
        "error"=>"User session expired"
    ]);
    exit;
}

if($withdraw_amount <= 0){
    echo json_encode([
        "success"=>false,
        "error"=>"Invalid withdrawal amount"
    ]);
    exit;
}

if(strlen($address) < 20){
    echo json_encode([
        "success"=>false,
        "error"=>"Invalid wallet address"
    ]);
    exit;
}

/* START TRANSACTION */

$conn->begin_transaction();

try{

    /* LOCK USER BALANCE */

    $stmt = $conn->prepare("SELECT balance FROM users WHERE id=? FOR UPDATE");
    $stmt->bind_param("i",$user_id);
    $stmt->execute();

    $result = $stmt->get_result();

    if($result->num_rows === 0){
        throw new Exception("User not found");
    }

    $row = $result->fetch_assoc();
    $balance = floatval($row["balance"]);

    if($total_deduct > $balance){
        throw new Exception("Insufficient balance");
    }

    /* INSERT WITHDRAW REQUEST */

    $stmt = $conn->prepare("INSERT INTO crypto_withdrawals
    (user_id,amount,wallet_address,network)
    VALUES (?,?,?,?)");

    $network = "TRC20";

    $stmt->bind_param(
        "idss",
        $user_id,
        $withdraw_amount,
        $address,
        $network
    );

    if(!$stmt->execute()){
        throw new Exception("Withdrawal insert failed");
    }

    /* DEDUCT BALANCE INCLUDING FEE */

    $stmt = $conn->prepare("UPDATE users SET balance = balance - ? WHERE id=?");

    $stmt->bind_param(
        "di",
        $total_deduct,
        $user_id
    );

    if(!$stmt->execute()){
        throw new Exception("Balance update failed");
    }

    $conn->commit();

    echo json_encode([
        "success"=>true
    ]);

}catch(Exception $e){

    $conn->rollback();

    echo json_encode([
        "success"=>false,
        "error"=>$e->getMessage()
    ]);
}
