<?php
declare(strict_types=1);
define('RFJ_CONTEXT_ONLY',true);require __DIR__.'/preflight.php';
set_exception_handler(static function(Throwable $e):void{echo json_encode(['setup_failed'=>true,'class'=>get_class($e),'message_sha256'=>hash('sha256',$e->getMessage()),'funds_dml'=>0]),"\n";exit(2);});
$resume=is_file(__DIR__.'/private-state.json');
foreach(array_merge($out['triggers'],$out['ai_triggers']) as $triggers)if($triggers!==[])throw new RuntimeException('Unknown trigger effects');
$marker='CDXCENT'.$lane.strtoupper(bin2hex(random_bytes(4)));$now=date('Y-m-d H:i:s');$state=['marker'=>$marker,'owner_sha256'=>$out['synthetic_account']['lease_marker_sha256'],'phase'=>'setup','restaurant_id'=>0,'equipment_id'=>0,'auth_id'=>0,'order_id'=>0,'refund_id'=>0,'recharge_order_id'=>0,'cash_no'=>'RC'.$marker.'C','pay_no'=>$marker.'R','refund_no'=>'RF'.$marker.'F','equipment_code'=>$marker,'msgid'=>$marker.'MSG'];
if($resume){$state=json_decode((string)file_get_contents(__DIR__.'/private-state.json'),true);$marker=$state['marker']??'';if(!preg_match('/^CDXCENT'.$lane.'[A-F0-9]{8}$/D',$marker)||$state['owner_sha256']!==$out['synthetic_account']['lease_marker_sha256']||$state['phase']!=='setup'||$state['auth_id']!==0||$state['restaurant_id']<=0||$state['equipment_id']<=0)throw new RuntimeException('Never replay a qualified or financial state');if($q($ai,'SELECT ORDER_ID FROM '.$a.'recharge_order WHERE ORDER_NO=?',[$state['cash_no']])||$q($store,'SELECT ID FROM '.$s.'meal_order WHERE MSGID=?',[$state['msgid']])||$q($store,'SELECT ID FROM '.$s.'api_auth WHERE ACCOUNT=?',[$marker]))throw new RuntimeException('Existing funding/order/auth prevents setup-only resume');}
$save=static function()use(&$state):void{file_put_contents(__DIR__.'/private-state.json',json_encode($state,JSON_PRETTY_PRINT));chmod(__DIR__.'/private-state.json',0600);};$save();
$insert=static function(string $table,array $data)use($store,$s,$out,$lane):void{$columns=array_map(static function($v){return strtolower($v['column_name']);},$out['schema'][$table]);if(array_diff(array_keys($data),$columns))throw new RuntimeException('Fixture column not in approved schema');$quoted=array_map(static function($key)use($lane){return $lane==='C'?'"'.strtoupper($key).'"':'`'.$key.'`';},array_keys($data));$sql='INSERT INTO '.$s.$table.' ('.implode(',',$quoted).') VALUES ('.implode(',',array_fill(0,count($data),'?')).')';$store->prepare($sql)->execute(array_values($data));};
if(!$resume){$uuid=sprintf('%s-%s-%s-%s-%s',bin2hex(random_bytes(4)),bin2hex(random_bytes(2)),bin2hex(random_bytes(2)),bin2hex(random_bytes(2)),bin2hex(random_bytes(6)));
$insert('restaurants',['uuid'=>$uuid,'name'=>$marker,'create_by'=>$marker,'book_rules'=>'{}','order_rules'=>'{}','status'=>1,'is_delete'=>2,'stall_type'=>1]);$rows=$q($store,'SELECT ID FROM '.$s.'restaurants WHERE UUID=? AND NAME=? AND CREATE_BY=?',[$uuid,$marker,$marker]);if(count($rows)!==1)throw new RuntimeException('Own restaurant not unique');$state['restaurant_id']=(int)$rows[0]['id'];$state['restaurant_uuid']=$uuid;$save();
$insert('equipment',['code'=>$marker,'name'=>$marker,'type'=>9,'restaurant_id'=>$state['restaurant_id'],'status'=>1,'del_flag'=>0,'create_time'=>$now,'update_time'=>$now,'create_by'=>$marker,'update_by'=>$marker,'print_receipt'=>0]);$rows=$q($store,'SELECT ID FROM '.$s.'equipment WHERE CODE=? AND NAME=? AND CREATE_BY=?',[$marker,$marker,$marker]);if(count($rows)!==1)throw new RuntimeException('Own equipment not unique');$state['equipment_id']=(int)$rows[0]['id'];$save();
}else{if(count($q($store,'SELECT ID FROM '.$s.'restaurants WHERE ID=? AND NAME=? AND CREATE_BY=?',[$state['restaurant_id'],$marker,$marker]))!==1||count($q($store,'SELECT ID FROM '.$s.'equipment WHERE ID=? AND CODE=? AND RESTAURANT_ID=? AND CREATE_BY=?',[$state['equipment_id'],$marker,$state['restaurant_id'],$marker]))!==1)throw new RuntimeException('Resumed own fixture ownership differs');}
$quote=new ReflectionMethod($consumer,'applyMarketingStrategy');$quote->setAccessible(true);$marketing=$quote->invoke($consumer,$chosen['staff']['uuid'],'0.01',$now,$state['restaurant_id'],2,(int)$chosen['store_user']['id']);if(bccomp((string)$marketing['pay_price'],'0.01',2)!==0||bccomp((string)$marketing['management_fee'],'0.00',2)!==0||bccomp((string)$marketing['discount_amount'],'0.00',2)!==0){$state['phase']='qualification-marketing-blocked';$save();throw new RuntimeException('Original marketing is not exactly one cent');}
$authPwd=bin2hex(random_bytes(16));$authKey=bin2hex(random_bytes(16));$insert('api_auth',['account'=>$marker,'pwd'=>$authPwd,'key'=>$authKey,'type'=>1,'status'=>1,'start_time'=>date('Y-m-d H:i:s',time()-60),'end_time'=>date('Y-m-d H:i:s',time()+3600)]);$rows=$q($store,'SELECT ID FROM '.$s.'api_auth WHERE ACCOUNT=? AND PWD=? AND '.$s.'api_auth.'.($lane==='C'?'"KEY"':'`key`').'=?',[$marker,$authPwd,$authKey]);if(count($rows)!==1)throw new RuntimeException('Own API credential not unique');$state['auth_id']=(int)$rows[0]['id'];$state['phase']='qualified-ready';$save();file_put_contents(__DIR__.'/private-auth.json',json_encode(['account'=>$marker,'pwd'=>$authPwd,'key'=>$authKey]));chmod(__DIR__.'/private-auth.json',0600);
$summary=['lane'=>$lane,'funds_dml'=>0,'new_staff_or_permissions'=>0,'one_cent_cash_and_zero_gift_forecast'=>true,'marketing_exactly_one_cent'=>true,'non_onecard_non_bank'=>true,'retained_setup'=>['marker'=>$marker,'restaurant_id'=>$state['restaurant_id'],'equipment_id'=>$state['equipment_id']],'temporary_api_auth_created'=>true,'phase'=>$state['phase']];echo json_encode($summary),"\n";
