<?php

declare(strict_types=1);

$options=getopt('', ['target::']);
$root=rtrim((string)($options['target']??'C:\xampp\htdocs\ddb-new'),"\\/");
$bootstrap=$root.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR.'bootstrap.php';
if(!is_file($bootstrap)){fwrite(STDERR,"TARGET_BOOTSTRAP_NOT_FOUND|$bootstrap\n");exit(10);} require $bootstrap;

use App\Core\Database;

$result=['release'=>'DIAR-6B.4','operation'=>'ORACLE_PRECHECK','status'=>'FAIL','writes'=>'NONE','gates'=>[]];
try{
 $id=Database::fetchOne('njch',"SELECT UPPER(SYS_CONTEXT('USERENV','DB_NAME')) DB_NAME,UPPER(SYS_CONTEXT('USERENV','CURRENT_SCHEMA')) CURRENT_SCHEMA FROM dual");
 $result['identity']=$id;
 if(strtoupper((string)($id['db_name']??''))!=='ORANJC'||strtoupper((string)($id['current_schema']??''))!=='WATANY') throw new RuntimeException('CONTROL_DB_IDENTITY_REQUIRED_ORANJC_WATANY');
 $result['gates']['CONTROL_IDENTITY']='PASS';
 $base=Database::fetchOne('njch',"SELECT COUNT(*) OBJECT_COUNT FROM USER_TABLES WHERE TABLE_NAME IN ('DASH_DIAR_CASES','DASH_DIAR_CASE_ASSIGNMENTS','DASH_DIAR_CASE_HISTORY','DASH_DIAR_CASE_NOTES','DASH_DIAR_CASE_EVIDENCE')");
 if((int)($base['object_count']??0)!==5) throw new RuntimeException('DIAR4B_BASE_SCHEMA_REQUIRED');
 $result['gates']['BASE_SCHEMA_5_TABLES']='PASS';
 $counts=Database::fetchOne('njch',"SELECT COUNT(*) TOTAL_CASES,SUM(CASE WHEN STATUS_CODE='CLOSED' THEN 1 ELSE 0 END) CLOSED_CASES FROM DASH_DIAR_CASES");
 $result['counts']=$counts;
 $result['gates']['CASE_DATA_READABLE']='PASS';
 $result['status']='PASS';
 echo 'DIAR_6B_4_ORACLE_PRECHECK|PASS|DB=ORANJC|SCHEMA=WATANY|BASE_TABLES=5|TOTAL_CASES='.(int)($counts['total_cases']??0).'|WRITES=NONE'.PHP_EOL;
 exit(0);
}catch(Throwable $e){$result['error']=$e->getMessage();fwrite(STDERR,'DIAR_6B_4_ORACLE_PRECHECK|FAIL|ERROR='.$e->getMessage().PHP_EOL);exit(20);}
