<?php
/**
 * API: Withdrawal Request
 * Location: api/request-withdrawal.php
 * Handles withdrawal requests
 */

require_once '../app/Core/init.php';

// Suppress all warnings/notices for clean JSON output
error_reporting(E_ERROR | E_PARSE);
ini_set('display_errors', '0');

header('Content-Type: application/json');

if (!Auth::isLoggedIn()) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

$user_id = Auth::getUserId();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Invalid request method']);
    exit;
}

$wallet_type = $_POST['wallet_type'] ?? '';
$amount = (float)$_POST['amount'] ?? 0;
$bank_name = trim($_POST['bank_name'] ?? '');
$account_number = trim($_POST['account_number'] ?? '');
$account_name = trim($_POST['account_name'] ?? '');

if (!$wallet_type || $amount <= 0 || !$bank_name || !$account_number || !$account_name) {
    echo json_encode(['success' => false, 'error' => 'All fields are required']);
    exit;
}

// Minimum withdrawal amount
if ($amount < 1000) {
    echo json_encode(['success' => false, 'error' => 'Minimum withdrawal amount is ₦1,000']);
    exit;
}

try {
    $withdrawalService = new WithdrawalService();
    
    $bank_details = [
        'bank_name' => $bank_name,
        'account_number' => $account_number,
        'account_name' => $account_name
    ];
    
    $result = $withdrawalService->createRequest($user_id, $wallet_type, $amount, $bank_details);
    
    if (!$result['success']) {
        throw new Exception($result['error']);
    }
    
    // Send notification (optional - won't break if email fails)
    try {
        $notificationService = new NotificationService();
        $notificationService->notifyWithdrawalRequest($user_id, $amount);
    } catch (Exception $e) {
        // Log error but don't break the withdrawal
        error_log("Email notification failed (not critical): " . $e->getMessage());
    }

    echo json_encode([
        'success' => true,
        'message' => 'Withdrawal request submitted successfully. It will be processed within 24-48 hours.',
        'reference' => $result['reference']
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}