<?php
// c:\xampp\htdocs\smart_football\admin\approve_withdrawal.php
require_once '../core/bootstrap.php';

// --- Super Admin Check ---
if (!isset($_SESSION['user_id']) || ($_SESSION['admin_user_role'] ?? '') !== 'super_admin') {
    header('Location: login.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: withdrawal_requests.php');
    exit();
}

$request_id = filter_input(INPUT_POST, 'request_id', FILTER_VALIDATE_INT);
$action = $_POST['action'] ?? '';

if (!$request_id || !in_array($action, ['approve', 'reject'])) {
    header('Location: withdrawal_requests.php');
    exit();
}

$db = new Database();
$walletModel = new Wallet();

// Fetch Request
$db->query("SELECT * FROM withdrawal_requests WHERE id = :id AND status = 'pending'");
$db->bind(':id', $request_id);
$request = $db->single();

if (!$request) {
    $_SESSION['flash_message'] = ['type' => 'error', 'text' => 'Request not found or already processed.'];
    header('Location: withdrawal_requests.php');
    exit();
}

// Find the associated pending wallet transaction
// We match by wallet_id, amount, and approximate time (within 10 seconds)
$db->query("SELECT id FROM wallet_transactions 
            WHERE wallet_id = :wid 
            AND amount = :amt 
            AND type = 'withdrawal' 
            AND status = 'pending' 
            AND created_at BETWEEN DATE_SUB(:created, INTERVAL 10 SECOND) AND DATE_ADD(:created, INTERVAL 10 SECOND) 
            LIMIT 1");
$db->bind(':wid', $request->wallet_id);
$db->bind(':amt', $request->amount);
$db->bind(':created', $request->created_at);
$transaction = $db->single();

if ($action === 'reject') {
    // Use Wallet model to handle rejection (refunds wallet and sets transaction to failed)
    if ($transaction && $walletModel->processWithdrawal($transaction->id, 'reject', 'Rejected by Super Admin', 'super_admin')) {
        $db->query("UPDATE withdrawal_requests SET status = 'rejected', approved_by = :uid WHERE id = :id");
        $db->bind(':uid', $_SESSION['user_id']);
        $db->bind(':id', $request_id);
        $db->execute();
        $_SESSION['flash_message'] = ['type' => 'success', 'text' => 'Withdrawal request rejected and funds refunded.'];
    } else {
        $_SESSION['flash_message'] = ['type' => 'error', 'text' => 'Failed to process rejection (Transaction not found or error).'];
    }
} elseif ($action === 'approve') {
    // Use Wallet model to handle approval (sets transaction to completed)
    if ($transaction && $walletModel->processWithdrawal($transaction->id, 'approve', 'Approved by Super Admin', 'super_admin')) {
        $db->query("UPDATE withdrawal_requests SET status = 'approved', approved_by = :uid WHERE id = :id");
        $db->bind(':uid', $_SESSION['user_id']);
        $db->bind(':id', $request_id);
        $db->execute();
        $_SESSION['flash_message'] = ['type' => 'success', 'text' => 'Withdrawal approved.'];
    } else {
        $_SESSION['flash_message'] = ['type' => 'error', 'text' => 'Failed to approve withdrawal (Transaction not found or error).'];
    }
}

header('Location: withdrawal_requests.php');
exit();
?>
