<?php
declare(strict_types=1);
require dirname(__DIR__).'/app/bootstrap.php';
use App\Repositories\DiarCasesRepository;
use App\Repositories\DiarExecutiveOverviewRepository;
use App\Services\DiarWorkspaceNavigation;
$result=['result'=>'FAIL','release'=>'DIAR-6B.2-R3.1.1','sites'=>['MNH','NJCH'],'month'=>'2026-06','snapshot_count'=>0,'cases'=>0,'critical'=>0,'high'=>0,'medium'=>0,'associated_inventory_cost'=>0.0,'trend_days'=>0,'first_page_rows'=>0,'module_count'=>count(DiarWorkspaceNavigation::definitions()),'checks'=>[]];
try{
 $sites=['MNH','NJCH'];
 $overview=(new DiarExecutiveOverviewRepository())->overview($sites,['site'=>'ALL','period'=>'latest_closed','month'=>'2026-06']);
 $summary=(array)($overview['summary']??[]);$refs=(array)($overview['snapshot_refs']??[]);
 $filters=['site'=>'ALL','month'=>'2026-06','q'=>'','severity'=>'','branch'=>'','store'=>'','item'=>'','unit'=>'','trans_code'=>'','trans_effect'=>'','date_from'=>'','date_to'=>'','min_score'=>'','sort'=>'priority'];
 $cases=(new DiarCasesRepository())->search($sites,$filters,1,25);
 $result['snapshot_count']=count($refs);$result['cases']=(int)($summary['detected_count']??0);$result['critical']=(int)($summary['critical_count']??0);$result['high']=(int)($summary['high_count']??0);$result['medium']=(int)($summary['medium_count']??0);$result['associated_inventory_cost']=round((float)($summary['inventory_cost_abs']??0),2);$result['trend_days']=count((array)($overview['trend']??[]));$result['first_page_rows']=count((array)($cases['rows']??[]));
 $available=(array)($overview['available_sites']??[]);$sources=[];foreach($refs as $ref){if(is_array($ref))$sources[(string)($ref['hospital_code']??'')]=(string)($ref['source_db']??'');}
 $result['checks']=[
  'six_modules'=>$result['module_count']===6,'both_sites_available'=>in_array('MNH',$available,true)&&in_array('NJCH',$available,true),
  'source_identity'=>($sources['MNH']??'')==='ORAMNH'&&($sources['NJCH']??'')==='ORANJC','two_snapshots'=>$result['snapshot_count']===2,
  'case_total'=>$result['cases']===1177,'critical_total'=>$result['critical']===277,'high_total'=>$result['high']===720,'medium_total'=>$result['medium']===180,
  'associated_cost'=>abs($result['associated_inventory_cost']-645791.35)<0.01,'trend_complete'=>$result['trend_days']===30,'pagination'=>$result['first_page_rows']===25,
  'bad_stores_zero'=>(int)($summary['bad_store_cases']??0)===0,'read_only_contract'=>!empty($overview['contract']['read_only'])&&!empty($cases['contract']['read_only']),
  'no_db_link_contract'=>empty($overview['contract']['database_link'])&&empty($cases['contract']['database_link'])
 ];
 $result['result']=!in_array(false,$result['checks'],true)?'PASS':'FAIL';
}catch(Throwable $e){$result['error']=preg_replace('/\s+/',' ',$e->getMessage());}
echo json_encode($result,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),PHP_EOL;exit($result['result']==='PASS'?0:60);
