<?php
require_once __DIR__.'/_bootstrap.php';require_once dirname(__DIR__,2).'/stats_snapshot_lib.php';$auth=mobile_api_authenticate($conn);$agent=$auth['agent'];$agentId=(int)($agent['id']??0);
$counts=['subscribers'=>0,'online'=>0,'unpaid_invoices'=>0,'unpaid_total'=>0.0,'payments_today'=>0.0];$stats=ua_app_stats_snapshot($conn,10,false);$counts['subscribers']=(int)($stats['total']??0);$counts['online']=(int)($stats['online']??0);
$r=@$conn->query("SELECT COUNT(*) total,COALESCE(SUM(amount),0) amount FROM invoices WHERE NOT (LOWER(COALESCE(payment_status,'')) IN ('paid','settled') OR LOWER(COALESCE(status,'')) IN ('paid','مدفوع'))");if($r&&($row=$r->fetch_assoc())){$counts['unpaid_invoices']=(int)$row['total'];$counts['unpaid_total']=mobile_api_money($row['amount']);}
$filter=$agentId>0?' AND agent_id='.$agentId:'';$r=@$conn->query("SELECT COALESCE(SUM(amount),0) amount FROM payments WHERE payment_status='POSTED' AND DATE(COALESCE(paid_at,created_at))=CURDATE(){$filter}");if($r&&($row=$r->fetch_assoc()))$counts['payments_today']=mobile_api_money($row['amount']);
$recent=[];$r=@$conn->query("SELECT p.id,p.invoice_id,p.subscriber_id,p.amount,p.method,p.reference,p.paid_at,p.created_at,s.full_name FROM payments p LEFT JOIN subscribers s ON s.id=p.subscriber_id WHERE p.payment_status='POSTED'{$filter} ORDER BY p.id DESC LIMIT 8");while($r&&($row=$r->fetch_assoc()))$recent[]=['id'=>(int)$row['id'],'invoice_id'=>(int)$row['invoice_id'],'subscriber_id'=>(int)$row['subscriber_id'],'subscriber_name'=>(string)($row['full_name']?:('#'.(int)$row['subscriber_id'])),'amount'=>mobile_api_money($row['amount']),'method'=>(string)$row['method'],'reference'=>(string)$row['reference'],'paid_at'=>(string)($row['paid_at']?:$row['created_at'])];
$profile=$agentId>0?['id'=>$agentId,'name'=>(string)($agent['full_name']??$agent['name']??''),'username'=>(string)($agent['username']??''),'phone'=>(string)($agent['phone']??''),'balance'=>mobile_api_money($agent['balance_cached']??$agent['balance']??0),'credit_limit'=>isset($agent['credit_limit'])?mobile_api_money($agent['credit_limit']):null,'commission_type'=>(string)($agent['commission_type']??''),'commission_value'=>mobile_api_money($agent['commission_value']??0)]:['name'=>(string)($auth['link']['instance_name']??'نسخة فرعية'),'instance_id'=>$auth['instance_id']];
mobile_api_reply(200,['ok'=>true,'role'=>$auth['install_type'],'profile'=>$profile,'stats'=>$counts,'recent_payments'=>$recent,'server_time'=>time()]);

