<?php
include 'config.php';
require 'vendor/autoload.php'; // Make sure Paystack SDK is available, or use curl

// Load API key from .env or directly from config
$paystackSecretKey = getenv('PAYSTACK_SECRET_KEY'); // or use your method

// Get Super-Admin ID
session_start();
$adminId = $_SESSION['user_id']; // Adjust if you use a different session key

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $amount = floatval($_POST['amount']);
    $userIds = $_POST['users'] ?? [];

    if ($amount <= 0 || empty($userIds)) {
        die('Invalid amount or no users selected.');
    }

    // Convert to kobo (Paystack expects amounts in kobo)
    $amountKobo = intval($amount * 100);

    // Collect recipient codes for each user
    $recipients = [];
    foreach ($userIds as $userId) {
        // Fetch user details from the database
        $stmt = $conn->prepare("SELECT username, phone, email FROM users WHERE id = ?");
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($user = $result->fetch_assoc()) {
            $username = $user['username'];
            $phone = $user['phone'];
            $email = $user['email'];

            // Prepare recipient data for Paystack
            $recipientData = [
                'type' => 'mobile_money',
                'name' => $username,
                'account_number' => $phone,
                'bank_code' => 'MTN', // Replace with dynamic bank codes if needed
                'currency' => 'GHS'
            ];

            // Send the recipient data to Paystack to create a recipient
            $ch = curl_init('https://api.paystack.co/transferrecipient');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                "Authorization: Bearer $paystackSecretKey",
                "Content-Type: application/json",
            ]);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($recipientData));
            $recipientResponse = curl_exec($ch);
            $recipientResult = json_decode($recipientResponse, true);
            curl_close($ch);

            if (isset($recipientResult['status']) && $recipientResult['status'] === true) {
                $recipientCode = $recipientResult['data']['recipient_code'];

                // Add recipient to the transfers array
                $recipients[] = [
                    'recipient' => $recipientCode,
                    'amount' => $amountKobo,
                    'reason' => "Bulk Transfer to $username",
                    'user_id' => $userId,
                    'phone' => $phone,
                ];
            } else {
                // Log or handle recipient creation failure
                echo "Failed to create recipient for user: $username. Skipping this user.<br>";
            }
        }
    }

    if (count($recipients) === 0) {
        die("No valid recipients found.");
    }

    // Create Bulk Transfer
    $ch = curl_init('https://api.paystack.co/transfer/bulk');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $paystackSecretKey",
        "Content-Type: application/json",
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['transfers' => $recipients]));
    $bulkResponse = curl_exec($ch);
    $bulkResult = json_decode($bulkResponse, true);
    curl_close($ch);

    if (isset($bulkResult['status']) && $bulkResult['status'] === true) {
        // Store payouts in DB
        foreach ($recipients as $r) {
            $stmt = $conn->prepare("INSERT INTO tbl_payouts (admin_id, recipient_name, phone, amount, status, paystack_transfer_code, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())");
            $status = 'Processing'; // Set initial status to 'Processing'
            $transferCode = ''; // Paystack doesn’t return individual codes in bulk API – this is optional
            $stmt->bind_param("issdss", $adminId, $r['recipient'], $r['phone'], $amount, $status, $transferCode);
            $stmt->execute();
        }

        // Redirect to a success page
        header("Location: deposit-admin.php?bulk=success");
        exit;
    } else {
        echo "Bulk transfer failed: " . $bulkResult['message'];
    }
} else {
    echo "Invalid request method.";
}
?>
