<?php

declare(strict_types=1);

$lane=(string)($argv[1]??'');$mode=(string)($argv[2]??'');$self=$lane==='B'?(string)hash_file('sha256',__FILE__):'';
if(count($argv)!==3||!in_array($lane,['B','C'],true)||!in_array($mode,['--preflight','--execute','--audit'],true)
    ||($mode==='--execute'&&((string)getenv('CDX_DORDER_READ')!=='DEDUCTION_ORDER_READ_V1'
        ||($lane==='B'?!hash_equals($self,(string)getenv('CDX_DORDER_SHA')):(string)getenv('CDX_DORDER_SOURCE_CHECKED')!=='1')))){
    echo json_encode(['status'=>'default_deny','connected'=>false,'http_sent'=>false,'dml'=>false]),PHP_EOL;exit(78);
}
$stage='bootstrap';set_exception_handler(static function(Throwable$e)use(&$stage):void{echo json_encode(['status'=>'redacted_stop','stage'=>$stage,'class'=>get_class($e),'code'=>(string)$e->getCode(),'message_sha'=>hash('sha256',$e->getMessage())]),PHP_EOL;exit(2);});
if($lane==='B'){$state='/tmp/cdx-rpe-b-worker.state';if(!is_file($state)||is_link($state)||(fileperms($state)&0777)!==0600)throw new RuntimeException('B state');$s=parse_ini_file($state,false,INI_SCANNER_RAW);$root=(string)($s['root']??'');$pid=(int)($s['pid']??0);$port=(int)($s['port']??0);}else{$root='/tmp/zhct-dm-poc-20260928.fcpiiN/store';$pid=112175;$port=18080;}
$base='http://127.0.0.1:'.$port;$runtimeReady=static function()use($lane,$root,$pid,$port,$base):bool{if($lane==='B'){$cmd=(string)shell_exec('/bin/ps -p '.$pid.' -o command=');$owner=trim((string)shell_exec('/usr/sbin/lsof -nP -t -iTCP:'.$port.' -sTCP:LISTEN 2>/dev/null'));$ok=$owner===(string)$pid&&strpos($cmd,$root.'/public')!==false;}else{$cmd=(string)@file_get_contents('/proc/'.$pid.'/cmdline');$ok=strpos($cmd,$root.'/public')!==false&&trim((string)@file_get_contents('/proc/'.$pid.'/task/'.$pid.'/children'))==='';}$b=json_decode((string)@file_get_contents($base.'/__poc_boundary'),true);return$ok&&is_array($b)&&($b['external_stubs']??null)===true&&($b['redis_isolated']??null)===true&&($b['real_queue']??true)===false;};if(!$runtimeReady())throw new RuntimeException('HTTP boundary');
foreach(['application/p/controller/AccountSetting.php'=>'65cf66aaa8866ec072841bcd4453d873f787d23c5a4fdb9036be9c3a7566fb66','application/p/logic/AccountSetting.php'=>'174036b5817358b659e086d9d4136e1bfc5bd3e8c75930e8e286c7341d6583e2','application/p/logic/AccountSettingPolicy.php'=>'385e3fa6a025d24a6cf8e7285e0a7f85990637116930b9024471378b87fd75ca','application/base/Security.php'=>'b82e5ed982e6084a2b2942c033d4767428fb6f1012ba628f609477a7563eb4c3']as$file=>$sha)if(hash_file('sha256',$root.'/'.$file)!==$sha)throw new RuntimeException('Source drift');
if($lane==='B'){$cfg=require'/Users/wiscourper/Documents/workspace/zhct/zhctproject/store/application/config/local/database.php';$dsn='mysql:host='.$cfg['hostname'].';port='.($cfg['hostport']??3306).';dbname='.$cfg['database'].';charset='.($cfg['charset']??'utf8');$table='ydy_config';$user='ydy_user';}else{$cfg=['username'=>(string)getenv('POC_USER'),'password'=>(string)getenv('POC_PASSWORD')];if((string)getenv('POC_HOST')!=='127.0.0.1'||(string)getenv('POC_PORT')!=='5237'||strtoupper((string)getenv('POC_SCHEMA'))!=='ZHCT_APP')throw new RuntimeException('C DB drift');$dsn='dm:host=127.0.0.1;port=5237;schema=ZHCT_APP';$table='YDY_CONFIG';$user='YDY_USER';}
$connect=static function()use($dsn,$cfg):PDO{return new PDO($dsn,(string)$cfg['username'],(string)$cfg['password'],[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_CASE=>PDO::CASE_LOWER]);};$db=$connect();
$row=static function(PDO$p,string$table):array{$s=$p->prepare('SELECT * FROM '.$table." WHERE CONFIG_KEY='account_deduction_order' AND RESTAURANT_ID=1 ORDER BY ID");$s->execute();$rows=$s->fetchAll(PDO::FETCH_ASSOC);if(count($rows)!==1)throw new RuntimeException('Config cardinality');$clean=[];foreach(array_change_key_case($rows[0],CASE_LOWER)as$k=>$v)$clean[$k]=is_resource($v)?stream_get_contents($v):$v;ksort($clean);return$clean;};$source=$row($db,$table);$sourceSha=hash('sha256',serialize($source));$raw=json_decode((string)$source['config_value'],true);$allowed=['subsidy','cash','gift'];$valid=is_array($raw)&&count($raw)===3&&count(array_unique($raw))===3&&!array_diff($raw,$allowed)&&!array_diff($allowed,$raw);$expected=$valid?array_values($raw):$allowed;$markerCount=static function(PDO$p,string$user):int{return(int)$p->query("SELECT COUNT(*) FROM $user WHERE UUID LIKE 'CDXDORDER%' OR ACCOUNT LIKE 'CDXDORDER%'")->fetchColumn();};
if($mode==='--preflight'){echo json_encode(['status'=>'natural_ready','lane'=>$lane,'source_sha'=>$sourceSha,'natural_order'=>$expected,'used_default'=>!$valid,'marker_rows'=>$markerCount($db,$user),'http_sent'=>false,'dml'=>false]),PHP_EOL;exit(0);}
if($mode==='--audit'){$receipt=(string)getenv('CDX_DORDER_RECEIPT');if(!preg_match('~^/tmp/cdx-dorder-[bc]-[a-f0-9]{12}/receipt\.json$~D',$receipt)||!is_file($receipt)||is_link($receipt)||is_link(dirname($receipt))||(fileperms(dirname($receipt))&0777)!==0700||(fileperms($receipt)&0777)!==0600)throw new RuntimeException('Receipt');$saved=json_decode((string)file_get_contents($receipt),true);if(!is_array($saved)||($saved['lane']??null)!==$lane||($saved['phase']??null)!=='http_complete'||($saved['source_sha']??null)!==hash('sha256',serialize($row($connect(),$table)))||$markerCount($connect(),$user)!==0)throw new RuntimeException('Audit');unlink($receipt);rmdir(dirname($receipt));echo json_encode(['status'=>'independent_readonly_pass','lane'=>$lane,'source_unchanged'=>true,'marker_rows'=>0,'private_receipt_removed'=>true]),PHP_EOL;exit(0);}
if($markerCount($db,$user)!==0)throw new RuntimeException('Marker');$marker='CDXDORDER'.strtoupper(bin2hex(random_bytes(4)));$dir='/tmp/cdx-dorder-'.strtolower($lane).'-'.strtolower(bin2hex(random_bytes(6)));if(!mkdir($dir,0700)||!chmod($dir,0700))throw new RuntimeException('Private dir');$receipt=$dir.'/receipt.json';$saved=['lane'=>$lane,'phase'=>'before_http','source_sha'=>$sourceSha];$save=static function()use(&$saved,$receipt):void{$e=json_encode($saved);if(file_put_contents($receipt,$e,LOCK_EX)!==strlen($e)||!chmod($receipt,0600))throw new RuntimeException('Receipt write');};$save();require_once$root.'/application/base/Security.php';$token=\app\base\Security::encrypt(implode("\t",['2147480031',$marker,$marker,'0','','',$marker]));$request=static function(?string$token)use($base,$runtimeReady):array{if(!$runtimeReady())throw new RuntimeException('Boundary');$body='';$headers="Content-Type: application/x-www-form-urlencoded\r\nContent-Length: 0\r\n".($token===null?'':'token: '.$token."\r\n");$stream=@fopen($base.'/p/AccountSetting/deductionOrder','rb',false,stream_context_create(['http'=>['method'=>'POST','header'=>$headers,'content'=>$body,'timeout'=>20,'ignore_errors'=>true]]));$raw=is_resource($stream)?stream_get_contents($stream,1048577):false;$meta=is_resource($stream)?stream_get_meta_data($stream):[];$hs=$http_response_header??[];if(is_resource($stream))fclose($stream);preg_match('/HTTP\/\S+\s+(\d+)/',(string)($hs[0]??''),$m);$within=is_string($raw)&&strlen($raw)<=1048576;$json=$within?json_decode($raw,true):null;if(!isset($m[1])||(int)$m[1]!==200||!empty($meta['timed_out'])||!$within||!is_array($json)||json_last_error()!==JSON_ERROR_NONE)throw new RuntimeException('HTTP unknown');return$json;};$unauth=$request(null);if((int)($unauth['code']??0)===0)throw new RuntimeException('Unauth accepted');$body=$request($token);if((int)($body['code']??-1)!==0||($body['data']['order']??null)!==$expected)throw new RuntimeException('Response/source mismatch');$shape=['code'=>gettype($body['code']??null),'data'=>['order'=>['[]'=>gettype($body['data']['order'][0]??null)]],'message'=>gettype($body['message']??null)];if(hash('sha256',serialize($row($connect(),$table)))!==$sourceSha||$markerCount($connect(),$user)!==0)throw new RuntimeException('Read mutated source');$saved['phase']='http_complete';$save();echo json_encode(['status'=>'HTTP_PASS_READONLY_PENDING_AUDIT','lane'=>$lane,'source_match'=>true,'used_default'=>!$valid,'key_sha'=>hash('sha256',serialize(array_keys($body))),'type_sha'=>hash('sha256',serialize($shape)),'shape'=>$shape,'source_sha'=>$sourceSha,'marker_rows'=>0,'receipt'=>$receipt]),PHP_EOL;
