<?php
header('Content-Type: application/json');
require_once '../config/db.php';

$id     = intval($_POST['id'] ?? 0);
$action = $_POST['action'] ?? '';

if (!$id || !in_array($action, ['completed', 'rejected'])) {
    echo json_encode(["status" => "error", "message" => "Invalid input"]);
    exit;
}

$id = intval($id);

// Get withdrawal details
$w = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM withdrawals WHERE id = $id LIMIT 1"));

if (!$w) {
    echo json_encode(["status" => "error", "message" => "Withdrawal not found"]);
    exit;
}

if ($w['status'] !== 'pending') {
    echo json_encode(["status" => "error", "message" => "Already processed"]);
    exit;
}

mysqli_begin_transaction($conn);

try {
    // Update withdrawal status
    mysqli_query($conn, "UPDATE withdrawals SET status = '$action' WHERE id = $id");

    // If rejected — refund balance back to user
    if ($action === 'rejected') {
        $wallet = mysqli_real_escape_string($conn, $w['wallet']);
        $amount = floatval($w['amount']);
        mysqli_query($conn, "UPDATE users SET balance = balance + $amount WHERE wallet = '$wallet'");
    }

    mysqli_commit($conn);
    echo json_encode(["status" => "success", "message" => "Withdrawal " . $action]);

} catch (Exception $e) {
    mysqli_rollback($conn);
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
}