<?php
require_once __DIR__.'/_bootstrap.php';
use App\Core\Database;use App\Core\WalletService;
$job='royalty_eligibility';$started=date('Y-m-d H:i:s');try{$start=date('Y-m-d',strtotime('monday last week'));$end=date('Y-m-d',strtotime('sunday last week'));$existing=Database::safeFetchOne('SELECT id FROM royalty_cycles WHERE cycle_type="weekly" AND period_start=? AND period_end=? LIMIT 1',[$start,$end]);if($existing){cron_log($job,'success','Weekly royalty cycle already exists for '.$start.' to '.$end.'.',$started);exit;}$pool=(float)(Database::safeFetchOne('SELECT COALESCE(SUM(marketing_psa),0)*0.25 total FROM psa_transactions WHERE DATE(created_at) BETWEEN ? AND ?',[$start,$end])['total']??0);$minimum=(float)setting('weekly_royalty_min_sale','2000');$members=Database::safeFetchAll('SELECT * FROM affiliate_members WHERE status="active" AND rank_code<>"IBO" AND weekly_personal_sales>=?',[$minimum]);Database::transaction(function()use($start,$end,$pool,$members){Database::execute('INSERT INTO royalty_cycles (cycle_type,period_start,period_end,total_amount,status,created_at) VALUES ("weekly",?,?,?,"completed",NOW())',[$start,$end,$pool]);$cycleId=Database::lastInsertId();$share=count($members)>0?round($pool/count($members),2):0;foreach($members as $m){Database::execute('INSERT INTO royalty_distributions (royalty_cycle_id,affiliate_member_id,rank_code,amount,status,created_at) VALUES (?,?,?,?,"paid",NOW())',[$cycleId,$m['id'],$m['rank_code'],$share]);if($share>0)WalletService::credit((int)$m['user_id'],'royalty',$share,'Weekly global royalty',$cycleId);Database::execute('UPDATE affiliate_members SET last_royalty_at=NOW() WHERE id=?',[$m['id']]);}Database::execute('UPDATE affiliate_members SET weekly_personal_sales=0,updated_at=NOW()');});cron_log($job,'success','Created royalty pool '.money($pool).' for '.count($members).' eligible member(s).',$started);}catch(Throwable $e){cron_log($job,'failed',$e->getMessage(),$started);exit(1);}
