<?php
/**
 * API: Process Withdrawal (Admin)
 * Location: api/process-withdrawal.php
 * Handles withdrawal approval/rejection by admin
 */

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

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

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

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

$action = $_POST['action'] ?? '';
$request_id = (int)$_POST['request_id'] ?? 0;

if (!$action || !$request_id) {
    echo json_encode(['success' => false, 'error' => 'Missing required fields']);
    exit;
}

try {
    $withdrawalService = new WithdrawalService();
    $admin_id = Auth::getUserId();
    
    if ($action === 'approve') {
        $result = $withdrawalService->approveRequest($request_id, $admin_id);
        
        if ($result['success']) {
            echo json_encode([
                'success' => true,
                'message' => 'Withdrawal approved successfully'
            ]);
        } else {
            throw new Exception($result['error']);
        }
        
    } elseif ($action === 'reject') {
        $reason = $_POST['reason'] ?? 'Rejected by admin';
        $result = $withdrawalService->rejectRequest($request_id, $admin_id, $reason);
        
        if ($result['success']) {
            echo json_encode([
                'success' => true,
                'message' => 'Withdrawal rejected'
            ]);
        } else {
            throw new Exception($result['error']);
        }
        
    } else {
        throw new Exception('Invalid action');
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
