<?php
// Define the base directory constant
define('ROOT_DIR', realpath(dirname(__FILE__)) . '/../');

include ROOT_DIR . 'pages/dbFunctions.php';
include ROOT_DIR . 'pages/dbInfo.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_POST['byte_order_status'])) {
    http_response_code(400);
    echo 'bad request';
    exit;
}

$byteTransactionId = $_POST['byte_order_status'];

$sql = "SELECT order_id, status FROM orders WHERE byteTransactionId=?";
// getXbyY() doesn't support bound params in this codebase's helper, so escape manually
$safe_id = addslashes($byteTransactionId);
$rows = getXbyY("SELECT order_id, status FROM orders WHERE byteTransactionId='$safe_id'");

if (count($rows) === 0) {
    http_response_code(404);
    echo 'not found';
    exit;
}

$order_id = $rows[0]['order_id'];
$current_status = $rows[0]['status'];

// Never overwrite a real success, and don't bother re-writing an already-failed order
if ($current_status !== 'SUCCESS' && $current_status !== 'FAILURE') {
    $safe_order_id = addslashes($order_id);
    setXbyY("UPDATE orders SET status='FAILURE' WHERE order_id='$safe_order_id'");
    $current_status = 'FAILURE';
}

header('Content-Type: application/json');
$orderRow = getXbyY("SELECT utr FROM orders WHERE order_id='" . addslashes($order_id) . "'");
echo json_encode([
    "status" => $current_status,
    "utr" => $orderRow[0]['utr'] ?? '',
]);
