<?php
// Allowed Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: Authorization, Accept');

// Monnify Config
$apiKey = 'MK_PROD_YU6AWBHUCK';
$clientSecret = 'QNP6Q55DFTVX76BNS7G4A7WQWY52WKPC';
$baseUrl = 'https://api.monnify.com';

// Validate request method
if ($_SERVER["REQUEST_METHOD"] !== 'GET') {
    http_response_code(400);
    echo json_encode(["status" => "fail", "msg" => "Only GET method is allowed"]);
    exit;
}

// Get transactionReference from query string
if (!isset($_GET['transactionReference'])) {
    http_response_code(400);
    echo json_encode(["error" => "Missing required parameter: transactionReference"]);
    exit;
}

$transactionReference = urlencode($_GET['transactionReference']);

// === STEP 1: AUTHENTICATE WITH MONNIFY ===
$authHeaders = [
    "Content-Type: application/json",
    "Authorization: Basic " . base64_encode("$apiKey:$clientSecret")
];

$authCh = curl_init("$baseUrl/api/v1/auth/login");
curl_setopt($authCh, CURLOPT_RETURNTRANSFER, true);
curl_setopt($authCh, CURLOPT_HTTPHEADER, $authHeaders);
curl_setopt($authCh, CURLOPT_POST, true);
curl_setopt($authCh, CURLOPT_POSTFIELDS, '{}');

$authResponse = json_decode(curl_exec($authCh), true);
curl_close($authCh);

if (!$authResponse['requestSuccessful']) {
    http_response_code(500);
    echo json_encode(["error" => "Auth failed", "message" => $authResponse['responseMessage']]);
    exit;
}

$accessToken = $authResponse['responseBody']['accessToken'];

// === STEP 2: CALL TRANSACTION STATUS ENDPOINT ===
$statusUrl = "$baseUrl/api/v2/transactions/$transactionReference";

$statusHeaders = [
    "Accept: application/json",
    "Authorization: Bearer $accessToken"
];

$statusCh = curl_init($statusUrl);
curl_setopt($statusCh, CURLOPT_RETURNTRANSFER, true);
curl_setopt($statusCh, CURLOPT_HTTPHEADER, $statusHeaders);

$statusResponse = json_decode(curl_exec($statusCh), true);
curl_close($statusCh);

if (!$statusResponse['requestSuccessful']) {
    http_response_code(500);
    echo json_encode(["error" => "Failed to fetch transaction status", "message" => $statusResponse['responseMessage']]);
    exit;
}

// Return status response
echo json_encode([
    "success" => true,
    "transactionStatus" => $statusResponse['responseBody']['paymentStatus'],
    "details" => $statusResponse['responseBody']
]);

?>