<?php
require_once __DIR__.'/conn.php';
require_once __DIR__.'/functions.php';

date_default_timezone_set('Asia/Kolkata');

referDebug("CRON START");

$sql = "
    SELECT h.order_id, h.user_id
    FROM otp_history h
    LEFT JOIN reseller_earnings e 
        ON e.order_id = h.order_id
    WHERE h.status = 'RECEIVED'
      AND e.order_id IS NULL
      AND h.created_at >= NOW() - INTERVAL 2 MINUTE
    ORDER BY h.created_at DESC
    LIMIT 200
";

$stmt = $pdo->prepare($sql);
$stmt->execute();
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

referDebug("CRON FOUND ".count($orders)." orders");

foreach ($orders as $order) {
    try {
        processReferralCommission($pdo, $order);
    } catch (Throwable $e) {
        referDebug("ERROR order={$order['order_id']} msg=".$e->getMessage());
    }
}

referDebug("CRON END");
