<?php
require_once __DIR__.'/_bootstrap.php';
use App\Core\Database;
$job='auto_suspend_reactivate';$started=date('Y-m-d H:i:s');try{$rule=Database::safeFetchOne('SELECT * FROM affiliate_suspension_rules WHERE status="active" ORDER BY id DESC LIMIT 1');if(!$rule){cron_log($job,'success','No active suspension rule; no accounts changed.',$started);exit;}$start=date('Y-m-01',strtotime('first day of last month'));$end=date('Y-m-t',strtotime('last day of last month'));$members=Database::fetchAll('SELECT * FROM affiliate_members WHERE rank_code<>"IBO"');$suspended=0;$reactivated=0;foreach($members as $m){$paid=db_count('royalty_distributions','affiliate_member_id=? AND status="paid" AND DATE(created_at) BETWEEN ? AND ?',[$m['id'],$start,$end])>0;if(!$paid&&!empty($rule['monthly_royalty_required'])&&$m['status']==='active'){Database::execute('UPDATE affiliate_members SET status="suspended",updated_at=NOW() WHERE id=?',[$m['id']]);$suspended++;}elseif($paid&&!empty($rule['auto_reactivate_on_royalty'])&&$m['status']==='suspended'){Database::execute('UPDATE affiliate_members SET status="active",updated_at=NOW() WHERE id=?',[$m['id']]);$reactivated++;}}cron_log($job,'success','Suspended '.$suspended.' and reactivated '.$reactivated.' member(s).',$started);}catch(Throwable $e){cron_log($job,'failed',$e->getMessage(),$started);exit(1);}
