<?php
declare(strict_types=1);
define('RFJ_CONTEXT_ONLY',true);require __DIR__.'/preflight.php';
$state=json_decode((string)file_get_contents(__DIR__.'/private-state.json'),true);$path='/api/consume/orderPay';$form=$state['pay_form'];$form['msgid']=$state['msgid'];
$hash=static function($v):string{return hash('sha256',json_encode($v,JSON_UNESCAPED_UNICODE|JSON_INVALID_UTF8_SUBSTITUTE|JSON_PRESERVE_ZERO_FRACTION));};
$snapshot=static function()use($q,$store,$ai,$s,$a,$chosen,$state):array{$data=[];foreach(['meal_order'=>'USER_ID','meal_order_refund'=>'USER_ID','initial_menu'=>'STAFF_UUID'] as $table=>$key)$data['store_'.$table]=$q($store,'SELECT * FROM '.$s.$table.' WHERE '.$key.'=?',[$key==='STAFF_UUID'?$chosen['staff']['uuid']:(int)$chosen['store_user']['id']]);$data['store_user']=$q($store,'SELECT * FROM '.$s.'user WHERE ID=?',[(int)$chosen['store_user']['id']]);foreach(['user','recharge_order','user_balance_log','user_gift_log','user_subsidy','user_subsidy_log','user_subsidy_used','account_settlement'] as $table)$data['ai_'.$table]=$q($ai,'SELECT * FROM '.$a.$table.' WHERE USER_ID=?',[(int)$chosen['ai_user']['user_id']]);foreach($data as &$rows){foreach($rows as &$row)ksort($row);unset($row);usort($rows,static function($x,$y){return strcmp(serialize($x),serialize($y));});}unset($rows);return $data;};
$orders=$q($store,'SELECT ID,REFUND_STATUS,PAY_STATUS,PAY_TIME FROM '.$s.'meal_order WHERE ID=? AND ORDER_NO=? AND MSGID=?',[$state['order_id'],$state['pay_no'],$state['msgid']]);if(count($orders)!==1||(int)$orders[0]['refund_status']!==3||(int)$orders[0]['pay_status']!==20)throw new RuntimeException('Only an existing fully refunded owned order may be replayed');
$before=$snapshot();$beforeHash=$hash($before);$auth=['account'=>'CDXCENTREAD'.$lane.bin2hex(random_bytes(4)),'pwd'=>bin2hex(random_bytes(16)),'key'=>bin2hex(random_bytes(16))];
// Authentication is deliberately a temporary fixture, not a business/funds mutation.
$column=$lane==='C'?'"KEY"':'`key`';$stmt=$store->prepare('INSERT INTO '.$s.'api_auth (ACCOUNT,PWD,'.$column.',TYPE,STATUS,START_TIME,END_TIME) VALUES (?,?,?,1,1,?,?)');$stmt->execute([$auth['account'],$auth['pwd'],$auth['key'],date('Y-m-d H:i:s',time()-60),date('Y-m-d H:i:s',time()+120)]);$ids=$q($store,'SELECT ID FROM '.$s.'api_auth WHERE ACCOUNT=? AND PWD=?',[$auth['account'],$auth['pwd']]);if(count($ids)!==1)throw new RuntimeException('Read replay credential not unique');$authId=(int)$ids[0]['id'];
try{$cacheFile=__DIR__.'/cache/CENT10_/'.md5('consume_orderpay_'.$state['msgid']).'.php';if(is_file($cacheFile)&&!is_link($cacheFile))unlink($cacheFile);
 $nonce=bin2hex(random_bytes(16));file_put_contents(__DIR__.'/private-request-order-no.json',json_encode(['nonce'=>$nonce,'path'=>$path,'order_no'=>$state['pay_no']]));chmod(__DIR__.'/private-request-order-no.json',0600);
 $raw=@file_get_contents('http://127.0.0.1:'.($lane==='B'?18301:18302).$path,false,stream_context_create(['http'=>['method'=>'POST','header'=>"Content-Type: application/x-www-form-urlencoded\r\naccount: ".$auth['account']."\r\npwd: ".$auth['pwd']."\r\nkey: ".$auth['key']."\r\nX-RFJ-Fixture-Nonce: ".$nonce."\r\n",'content'=>http_build_query($form),'ignore_errors'=>true,'timeout'=>20]]));$body=json_decode((string)$raw,true);$wire=json_decode((string)$raw);preg_match('#^HTTP/\S+\s+(\d+)#',$http_response_header[0]??'',$m);$after=$snapshot();$time=$body['data']['pay_time']??null;$sourceTime=(string)$orders[0]['pay_time'];
 $shape=static function($v)use(&$shape){if(is_object($v)){$r=[];foreach(get_object_vars($v) as $k=>$x)$r[$k]=$shape($x);ksort($r);return ['object'=>$r];}return is_array($v)?['array'=>array_map($shape,$v)]:(is_int($v)||is_float($v)?'number':gettype($v));};
 $report=['lane'=>$lane,'method'=>'POST','path'=>$path,'scenario'=>'already_fully_refunded_owned_order_db_idempotence','http_status'=>(int)($m[1]??0),'code'=>$body['code']??null,'wire_shape'=>$shape($wire),'raw_wire_sha256'=>hash('sha256',(string)$raw),'same_complete_body_as_original_B_replay'=>hash('sha256',(string)$raw)===hash_file('sha256',__DIR__.'/private-response-pay_repeat_same_msgid_database.json'),'pay_time_type'=>gettype($time),'pay_time_length'=>is_string($time)?strlen($time):null,'pay_time_seconds_match_original_source'=>is_string($time)&&$time===substr($sourceTime,0,19),'raw_database_time_length'=>strlen($sourceTime),'all_selected_business_sources_unchanged'=>$before===$after,'source_before_sha256'=>$beforeHash,'source_after_sha256'=>$hash($after),'business_funds_dml'=>0,'temporary_auth_fixture'=>true,'execution_source_sha256'=>hash_file('sha256',__DIR__.'/source/application/api/service/Consume.php')];
 file_put_contents(__DIR__.'/private-readonly-replay-response.json',(string)$raw);chmod(__DIR__.'/private-readonly-replay-response.json',0600);
}finally{$stmt=$store->prepare('DELETE FROM '.$s.'api_auth WHERE ID=? AND ACCOUNT=? AND PWD=?');$stmt->execute([$authId,$auth['account'],$auth['pwd']]);$deleted=$stmt->rowCount();}
$report['temporary_auth_exact_deleted']=$deleted===1&&$q($store,'SELECT ID FROM '.$s.'api_auth WHERE ID=?',[$authId])===[];echo json_encode($report),"\n";exit($report['all_selected_business_sources_unchanged']&&$report['temporary_auth_exact_deleted']&&$report['code']===0?0:2);
