<?php

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


/**
 * SASAPAY PAYOUT
 */
function sasapay_payout($country, $channel, $data)
{
    $token = sasapay_get_token();

    if (!$token) {
        return [
            'status' => 'FAILED',
            'message' => 'Unable to get SasaPay token'
        ];
    }

    $payload = [
        "MerchantCode" => SASAPAY_MERCHANT,
        "MerchantTransactionReference" => $data['reference'],
        "DestinationChannelName" => $channel,
        "Currency" => $country == "KE" ? "KES" : "TZS",
        "Amount" => $data['amount'],
        "ReceiverPhoneNumber" => $data['phone'],
        "ReceiverAccountNumber" => $data['phone'],
        "ReceiverAccountName" => $data['recipient'],
        "SenderName" => $data['sender_name'],
        "CallbackURL" => MADR_CALLBACK_URL
    ];

    return madr_bearer_call(SASAPAY_URL, $token, $payload);
}


/**
 * GET & CACHE TOKEN
 */
function sasapay_get_token()
{
    global $conn;

    // Check cached token
    $result = $conn->query("SELECT * FROM madr_tokens WHERE provider='SASAPAY' LIMIT 1");
    $tokenData = $result->fetch_assoc();

    if ($tokenData && strtotime($tokenData['expires_at']) > time()) {
        return $tokenData['access_token'];
    }

    // Request new token
    $ch = curl_init(SASAPAY_TOKEN_URL);

    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query([
            'grant_type' => 'client_credentials',
            'client_id' => SASAPAY_CLIENT_ID,
            'client_secret' => SASAPAY_CLIENT_SECRET
        ]),
        CURLOPT_HTTPHEADER => [
            "Content-Type: application/x-www-form-urlencoded"
        ]
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    $decoded = json_decode($response, true);

    if (!isset($decoded['access_token'])) {
        return null;
    }

    $accessToken = $decoded['access_token'];
    $expiresIn = $decoded['expires_in'];

    $expiry = date('Y-m-d H:i:s', time() + $expiresIn - 60);

    // Save token
    $stmt = $conn->prepare("
        REPLACE INTO madr_tokens
        (provider, access_token, expires_at)
        VALUES ('SASAPAY', ?, ?)
    ");
    $stmt->bind_param("ss", $accessToken, $expiry);
    $stmt->execute();

    return $accessToken;
}


/**
 * BEARER CALL
 */
function madr_bearer_call($url, $token, $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",
            "Authorization: Bearer $token"
        ],
        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);

    if ($httpCode == 200 && isset($decoded['status']) && $decoded['status'] == "SUCCESS") {
        return [
            'status' => 'SUCCESS',
            'provider_ref' => $decoded['transactionId'] ?? null,
            'raw' => $decoded
        ];
    }

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