<?php
require_once dirname(__DIR__) . '/db_bootstrap.php';
require_once dirname(__DIR__) . '/device_subscriber_confirmation_lib.php';
$conn=ensure_db(true);
function dsc_assert(bool $condition,string $message): void {if(!$condition)throw new RuntimeException($message);}

$deviceId=0;$subscriberUser='';
$rs=$conn->query("SELECT airmax_device_id,COALESCE(NULLIF(ppp_username,''),username) ppp_user,COUNT(*) c
  FROM subscribers WHERE COALESCE(airmax_device_id,0)>0 AND COALESCE(is_deleted,0)=0
  GROUP BY airmax_device_id,ppp_user ORDER BY c DESC LIMIT 1");
if($rs&&($row=$rs->fetch_assoc())){$deviceId=(int)$row['airmax_device_id'];$subscriberUser=ua_norm_ppp_user((string)$row['ppp_user']);}
dsc_assert($deviceId>0&&$subscriberUser!=='','لا يوجد مستقبل مربوط بمشترك صالح للاختبار.');

$base=['secrets'=>[],'active_rows'=>[],'has_observation'=>true,'router_online'=>true,'connection_state'=>'online','source'=>'test','data_age'=>5,'live_data_reliable'=>true,'raw'=>[]];
$onlineReality=array_merge($base,['active'=>[$subscriberUser=>true]]);
$online=ua_device_subscriber_confirmation($conn,'receivers',$deviceId,$onlineReality);
dsc_assert($online['linked_total']>0,'لم يجد التحقق مشتركي الجهاز.');
dsc_assert($online['online']>0&&$online['allow_alert']===false&&$online['reason']==='linked_subscriber_online','لم يمنع المشترك المتصل التنبيه الخاطئ.');

$allOffline=ua_device_subscriber_confirmation($conn,'receivers',$deviceId,array_merge($base,['active'=>[]]));
dsc_assert($allOffline['online']===0&&$allOffline['allow_alert']===true&&$allOffline['reason']==='all_linked_subscribers_offline','لم يؤكد انقطاع جميع مشتركي الجهاز.');

$stale=array_merge($base,['active'=>[],'data_age'=>900,'live_data_reliable'=>false,'router_online'=>false,'connection_state'=>'offline']);
$inconclusive=ua_device_subscriber_confirmation($conn,'receivers',$deviceId,$stale);
dsc_assert($inconclusive['allow_alert']===false&&$inconclusive['reason']==='subscriber_snapshot_not_reliable','أصدر التحقق حكماً من لقطة غير موثوقة.');

echo "PASS: online subscriber suppresses, all-offline confirms, stale snapshot defers\n";
