<?php
/**
 * order_timeout_check.php
 * Recommended frequency: every 5-10 minutes.
 *
 * FamPay orders in particular never get explicitly marked FAILED server-side
 * (payment9/payment_status.php only ever reports SUCCESS or PENDING) - if a
 * customer abandons the payment page, that order just sits as "Pending"
 * forever with no failure notification ever sent. This catches any order
 * (from any gateway) still Pending more than 10 minutes after creation,
 * marks it FAILURE, and notifies the merchant - same as a live timeout
 * would, just as a safety net for ones that were never explicitly closed out.
 */

define('PROJECT_ROOT', realpath(dirname(__FILE__)) . '/../');
include PROJECT_ROOT . 'pages/dbFunctions.php';
include PROJECT_ROOT . 'auth/config.php';
include PROJECT_ROOT . 'includes/cron_lib.php';
include PROJECT_ROOT . 'includes/notify_lib.php';
include PROJECT_ROOT . 'includes/webhook_lib.php';

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

if (!cron_is_enabled($conn, 'order_timeout_check')) {
    echo json_encode(['status' => 'skipped', 'reason' => 'Disabled from Website Manage']);
    exit;
}

$notifiedCount = 0;

$sql = "SELECT * FROM orders
        WHERE status = 'PENDING'
          AND create_date < DATE_SUB(NOW(), INTERVAL 10 MINUTE)
          AND create_date > DATE_SUB(NOW(), INTERVAL 2 DAY)";
$result = mysqli_query($conn, $sql);

if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        $orderId = $row['order_id'];
        $userId = (int)($row['user_id'] ?? 0);
        if (!$userId) continue;

        $orderIdEsc = mysqli_real_escape_string($conn, $orderId);
        mysqli_query($conn, "UPDATE orders SET status = 'FAILURE' WHERE order_id = '$orderIdEsc'");

        send_payment_failed_notification($conn, $userId, $orderId, $row['amount'] ?? 0, $row['gateway'] ?? 'UPI', 'Payment not completed (timed out)');

        $userRow = mysqli_fetch_assoc(mysqli_query($conn, "SELECT callback_url FROM users WHERE id = $userId"));
        send_webhook($conn, $userId, $userRow['callback_url'] ?? '', 'payment.failed', [
            'order_id' => $orderId,
            'status'   => 'Failed',
            'amount'   => $row['amount'] ?? 0,
            'reason'   => 'Payment not completed (timed out)',
        ], $orderId);

        $notifiedCount++;
    }
}

cron_mark_ran($conn, 'order_timeout_check', "{$notifiedCount} stale order(s) marked failed and notified");

echo json_encode(['status' => 'ok', 'notified_count' => $notifiedCount, 'ran_at' => date('Y-m-d H:i:s')]);
