<?php
/**
 * CUSTOMER WITHDRAWAL REQUEST API - CLEAN VERSION
 * File: api/customer-withdraw.php
 */

ob_start();
error_reporting(0);
ini_set('display_errors', '0');

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

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

// Check authentication
if (!Auth::check() || Auth::userType() !== 'customer') {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

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

try {
    $db = Database::getInstance();
    $user_id = Auth::id();
    
    // Get and validate input
    $amount = floatval($_POST['amount'] ?? 0);
    $wallet_id = intval($_POST['wallet_id'] ?? 0);
    
    // Validate amount
    if ($amount < 100) {
        throw new Exception('Minimum withdrawal amount is ₦100.00');
    }
    
    // Get wallet
    $wallet = $db->fetch("
        SELECT * FROM wallets 
        WHERE id = ? AND user_id = ? AND user_type = 'customer'
    ", [$wallet_id, $user_id]);
    
    if (!$wallet) {
        throw new Exception('Wallet not found');
    }
    
    // Check balance
    if ($amount > floatval($wallet['balance'])) {
        throw new Exception('Insufficient balance. Available: ₦' . number_format($wallet['balance'], 2));
    }
    
    // Get bank details
    $user = $db->fetch("
        SELECT bank_name, account_name, account_number 
        FROM users 
        WHERE id = ?
    ", [$user_id]);
    
    if (empty($user['bank_name']) || empty($user['account_number'])) {
        throw new Exception('Bank details not set. Please update your profile first.');
    }
    
    // Check for existing pending withdrawal
    $existing = $db->fetch("
        SELECT id FROM withdrawal_requests 
        WHERE user_id = ? AND status = 'pending'
        LIMIT 1
    ", [$user_id]);
    
    if ($existing) {
        throw new Exception('You already have a pending withdrawal request. Please wait for approval.');
    }
    
    // Generate unique reference
    $reference = 'W' . date('ymdHis') . strtoupper(substr(uniqid(), -3));
    
    // Start transaction
    $db->beginTransaction();
    
    try {
        // Insert withdrawal request
        $inserted = $db->execute("
            INSERT INTO withdrawal_requests 
            (user_id, wallet_id, amount, wallet_balance_before, wallet_balance_after, 
             bank_name, account_number, account_name, status, reference, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, NOW())
        ", [
            $user_id,
            $wallet_id,
            $amount,
            $wallet['balance'],
            $wallet['balance'], // Not deducted yet
            $user['bank_name'],
            $user['account_number'],
            $user['account_name'],
            $reference
        ]);
        
        if (!$inserted) {
            throw new Exception('Failed to create withdrawal request');
        }
        
        $withdrawal_id = $db->lastInsertId();
        
        if (!$withdrawal_id || $withdrawal_id == 0) {
            throw new Exception('Failed to get withdrawal ID');
        }
        
        // Commit transaction
        $db->commit();
        
        // Return success
        echo json_encode([
            'success' => true,
            'message' => 'Withdrawal request submitted successfully! Amount: ₦' . number_format($amount, 2) . '. Awaiting admin approval.',
            'withdrawal_id' => $withdrawal_id,
            'reference' => $reference
        ]);
        
    } catch (Exception $e) {
        $db->rollback();
        throw $e;
    }
    
} catch (Exception $e) {
    if (isset($db) && method_exists($db, 'inTransaction') && $db->inTransaction()) {
        $db->rollback();
    }
    
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}