<?php
// Simulates a payment outcome for TEST MODE orders only. Refuses to touch
// any order that isn't explicitly flagged is_test=1, so this can never be
// used to fabricate a real/live transaction.

define('ROOT_DIR', realpath(dirname(__FILE__)) . '/../');
include ROOT_DIR . 'pages/dbFunctions.php';
include ROOT_DIR . 'pages/dbInfo.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_POST['order_id']) || empty($_POST['action'])) {
    echo json_encode(["status" => false, "message" => "Bad request"]);
    exit;
}

$order_id = $_POST['order_id'];
$action = $_POST['action'];

if (!in_array($action, ['success', 'failed', 'timeout'], true)) {
    echo json_encode(["status" => false, "message" => "Invalid action"]);
    exit;
}

$safeOrderId = addslashes($order_id);
$rows = getXbyY("SELECT * FROM orders WHERE order_id='$safeOrderId'");

if (count($rows) === 0) {
    echo json_encode(["status" => false, "message" => "Order not found"]);
    exit;
}

$order = $rows[0];

// Hard safety gate: only ever act on orders explicitly created in test mode.
if (empty($order['is_test'])) {
    echo json_encode(["status" => false, "message" => "This order is not a test-mode order."]);
    exit;
}

// Don't let a finished test order be re-simulated into a different outcome silently
if (in_array($order['status'], ['SUCCESS', 'FAILURE'], true)) {
    // still allow re-notifying the webhook for convenience, but don't error out
}

$newDbStatus = ($action === 'success') ? 'SUCCESS' : 'FAILURE';
setXbyY("UPDATE orders SET status='$newDbStatus' WHERE order_id='$safeOrderId'");

// Fire the merchant's webhook exactly like a real transaction would, so their
// integration can be tested end-to-end - but include a test_mode flag so
// their backend can tell it apart from a real payment if they choose to.
$webhookSent = false;
$callbackUrl = $order['redirect_url'] ?? '';

// Prefer the account's configured webhook (callback_url on users) if present,
// since redirect_url is the browser redirect, not necessarily the server webhook.
$userRows = getXbyY("SELECT callback_url FROM users WHERE user_token='" . addslashes($order['user_token']) . "'");
if (!empty($userRows[0]['callback_url'])) {
    $callbackUrl = $userRows[0]['callback_url'];
}

if (!empty($callbackUrl)) {
    $webhookStatus = ($action === 'success') ? 'SUCCESS' : (($action === 'timeout') ? 'TIMEOUT' : 'FAILURE');
    $postData = [
        'order_id' => $order_id,
        'status' => $webhookStatus,
        'remark1' => $order['remark1'] ?? '',
        'test_mode' => 'true',
    ];
    $ch = curl_init($callbackUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    curl_setopt($ch, CURLOPT_TIMEOUT, 8);
    curl_exec($ch);
    curl_close($ch);
    $webhookSent = true;
}

$responses = [
    'success' => ['title' => 'Payment Simulated: SUCCESS', 'message' => 'This test order has been marked as a successful payment.', 'color' => '#1FAA59'],
    'failed'  => ['title' => 'Payment Simulated: FAILED', 'message' => 'This test order has been marked as a failed payment.', 'color' => '#D35400'],
    'timeout' => ['title' => 'Payment Simulated: TIMEOUT', 'message' => 'This test order has been marked as timed out / failed.', 'color' => '#B7791F'],
];

echo json_encode([
    "status" => true,
    "order_id" => $order_id,
    "title" => $responses[$action]['title'],
    "message" => $responses[$action]['message'],
    "color" => $responses[$action]['color'],
    "webhook_sent" => $webhookSent,
]);
