<?php
// paystack_functions.php

function initiate_bulk_paystack_transfer($withdrawals) {
    // Prepare transfer data
    $transfers = [];
    
    foreach ($withdrawals as $withdrawal) {
        $transfers[] = [
            'email' => $withdrawal['email'],
            'phone' => $withdrawal['phone'],
            'amount' => $withdrawal['amount'] * 100, // Paystack API expects amount in kobo (100 kobo = 1 GHS)
            'reason' => "Withdrawal for " . $withdrawal['username']
        ];
    }

    // Prepare payload
    $data = [
        'transfer_group' => 'withdrawal-' . time(),
        'transfers' => $transfers
    ];

    $api_key = getenv('PAYSTACK_SECRET_KEY');  // Ensure this is set in your .env file
    $url = 'https://api.paystack.co/transfer/bulk';
    
    // Initialize cURL
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $api_key,
        'Content-Type: application/json'
    ]);
    
    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);

    if ($error) {
        throw new Exception('Error executing Paystack API request: ' . $error);
    }
    
    $response_data = json_decode($response, true);

    if ($response_data['status'] === true) {
        return $response_data['data'];  // Return data (transfer batch details)
    } else {
        throw new Exception('Paystack Bulk Transfer failed: ' . $response_data['message']);
    }
}
?>
