<?php
/**
 * API - Create Withdrawal Request
 */
header('Content-Type: application/json');

require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../includes/functions.php';
require_once '../../includes/Auth.php';

if (!auth()->isUserLoggedIn()) {
    jsonError('Unauthorized', 401);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonError('Method not allowed', 405);
}

$user = auth()->refreshUser();
$input = json_decode(file_get_contents('php://input'), true) ?: $_POST;

$amount = (float)($input['amount'] ?? 0);
$method = $input['method'] ?? '';

$minWithdraw = (float)getSetting('min_withdrawal', 1000);
$maxWithdraw = (float)getSetting('max_withdrawal', 100000);
$feePercent = (float)getSetting('withdrawal_fee_percent', 2);

if ($amount < $minWithdraw) {
    jsonError('Minimum withdrawal is ' . formatCurrency($minWithdraw));
}

if ($amount > $user['balance']) {
    jsonError('Insufficient balance');
}

if ($amount > $maxWithdraw) {
    jsonError('Maximum withdrawal is ' . formatCurrency($maxWithdraw));
}

$fee = $amount * ($feePercent / 100);
$netAmount = $amount - $fee;

$withdrawalId = 'WDR' . strtoupper(substr(md5(uniqid()), 0, 10));

$data = [
    'withdrawal_id' => $withdrawalId,
    'user_id' => $user['id'],
    'amount' => $amount,
    'fee' => $fee,
    'net_amount' => $netAmount,
    'payment_method' => $method,
    'status' => 'pending'
];

if ($method === 'upi') {
    $data['upi_id'] = $input['upi_id'] ?? '';
} elseif ($method === 'bank_transfer') {
    $data['bank_name'] = $input['bank_name'] ?? '';
    $data['account_number'] = $input['account_number'] ?? '';
    $data['ifsc_code'] = $input['ifsc_code'] ?? '';
    $data['account_holder'] = $input['account_holder'] ?? '';
} elseif ($method === 'crypto') {
    $data['wallet_address'] = $input['wallet_address'] ?? '';
    $data['network'] = $input['network'] ?? 'TRC20';
}

dbInsert('withdrawals', $data);

// Deduct balance
dbUpdate('users', ['balance' => $user['balance'] - $amount], 'id = :id', ['id' => $user['id']]);

// Log transaction
dbInsert('transactions', [
    'transaction_id' => 'TXN' . strtoupper(substr(md5(uniqid()), 0, 10)),
    'user_id' => $user['id'],
    'type' => 'withdrawal',
    'amount' => -$amount,
    'balance_after' => $user['balance'] - $amount,
    'description' => 'Withdrawal request: ' . $withdrawalId
]);

jsonSuccess('Withdrawal request submitted', [
    'withdrawal_id' => $withdrawalId,
    'amount' => $amount,
    'fee' => $fee,
    'net_amount' => $netAmount
]);
