<?php
require_once __DIR__ . '/_init.php';
rx_cron_boot('pasarguard_resellers', 180);
$root=dirname(__DIR__);
if (!rx_cron_require_or_skip('pasarguard_resellers', [$root.'/config.php',$root.'/pasarguard.php'])) exit;
if (!rx_cron_db_ready('pasarguard_resellers')) exit;

$now=time();$done=0;$failed=0;
try{
    $q=$pdo->prepare("SELECT * FROM pasarguard_resellers WHERE expires_at>0 AND expires_at<=:now AND status IN ('active','limited') ORDER BY id ASC LIMIT 100");
    $q->execute([':now'=>$now]);
    foreach($q->fetchAll(PDO::FETCH_ASSOC) as $row){
        try{
            $ps=$pdo->prepare("SELECT * FROM marzban_panel WHERE code_panel=:c AND type='pasarguard' LIMIT 1");
            $ps->execute([':c'=>$row['panel_code']]);$panel=$ps->fetch(PDO::FETCH_ASSOC);
            if(!$panel) throw new RuntimeException('PasarGuard backend not found');
            $r=pg_set_admin_status($panel,(int)$row['remote_admin_id'],'disabled');
            if(empty($r['ok'])) throw new RuntimeException($r['error']??'remote disable failed');
            $u=$pdo->prepare("UPDATE pasarguard_resellers SET status='expired',updated_at=:t WHERE id=:id");$u->execute([':t'=>$now,':id'=>$row['id']]);
            if(!empty($row['invoice_id'])){
                try{$pdo->prepare("UPDATE invoice SET Status='end_of_time' WHERE id_invoice=:i")->execute([':i'=>$row['invoice_id']]);}catch(Throwable $e){}
            }
            $done++;
        }catch(Throwable $e){$failed++;error_log('[PasarGuard reseller cron #'.($row['id']??'?').'] '.$e->getMessage());}
    }
}catch(Throwable $e){error_log('[PasarGuard reseller cron] '.$e->getMessage());$failed++;}
echo "OK reseller_expiry done={$done} failed={$failed}\n";
