<?php
include(__DIR__."/includes/db_connect.php");

$payload = file_get_contents("php://input");
$data = json_decode($payload,true);

// Always log callbacks
file_put_contents(
    "mobex_callbacks.log",
    date('Y-m-d H:i:s')." ".$payload.PHP_EOL,
    FILE_APPEND
);

$ref    = $data['reference'] ?? '';
$status = $data['status'] ?? '';
$reason = $data['reason'] ?? '';

if (!$ref) exit;

if ($status === "SUCCESS") {

    $conn->query("
        UPDATE transactions
        SET status='SUCCESS', completed_at=NOW()
        WHERE reference='$ref'
    ");

} 

if ($status === "FAILED") {

    if ($reason === "LIMIT_EXCEEDED" || $reason === "INVALID_NUMBER") {

        // FINAL FAIL
        $conn->query("
            UPDATE transactions
            SET status='FAILED', failure_reason='$reason'
            WHERE reference='$ref'
        ");

    } else {

        // RETRY
        $conn->query("
            UPDATE transactions
            SET status='QUEUED'
            WHERE reference='$ref'
        ");
    }
}


http_response_code(200);
echo "OK";
