<?php
/**
 * CodexVertex Callback Handler Example
 * Give this file to your merchants to help them integrate the payment success notification.
 */

// 1. Get the raw POST data from the request
$data = file_get_contents('php://input');

// 2. Log the callback (Good for debugging)
file_put_contents('callback.log', "[" . date('Y-m-d H:i:s') . "] CALLBACK RECEIVED: " . $data . "\n", FILE_APPEND);

// 3. Decode the JSON data
$json = json_decode($data);

if (!$json) {
    http_response_code(400);
    echo "Invalid JSON";
    exit;
}

/**
 * Expected JSON Structure:
 * {
 *   "code": "SUCCESS",
 *   "data": {
 *      "status": "COMPLETED",
 *      "order_id": "ORD_123456789",
 *      "amount": "1.00",
 *      "utr": "606807709098",
 *      "id": "transaction_uuid"
 *   }
 * }
 */

// 4. Verify the status
if ($json->code === 'SUCCESS' && isset($json->data->status) && $json->data->status === 'COMPLETED') {
    
    $order_id = $json->data->order_id;
    $amount = $json->data->amount;
    $utr = $json->data->utr;

    // TODO: VALIDATE TRANSACTION IN YOUR DATABASE
    // You should check if $order_id exists in your system and is still pending
    
    // Example: Update your local database
    // $db->query("UPDATE your_orders SET status='paid', utr='$utr' WHERE order_id='$order_id'");

    // 5. Respond with 200 OK to acknowledge receipt
    echo json_encode(["status" => "received"]);
} else {
    // Payment failed or data mismatched
    echo json_encode(["status" => "ignored"]);
}
?>
