<?php
// PUBLIC API: GET /api/checkout-status.php?order_id=...
// Safe endpoint for frontend polling. Returns only basic status.
require_once __DIR__ . '/../includes/functions.php';

header('Content-Type: application/json');
header('Cache-Control: no-store, no-cache, must-revalidate');

$orderId = $_GET['order_id'] ?? '';

if (!$orderId) {
    echo json_encode(['status' => 'error', 'message' => 'Missing order_id']);
    exit;
}

// Trigger PHP IMAP processor for the specific merchant who owns this order.
// Non-blocking: we fire and forget with a 1-second timeout so the status response is instant.
try {
    // Resolve user_id from the order or payment link
    $triggerUserId = null;
    if (strpos($orderId, 'LINK_') === 0) {
        $slugLookup = substr($orderId, 5);
        $stmtU = getDB()->prepare("SELECT user_id FROM payment_links WHERE slug = ? LIMIT 1");
        $stmtU->execute([$slugLookup]);
        $rowU = $stmtU->fetch();
        if ($rowU) $triggerUserId = $rowU['user_id'];
    } else {
        $stmtU = getDB()->prepare("SELECT user_id FROM orders WHERE order_id = ? LIMIT 1");
        $stmtU->execute([$orderId]);
        $rowU = $stmtU->fetch();
        if ($rowU) $triggerUserId = $rowU['user_id'];
    }

    if ($triggerUserId) {
        $imapUrl = getBaseUrl() . '/api/imap-processor.php?secret=' . urlencode(CRON_SECRET) . '&user_id=' . urlencode($triggerUserId);
        $ch = curl_init();
        if ($ch !== false) {
            curl_setopt($ch, CURLOPT_URL, $imapUrl);
            curl_setopt($ch, CURLOPT_TIMEOUT, 2);
            curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_exec($ch);
            curl_close($ch);
        }
    }
} catch (\Throwable $e) {
    // Ignore errors — status response must always return fast
}

if (strpos($orderId, 'LINK_') === 0) {
    // Payment Link flow
    $slug = substr($orderId, 5);
    $stmt = getDB()->prepare("SELECT * FROM payment_links WHERE slug = ?");
    $stmt->execute([$slug]);
    $link = $stmt->fetch();
    
    if (!$link) {
        echo json_encode(['status' => 'error', 'message' => 'Link not found']);
        exit;
    }
    
    if ($link['status'] === 'paid') {
        echo json_encode(['status' => 'success']);
    } elseif ($link['status'] === 'expired' || $link['status'] === 'disabled' || time() > $link['expires_at']) {
        echo json_encode(['status' => 'expired']);
    } else {
        echo json_encode(['status' => 'pending']);
    }
} else {
    // Standard Order flow
    $order = getOrderById($orderId);
    
    if (!$order) {
        echo json_encode(['status' => 'error', 'message' => 'Order not found']);
        exit;
    }
    
    if ($order['status'] === 'success') {
        echo json_encode(['status' => 'success']);
    } elseif ($order['status'] === 'expired' || (isset($order['expires_at_timestamp']) && time() > $order['expires_at_timestamp'])) {
        echo json_encode(['status' => 'expired']);
    } else {
        echo json_encode(['status' => 'pending']);
    }
}
