<?php
require_once __DIR__ . '/bootstrap.php';
// endpoints/withdraw.php

$auth   = requireAuth();
$userId = $auth['user_id'];
$db     = Database::getInstance();

// POST /withdraw/submit
if ($method === 'POST' && strpos($uri, '/withdraw/submit') !== false) {
    $amount       = (float)($input['amount'] ?? 0);
    $currency     = sanitize($input['currency'] ?? 'USDT');
    $walletAddr   = sanitize($input['wallet_address'] ?? '');
    $walletFrom   = sanitize($input['wallet_from'] ?? 'interest'); // 'deposit' or 'interest'

    if ($amount <= 0 || !$walletAddr) jsonError('Amount and wallet address are required.');
    if ($amount < (float)MIN_WITHDRAWAL) jsonError('Minimum withdrawal is $' . MIN_WITHDRAWAL . '.');
    if (!in_array($walletFrom, ['deposit','interest'])) $walletFrom = 'interest';

    $user = $db->fetch("SELECT deposit_balance, interest_balance, kyc_status FROM users WHERE id=?", [$userId]);
    $balance = $walletFrom === 'interest' ? (float)$user['interest_balance'] : (float)$user['deposit_balance'];

    if ($balance < $amount) jsonError("Insufficient balance. Available: $" . number_format($balance, 2));

    // Deduct balance
    if ($walletFrom === 'interest') {
        $db->query("UPDATE users SET interest_balance=interest_balance-? WHERE id=?", [$amount, $userId]);
    } else {
        $db->query("UPDATE users SET deposit_balance=deposit_balance-? WHERE id=?", [$amount, $userId]);
    }

    $wdId = $db->insert(
        "INSERT INTO withdrawals (user_id, amount, currency, wallet_address, wallet_type, wallet_from) VALUES (?,?,?,?,?,?)",
        [$userId, $amount, $currency, $walletAddr, $currency, $walletFrom]
    );

    $db->insert(
        "INSERT INTO transactions (user_id,type,amount,description,reference_id,wallet,status) VALUES (?,?,?,?,?,?,?)",
        [$userId, 'withdrawal', $amount, "Withdrawal of $$amount to $walletAddr (Pending)", $wdId, $walletFrom, 'pending']
    );

    jsonSuccess(['withdrawal_id' => $wdId], 'Withdrawal request submitted. Processing within 24 hours.');
}

// GET /withdraw/history
if ($method === 'GET' && strpos($uri, '/withdraw/history') !== false) {
    $page  = max(1, (int)($_GET['page'] ?? 1));
    $limit = 20;
    $offset= ($page - 1) * $limit;

    $total = $db->fetch("SELECT COUNT(*) as cnt FROM withdrawals WHERE user_id=?", [$userId])['cnt'];
    $wds   = $db->fetchAll("SELECT * FROM withdrawals WHERE user_id=? ORDER BY created_at DESC LIMIT $limit OFFSET $offset", [$userId]);
    jsonSuccess(['withdrawals'=>$wds,'total'=>(int)$total,'page'=>$page,'pages'=>ceil($total/$limit)]);
}
