<?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);$before=json_decode((string)file_get_contents(__DIR__.'/private-before.json'),true);$initial=json_decode((string)file_get_contents(__DIR__.'/result-private.json'),true);$checks=[];$money=static function($v):string{return bcadd((string)$v,'0',2);};$uid=(int)$chosen['ai_user']['user_id'];$sid=(int)$chosen['store_user']['id'];$hash=static function($v):string{return hash('sha256',json_encode($v,JSON_UNESCAPED_UNICODE|JSON_INVALID_UTF8_SUBSTITUTE|JSON_PRESERVE_ZERO_FRACTION));};
$rc=$q($ai,'SELECT * FROM '.$a.'recharge_order WHERE ORDER_ID=? AND ORDER_NO=? AND USER_ID=?',[$state['recharge_order_id'],$state['cash_no'],$uid]);$orders=$q($store,'SELECT * FROM '.$s.'meal_order WHERE ID=? AND ORDER_NO=? AND USER_ID=?',[$state['order_id'],$state['pay_no'],$sid]);$refunds=$q($store,'SELECT * FROM '.$s.'meal_order_refund WHERE ID=? AND MEAL_ORDER_ID=? AND ORDER_NO=?',[$state['refund_id'],$state['order_id'],$state['refund_no']]);$checks['owned_recharge_order_refund_unique']=count($rc)===1&&count($orders)===1&&count($refunds)===1;if(!$checks['owned_recharge_order_refund_unique'])throw new RuntimeException('Retained financial ownership not complete');$order=$orders[0];$refund=$refunds[0];
$user=$q($ai,'SELECT * FROM '.$a.'user WHERE USER_ID=?',[$uid])[0];$localUser=$q($store,'SELECT ID,UUID,STAFF_UUID,AI_USER_ID,NAME,PAY_MONEY FROM '.$s.'user WHERE ID=?',[$sid])[0];
$checks['recharge_one_cent_zero_gift']=(int)$rc[0]['pay_status']===20&&$money($rc[0]['pay_price'])==='0.01'&&$money($rc[0]['gift_money'])==='0.00'&&$money($rc[0]['actual_money'])==='0.01';$checks['paid_full_refund_states']=(int)$order['pay_status']===20&&(int)$order['order_status']===30&&(int)$order['refund_status']===3&&$money($order['pay_price'])==='0.01'&&$money($order['refund_amount'])==='0.01'&&(int)$refund['refund_status']===2;
$checks['retained_net_principal_and_cumulative']=$money($user['balance'])===bcadd((string)$before['ai_user'][0]['balance'],'0.01',2)&&$money($user['gift_balance'])===$money($before['ai_user'][0]['gift_balance'])&&$money($localUser['pay_money'])===bcadd((string)$before['store_user'][0]['pay_money'],'0.01',2);
$ownCash=$q($ai,'SELECT * FROM '.$a.'user_balance_log WHERE USER_ID=? AND ((SCENE=30 AND ORDER_ID=?) OR (SCENE=20 AND ORDER_ID=?) OR (SCENE=40 AND ORDER_ID=?)) ORDER BY LOG_ID',[$uid,$state['recharge_order_id'],$state['order_id'],$state['refund_id']]);$ownGift=$q($ai,'SELECT * FROM '.$a.'user_gift_log WHERE USER_ID=? AND ((BIZ_TYPE=? AND BIZ_ORDER_NO=?) OR (BIZ_TYPE=? AND BIZ_ORDER_NO=?)) ORDER BY LOG_ID',[$uid,'consume',$state['pay_no'],'refund',$state['refund_no']]);
$checks['cash_log_exact_rows']=count($ownCash)===(1+($money($order['cash'])!=='0.00'?2:0));$sum='0.00';foreach($ownCash as $row){$sum=bcadd($sum,(string)$row['money'],2);$expected=(int)$row['scene']===30?'0.01':((int)$row['scene']===20?bcsub('0',(string)$order['cash'],2):$money($order['cash']));$checks['cash_scene_'.$row['scene'].'_amount']=$money($row['money'])===$expected;$afterCash=bcadd((string)$before['ai_user'][0]['balance'],'0.01',2);if((int)$row['scene']===20)$afterCash=bcsub($afterCash,(string)$order['cash'],2);$checks['cash_scene_'.$row['scene'].'_balance_after']=$money($row['balance_after'])===$afterCash;}$checks['cash_log_net_one_cent']=$sum==='0.01';
$checks['gift_log_exact_rows']=count($ownGift)===($money($order['gift'])!=='0.00'?2:0);$sum='0.00';foreach($ownGift as $row){$sum=bcadd($sum,(string)$row['money'],2);$expected=$row['biz_type']==='consume'?bcsub('0',(string)$order['gift'],2):$money($order['gift']);$checks['gift_'.$row['biz_type'].'_amount']=$money($row['money'])===$expected;}$checks['gift_log_net_zero']=$sum==='0.00';
$settlements=$q($ai,'SELECT * FROM '.$a.'account_settlement WHERE USER_ID=? AND BIZ_ORDER_NO=? ORDER BY SETTLEMENT_ID',[$uid,$state['pay_no']]);$checks['exact_two_success_settlements']=count($settlements)===2;foreach($settlements as $row){$checks['settlement_'.$row['biz_type'].'_amount_and_status']=$money($row['amount'])==='0.01'&&(int)$row['status']===20;foreach(['cash','subsidy','gift'] as $field)$checks['settlement_'.$row['biz_type'].'_'.$field]=$money($row[$field.'_amount'])===$money($order[$field]);if($row['biz_type']==='consume')$checks['consume_settlement_backreference']=(int)$row['settlement_id']===(int)$order['account_settlement_id'];if($row['biz_type']==='refund')$checks['refund_settlement_backreference']=(int)$row['settlement_id']===(int)$refund['account_settlement_id']&&$row['refund_no']===$state['refund_no'];}
foreach(['cash','subsidy','gift'] as $field)$checks['refund_split_'.$field]=$money($order[$field.'_refund_amount'])===$money($order[$field])&&$money($refund[$field.'_refund_amount'])===$money($order[$field]);
$goods=$q($store,'SELECT * FROM '.$s.'initial_menu WHERE MEAL_ORDER_ID=?',[$state['order_id']]);$checks['retained_virtual_detail']=count($goods)===1&&$goods[0]['dishes_uuid']==='custom_dish'&&$money($goods[0]['total_price'])==='0.01'&&(int)$goods[0]['pay_status']===20;
$audit=$q($store,'SELECT * FROM '.$s.'security_audit_log WHERE OPERATOR=? AND ((TARGET_TYPE=? AND TARGET_ID=?) OR (TARGET_TYPE=? AND TARGET_ID=?)) ORDER BY ID',['CDXCENTADMIN','order',(string)$state['order_id'],'refund',(string)$state['refund_id']]);$checks['exact_apply_agree_audits']=count($audit)===2;foreach($audit as $row)$checks['audit_'.$row['event_code']]=(int)$row['store_id']===10001&&$row['result']==='success'&&$row['request_method']==='POST'&&$row['module']==='meal_order';
$checks['zero_external_card_trades']=$q($store,'SELECT ID FROM '.$s.'one_card_trade_order WHERE LOCAL_ORDER_NO=?',[$state['pay_no']])===[];$checks['zero_pickup_rows']=$q($store,'SELECT ID FROM '.$s.'meal_order_pickup WHERE MEAL_ORDER_ID=?',[$state['order_id']])===[];$checks['zero_async_work_rows']=$q($store,'SELECT ID FROM '.$s.'consume_order_work WHERE MSGID=?',[$state['msgid']])===[];$checks['zero_active_temp_credentials']=$q($store,'SELECT ID FROM '.$s.'api_auth WHERE ID=? AND STATUS=1',[$state['auth_id']])===[];
$checks['own_restaurant_and_device_retained']=count($q($store,'SELECT ID FROM '.$s.'restaurants WHERE ID=? AND UUID=? AND NAME=?',[$state['restaurant_id'],$state['restaurant_uuid'],$state['marker']]))===1&&count($q($store,'SELECT ID FROM '.$s.'equipment WHERE ID=? AND CODE=? AND RESTAURANT_ID=?',[$state['equipment_id'],$state['equipment_code'],$state['restaurant_id']]))===1;
// Rebuild unchanged pre-existing ledger sets with native source types, not JSON-normalized old values.
$oldSets=[];foreach(['recharge_order'=>'order_id','user_balance_log'=>'log_id','user_gift_log'=>'log_id','user_subsidy'=>'id','user_subsidy_log'=>'log_id','user_subsidy_used'=>'id','account_settlement'=>'settlement_id'] as $t=>$pk){$rows=$q($ai,'SELECT * FROM '.$a.$t.' WHERE USER_ID=?',[$uid]);$oldIds=array_map(static function($v)use($pk){return (string)$v[$pk];},$before['ai_'.$t]);$rows=array_values(array_filter($rows,static function($v)use($oldIds,$pk){return in_array((string)$v[$pk],$oldIds,true);}));foreach($rows as &$row)ksort($row);unset($row);usort($rows,static function($x,$y){return strcmp(serialize($x),serialize($y));});$oldSets[$t]=['rows'=>count($rows),'unchanged'=>$hash($rows)===$initial['source_before']['ai_'.$t]['sha256']];$checks['preexisting_'.$t.'_unchanged']=$oldSets[$t]['unchanged'];}
$wire=[];foreach(['internal_pay','pay_repeat_same_msgid_database'] as $case){$body=json_decode((string)file_get_contents(__DIR__.'/private-response-'.$case.'.json'),true);$time=$body['data']['pay_time']??null;$wire[$case]=['pay_time_type'=>gettype($time),'pay_time_length'=>is_string($time)?strlen($time):null,'pay_time_mysql_second_format'=>is_string($time)&&preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/D',$time)===1];}
$passed=!in_array(false,$checks,true);$inventory=['marker'=>$state['marker'],'recharge_order_id'=>$state['recharge_order_id'],'order_id'=>$state['order_id'],'refund_id'=>$state['refund_id'],'restaurant_id'=>$state['restaurant_id'],'equipment_id'=>$state['equipment_id'],'initial_menu_ids'=>array_map(static function($r){return (int)$r['id'];},$goods),'settlement_ids'=>array_map(static function($r){return (int)$r['settlement_id'];},$settlements),'cash_log_ids'=>array_map(static function($r){return (int)$r['log_id'];},$ownCash),'gift_log_ids'=>array_map(static function($r){return (int)$r['log_id'];},$ownGift),'audit_ids'=>array_map(static function($r){return (int)$r['id'];},$audit),'owner_sha256'=>$state['owner_sha256']];
$report=['lane'=>$lane,'independent_new_connections'=>true,'database_writes'=>0,'financial_source_checks'=>$checks,'all_financial_source_passed'=>$passed,'retained_inventory'=>$inventory,'actual_split'=>['cash'=>$money($order['cash']),'gift'=>$money($order['gift']),'subsidy'=>$money($order['subsidy'])],'net_retained'=>['cash'=>'0.01','gift'=>'0.00','store_pay_money'=>'0.01'],'existing_source_sets'=>$oldSets,'wire_date_contract'=>$wire,'initial_tool_failure'=>$initial['failure'],'normalization'=>'No DB value changed; canonical two-decimal arithmetic only for source financial comparison'];file_put_contents(__DIR__.'/audit-private.json',json_encode($report,JSON_PRETTY_PRINT));chmod(__DIR__.'/audit-private.json',0600);echo json_encode($report),"\n";exit($passed?0:2);
