<?php
/**
 * cron.php - Background Payment Verifier
 * Run via cPanel/Hostinger Cron every 1 minute:
 * curl -s https://famgateway.in/api/cron.php?secret=CHANGE_THIS_SECRET > /dev/null
 */
require_once __DIR__ . '/../includes/functions.php';

// Security: only allow requests with the correct secret
if (($_GET['secret'] ?? '') !== CRON_SECRET) {
    http_response_code(403);
    echo 'Forbidden';
    exit;
}

// Allow script to run in background even if curl times out from checkout-status.php
ignore_user_abort(true);
set_time_limit(0);

$checked = 0;
$verified = 0;

// 1. Order verification is now handled instantly by the Node.js IMAP Daemon
//    via the internal-process-payment.php endpoint.

// -----------------------------------------------
// 2. Process pending Webhooks
// -----------------------------------------------
$webhookChecked = 0;
$webhookSent = 0;

try {
    $stmt = getDB()->query("SELECT * FROM webhook_jobs WHERE status = 'pending' ORDER BY created_at ASC LIMIT 50");
    $jobs = $stmt->fetchAll();

    foreach ($jobs as $job) {
        $webhookChecked++;
        $ch = curl_init($job['webhook_url']);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => $job['payload'],
            CURLOPT_TIMEOUT        => 10,
            CURLOPT_USERAGENT      => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36 FamGateway-Webhook/1.0',
            CURLOPT_HTTPHEADER     => [
                'Content-Type: application/json',
                'X-FamGateway-Signature: ' . $job['signature'],
                'X-FamGateway-Event: payment.success'
            ],
            CURLOPT_SSL_VERIFYPEER => true,
        ]);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);

        $finalStatus = 'completed';
        if ($error) {
            saveWebhookLog($job['user_id'], $job['webhook_url'], $job['payload'], 0, "cURL Error: " . $error);
            $finalStatus = 'failed';
        } else {
            saveWebhookLog($job['user_id'], $job['webhook_url'], $job['payload'], $httpCode, $response);
            if ($httpCode < 200 || $httpCode >= 300) {
                $finalStatus = 'failed';
            }
        }

        $upd = getDB()->prepare("UPDATE webhook_jobs SET status = ?, processed_at = ? WHERE id = ?");
        $upd->execute([$finalStatus, nowIST()->format('Y-m-d H:i:s'), $job['id']]);
        $webhookSent++;
    }
} catch (\Exception $e) {
    // Table might not exist yet if initWebhookJobsTable hasn't been called. 
    // It gets called first time fireWebhook is executed.
}

// Log this cron run
getDB()->prepare("INSERT INTO cron_log (ran_at, checked, verified) VALUES (?, ?, ?)")
    ->execute([time(), $checked, $verified]);

echo json_encode([
    'status' => 'ok',
    'checked_orders' => $checked,
    'verified_orders' => $verified,
    'checked_webhooks' => $webhookChecked,
    'sent_webhooks' => $webhookSent,
    'ran_at' => date('d-m-Y H:i:s')
]);
