<?php
// PUBLIC API: GET /api/verify_order.php?api_key=...&order_id=...
require_once __DIR__ . '/../includes/functions.php';

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

if (!$apiKey) {
    jsonResponse(['status' => 'unauthorized', 'message' => 'Missing api_key'], 401);
}

$user = getUserByApiKey($apiKey);
if (!$user) {
    jsonResponse(['status' => 'unauthorized', 'message' => 'Invalid api_key'], 401);
}

if ($user['status'] === 'banned') {
    jsonResponse(['status' => 'suspended', 'message' => 'Account suspended by admin'], 403);
}


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

$order = null;
$isPaymentLink = false;
$slug = '';

if (strpos($orderId, 'LINK_') === 0) {
    $isPaymentLink = true;
    $slug = substr($orderId, 5);
    $link = getPaymentLinkBySlug($slug);
    
    if (!$link || $link['user_id'] !== $user['id']) {
        jsonResponse(['status' => 'not_found', 'message' => 'Payment link not found'], 404);
    }
    
    if ($link['status'] === 'expired') {
        jsonResponse(['status' => 'expired', 'message' => 'This payment link has been expired by merchant'], 408);
    }
    
    $dummyOrder = null;
    if ($link['status'] === 'paid') {
        $stmt = getDB()->prepare("SELECT transaction_id, utr, sender_name, payment_time_ist FROM orders WHERE type = ? AND user_id = ? ORDER BY created_at_timestamp DESC LIMIT 1");
        $stmt->execute(['link_' . $slug, $user['id']]);
        $dummyOrder = $stmt->fetch();
    }
    
    $order = [
        'order_id' => $orderId,
        'status' => $link['status'] === 'paid' ? 'success' : 'pending',
        'amount' => $link['amount'],
        'payable_amount' => !empty((float)($link['payable_amount'] ?? 0)) ? $link['payable_amount'] : $link['amount'],
        'created_at_timestamp' => $link['created_at'],
        'expires_at_timestamp' => $link['expires_at'],
        'transaction_id' => $dummyOrder ? $dummyOrder['transaction_id'] : '',
        'utr' => $dummyOrder ? $dummyOrder['utr'] : '',
        'sender_name' => $dummyOrder ? $dummyOrder['sender_name'] : '',
        'payment_time_ist' => $dummyOrder ? $dummyOrder['payment_time_ist'] : ''
    ];
} else {
    $order = getOrderById($orderId);
    if (!$order || $order['user_id'] !== $user['id']) {
        jsonResponse(['status' => 'not_found', 'message' => 'Order ID not found'], 404);
    }
}

// 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 {
    $imapUrl = getBaseUrl() . '/api/imap-processor.php?secret=' . urlencode(CRON_SECRET) . '&user_id=' . urlencode($user['id']);
    $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 already confirmed previously, just return cached result
if ($order['status'] === 'success') {
    jsonResponse([
        'status' => 'success',
        'data' => [
            'order_id' => $order['order_id'],
            'transaction_id' => $order['transaction_id'] ?? '',
            'amount' => $order['amount'],
            'utr' => $order['utr'] ?? '',
            'sender_name' => $order['sender_name'] ?? '',
            'payment_time_ist' => $order['payment_time_ist'] ?? ''
        ]
    ]);
}

// Check order expiry
if (isset($order['expires_at_timestamp']) && time() > $order['expires_at_timestamp']) {
    if ($isPaymentLink) {
        updatePaymentLink($slug, 'expired');
    } else {
        updateOrder($orderId, ['status' => 'expired']);
    }
    jsonResponse(['status' => 'expired', 'message' => 'Order expired'], 408);
}

jsonResponse(['status' => 'pending', 'message' => 'Payment not received yet']);
