<?php
require_once __DIR__.'/_bootstrap.php';require_once dirname(__DIR__,2).'/agent_portal_lib.php';require_once dirname(__DIR__,2).'/subscriber_reality_lib.php';$auth=mobile_api_authenticate($conn);$data=$auth['payload'];$query=trim((string)($data['query']??''));$subscriberId=(int)($data['subscriber_id']??0);$rows=[];
if($subscriberId>0){$r=@$conn->query("SELECT id,full_name,first_name,father_name,last_name,phone,status,package_name,speed_name,ppp_username,is_online,current_ip,last_seen_at FROM subscribers WHERE id={$subscriberId} AND COALESCE(is_deleted,0)=0 LIMIT 1");if(!$r||!$r->num_rows)mobile_api_reply(404,['ok'=>false,'error'=>'SUBSCRIBER_NOT_FOUND','message'=>'المشترك غير موجود.']);$rows[]=$r->fetch_assoc();}elseif($query!==''){$rows=agent_portal_search_subscribers($conn,$query,40);}else{$r=@$conn->query("SELECT id,full_name,first_name,father_name,last_name,phone,status,package_name,speed_name,ppp_username,is_online,current_ip,last_seen_at FROM subscribers WHERE COALESCE(is_deleted,0)=0 ORDER BY id DESC LIMIT 30");while($r&&($row=$r->fetch_assoc()))$rows[]=$row;}
$result=[];$reality=ua_subscriber_reality_snapshot($conn,3600);foreach($rows as $row){$sid=(int)$row['id'];$invoices=[];if($subscriberId>0){$ir=@$conn->query("SELECT id,amount,status,cycle_month,invoice_type,payment_status,paid_at,due_date FROM invoices WHERE subscriber_id={$sid} ORDER BY id DESC LIMIT 20");while($ir&&($inv=$ir->fetch_assoc()))$invoices[]=['id'=>(int)$inv['id'],'amount'=>mobile_api_money($inv['amount']),'status'=>(string)$inv['status'],'cycle_month'=>(string)$inv['cycle_month'],'invoice_type'=>(string)$inv['invoice_type'],'payment_status'=>(string)$inv['payment_status'],'paid'=>mobile_api_paid($inv),'paid_at'=>(string)$inv['paid_at'],'due_date'=>(string)$inv['due_date']];}$runtime=ua_subscriber_reality_state($row,$reality);$result[]=['id'=>$sid,'name'=>agent_portal_customer_name($row),'phone'=>(string)($row['phone']??''),'status'=>(string)($row['status']??''),'package_name'=>(string)($row['package_name']??''),'speed_name'=>(string)($row['speed_name']??''),'ppp_username'=>(string)($row['ppp_username']??''),'is_online'=>!empty($runtime['is_online']),'is_disabled'=>!empty($runtime['is_disabled']),'current_ip'=>(string)($row['current_ip']??''),'last_seen_at'=>(string)($row['last_seen_at']??''),'invoices'=>$invoices];}
mobile_api_reply(200,['ok'=>true,'subscribers'=>$result]);

