<?php
session_start();
require 'config.php';
require 'vendor/autoload.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Ensure only Super-Admins can access this
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'super-admin') {
    die("Unauthorized access.");
}

// Load .env and get Paystack secret key
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

$paystackSecretKey = $_ENV['PAYSTACK_SECRET_KEY'];
$adminId = $_SESSION['user_id'];

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

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

    $amountKobo = intval($amount * 100);
    $recipients = [];

    // Check admin balance
    $stmt = $conn->prepare("SELECT balance FROM users WHERE id = ?");
    $stmt->bind_param("i", $adminId);
    $stmt->execute();
    $stmt->bind_result($adminBalance);
    $stmt->fetch();
    $stmt->close();

    $totalTransferAmount = $amount * count($userIds);

    if ($adminBalance < $totalTransferAmount) {
        die("Insufficient balance to complete bulk transfer.");
    }

    foreach ($userIds as $userId) {
        $stmt = $conn->prepare("SELECT username, phone 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'];

            // Create Paystack recipient
            $recipientPayload = [
                "type" => "mobile_money",
                "name" => $username,
                "account_number" => $phone,
                "bank_code" => "MTN", // Change dynamically based on network if needed
                "currency" => "GHS"
            ];

            $ch = curl_init("https://api.paystack.co/transferrecipient");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($recipientPayload));
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                "Authorization: Bearer $paystackSecretKey",
                "Content-Type: application/json"
            ]);
            $recipientResponse = curl_exec($ch);
            $recipientError = curl_error($ch);
            curl_close($ch);

            if ($recipientError) {
                die("Curl error (recipient): " . htmlspecialchars($recipientError));
            }

            $recipientResult = json_decode($recipientResponse, true);
            if (!$recipientResult['status']) {
                die("Paystack error (Recipient): " . htmlspecialchars($recipientResult['message']));
            }

            $recipientCode = $recipientResult['data']['recipient_code'];

            // Add to list for bulk transfer
            $recipients[] = [
                'recipient' => $recipientCode,
                'amount' => $amountKobo,
                'reason' => "Bulk payout to $username",
                'phone' => $phone,
                'name' => $username
            ];
        } else {
            die("User not found with ID: $userId");
        }

        $stmt->close();
    }

    // Create bulk transfer payload
    $bulkPayload = [
        "currency" => "GHS",
        "source" => "balance",
        "transfers" => array_map(function ($r) {
            return [
                "amount" => $r['amount'],
                "recipient" => $r['recipient'],
                "reason" => $r['reason']
            ];
        }, $recipients)
    ];

    // Send bulk transfer request to Paystack
    $ch = curl_init("https://api.paystack.co/transfer/bulk");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($bulkPayload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer $paystackSecretKey",
        "Content-Type: application/json"
    ]);
    $bulkResponse = curl_exec($ch);
    $bulkError = curl_error($ch);
    curl_close($ch);

    if ($bulkError) {
        die("Curl error (bulk): " . htmlspecialchars($bulkError));
    }

    $bulkResult = json_decode($bulkResponse, true);
    if (!$bulkResult['status']) {
        die("Paystack error (Bulk Transfer): " . htmlspecialchars($bulkResult['message']));
    }

    // Save each transfer and deduct admin balance
    $conn->begin_transaction();

    try {
        foreach ($recipients as $r) {
            $stmt = $conn->prepare("INSERT INTO tbl_payouts 
                (admin_id, recipient_name, phone, amount, status, paystack_transfer_code, created_at, approved_at) 
                VALUES (?, ?, ?, ?, 'Approved', '', NOW(), NOW())");
            $stmt->bind_param("issd", $adminId, $r['name'], $r['phone'], $amount);
            $stmt->execute();
            $stmt->close();
        }

        // Deduct from Super-Admin balance
        $stmt = $conn->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
        $stmt->bind_param("di", $totalTransferAmount, $adminId);
        $stmt->execute();
        $stmt->close();

        $conn->commit();

        echo "<script>
            alert('Bulk transfer successful!');
            setTimeout(function() {
                window.location.href = 'super-admin.php';
            }, 3000);
        </script>";
    } catch (Exception $e) {
        $conn->rollback();
        die("Transaction failed: " . $e->getMessage());
    }
} else {
    echo "Invalid request.";
}
?>
