<?php
require_once '../core/bootstrap.php';

// --- Permission Check ---
requirePermission('withdrawals:manage');

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

$transaction_id = filter_input(INPUT_POST, 'transaction_id', FILTER_VALIDATE_INT);
$action = $_POST['action'] ?? '';
$note = trim($_POST['note'] ?? '');
$current_admin_role = $_SESSION['user_role'] ?? $_SESSION['admin_user_role'] ?? '';

if (!$transaction_id || !in_array($action, ['approve', 'reject'])) {
    $_SESSION['flash_message'] = ['type' => 'error', 'text' => 'Invalid request.'];
    header('Location: withdrawal_requests.php');
    exit();
}

$walletModel = new Wallet();
$notificationModel = new Notification();

// Use standard model logic which handles approval (sets to completed) and rejection (refunds wallet)
$success = $walletModel->processWithdrawal($transaction_id, $action, $note, $current_admin_role);

if ($success) {
    $_SESSION['flash_message'] = ['type' => 'success', 'text' => "Request has been successfully {$action}d."];

    // Notify the user
    $db = new Database();
    $db->query("SELECT w.entity_id FROM wallet_transactions wt JOIN wallets w ON wt.wallet_id = w.id WHERE wt.id = :id AND w.entity_type = 'user'");
    $db->bind(':id', $transaction_id);
    $user_res = $db->single();
    if ($user_res) {
        $user_id = $user_res->entity_id;
        $message = "Your withdrawal request has been {$action}d. " . ($note ? "Note: {$note}" : "");
        $notificationModel->create($user_id, 'withdrawal_status', $message);
    }
} else {
    error_log("Withdrawal Process Failed. Transaction ID: $transaction_id, Action: $action, Role: $current_admin_role");
    $_SESSION['flash_message'] = ['type' => 'error', 'text' => 'Failed to process the request. It might have already been processed or you lack permission for this stage.'];
}

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