<?php
require 'config.php'; 

// Function to get the Paystack secret key
$paystack_secret_key = getPaystackSecretKey();

if (!$paystack_secret_key) {
    die("Error: Paystack secret key is missing.");
}

$withdrawal_id = $_POST['withdrawal_id'] ?? 0;

if ($withdrawal_id == 0) {
    die("Invalid request");
}

// Fetch withdrawal details
$stmt = $conn->prepare("SELECT * FROM withdrawals WHERE id = ? AND status = 'pending'");
$stmt->bind_param("i", $withdrawal_id);
$stmt->execute();
$withdrawal = $stmt->get_result()->fetch_assoc();

if (!$withdrawal) {
    die("No pending withdrawal found");
}

// Paystack Transfer (requires payout setup in Paystack)
$data = [
    "source" => "balance",
    "amount" => $withdrawal['amount'] * 100, // Paystack works in kobo (subunits of GHS)
    "currency" => "GHS",
    "recipient" => $withdrawal['user_id'], // Paystack Transfer Recipient ID
    "reason" => "User Withdrawal"
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.paystack.co/transfer");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $paystack_secret_key",
    "Content-Type: application/json"
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true);

if ($result['status']) {
    // Update withdrawal status to completed
    $stmt = $conn->prepare("UPDATE withdrawals SET status = 'completed' WHERE id = ?");
    $stmt->bind_param("i", $withdrawal_id);
    $stmt->execute();

    echo "Withdrawal approved!";
} else {
    echo "Error processing withdrawal: " . $result['message'];
}
?>
