<?php
// Include database config file
include("config.php");

// Open php://input as a file resource and read the raw JSON
$handle = fopen("php://input", "r");
$rawData = "";

if ($handle) {
    while (!feof($handle)) {
        $rawData .= fread($handle, 8192);
    }
    fclose($handle);
}

// Log raw data for debugging (optional)
file_put_contents("hubtel_callback.log", $rawData . "\n", FILE_APPEND);

// Decode JSON data
$data = json_decode($rawData, true);

// Check if the JSON decoding was successful
if ($data === null) {
    die("Invalid JSON received");
}

// Extract relevant Hubtel response values
$responseCode = $data['ResponseCode'] ?? null;
$amountDebited = $data['Data']['AmountDebited'] ?? null;
$transactionId = $data['Data']['TransactionId'] ?? null;
$clientReference = $data['Data']['ClientReference'] ?? null;
$paymentStatus = ($responseCode == "0000") ? "Success" : "Failed";

// Log extracted values for debugging
$logMessage = "Transaction ID: $transactionId | Status: $paymentStatus | Amount: $amountDebited\n";
file_put_contents("hubtel_callback.log", $logMessage, FILE_APPEND);

// Update transaction status in database
include("config.php");

$updateQuery = "UPDATE api_logs SET response=?, date_created=NOW() WHERE token=?";
$stmt = $conn->prepare($updateQuery);
$stmt->bind_param("ss", $data, $clientReference);
$stmt->execute();
$stmt->close();
$conn->close();

echo "Callback processed successfully!";
?>
