<?php

require_once __DIR__ . '/../config.php';

/**
 * HUBTEL PAYOUT
 */
function hubtel_payout($channel, $data)
{
    $payload = [
        "RecipientName" => $data['recipient'],
        "RecipientMsisdn" => $data['phone'],
        "Channel" => $channel,
        "Amount" => $data['amount'],
        "ClientReference" => $data['reference'],
        "PrimaryCallbackUrl" => MADR_CALLBACK_URL
    ];

    return madr_basic_auth_call(
        HUBTEL_URL,
        HUBTEL_USERNAME,
        HUBTEL_PASSWORD,
        $payload
    );
}


/**
 * BASIC AUTH CURL CALL
 */
function madr_basic_auth_call($url, $username, $password, $payload)
{
    $ch = curl_init($url);

    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($payload),
        CURLOPT_HTTPHEADER => [
            "Content-Type: application/json"
        ],
        CURLOPT_USERPWD => $username . ":" . $password,
        CURLOPT_TIMEOUT => 30
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if (curl_errno($ch)) {
        return [
            'status' => 'FAILED',
            'message' => curl_error($ch)
        ];
    }

    curl_close($ch);

    $decoded = json_decode($response, true);

    // Normalize response
    if ($httpCode == 200 && isset($decoded['ResponseCode']) && $decoded['ResponseCode'] == "0000") {
        return [
            'status' => 'SUCCESS',
            'provider_ref' => $decoded['Data']['TransactionId'] ?? null,
            'raw' => $decoded
        ];
    }

    return [
        'status' => 'FAILED',
        'message' => $decoded['Message'] ?? 'Hubtel error',
        'raw' => $decoded
    ];
}
