<?php
error_reporting(0);
ini_set('display_errors', 0);
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
require_once '../config/db.php';

$wallet       = trim($_POST['wallet']       ?? '');
$dest_address = trim($_POST['dest_address'] ?? '');
$amount       = floatval($_POST['amount']   ?? 0);
$type         = trim($_POST['type']         ?? 'income');

// Sirf valid types allow karo
if (!in_array($type, ['income', 'trading'])) {
    $type = 'income';
}

if (empty($wallet) || empty($dest_address) || $amount < 5) {
    echo json_encode(["status" => "error", "message" => "Minimum \$5 and address required."]);
    exit;
}

$safeWallet = mysqli_real_escape_string($conn, $wallet);
$safeAddr   = mysqli_real_escape_string($conn, $dest_address);
$safeType   = mysqli_real_escape_string($conn, $type);

$user = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT account_id, name FROM users WHERE wallet='$safeWallet' LIMIT 1"));
if (!$user) {
    echo json_encode(["status" => "error", "message" => "User not found."]);
    exit;
}

$accId = $user['account_id'];
$uName = mysqli_real_escape_string($conn, $user['name']);
$fee   = round($amount * 0.05, 4);
$net   = round($amount - $fee, 4);
$now   = date('Y-m-d H:i:s');

$sql = "INSERT INTO withdrawals 
            (wallet, account_id, name, amount, fee, net_amount, type, dest_address, status, created_at) 
        VALUES 
            ('$safeWallet', '$accId', '$uName', '$amount', '$fee', '$net', '$safeType', '$safeAddr', 'pending', '$now')";

if (mysqli_query($conn, $sql)) {
    echo json_encode(["status" => "success", "message" => "Withdrawal request submitted!"]);
} else {
    echo json_encode(["status" => "error", "message" => "DB Error: " . mysqli_error($conn)]);
}
?>