<?php
declare(strict_types=1);
require __DIR__.'/contract.php';$pre=smLoad('preflight-private.json');$db=smPdo();$seed=$pre['seed'];$journal=getenv('SM7_RUNTIME').'/setup-intent-private.json';if(is_file($journal)||is_file(getenv('SM7_RUNTIME').'/fixture-private.json')){throw new RuntimeException('Never replay successful or ambiguous fixture inserts');}
$ids=[];$state=['seed'=>$seed,'inserted_ids'=>[],'pending'=>null,'phase'=>'begin'];smSave('setup-intent-private.json',$state);$db->beginTransaction();
try{foreach($pre['rows'] as $t=>$row){$state['pending']=$t;smSave('setup-intent-private.json',$state);$quote=static function(string $n):string{return getenv('SM7_LANE')==='C'?'"'.strtoupper($n).'"':'`'.$n.'`';};$names=array_map($quote,array_keys($row));$sql='INSERT INTO '.$quote('ydy_'.$t).' ('.implode(',',$names).') VALUES ('.implode(',',array_fill(0,count($row),'?')).')';$s=$db->prepare($sql);$s->execute(array_values($row));
 if($t==='staff_department'){$found=smRows($db,'SELECT id FROM ydy_staff_department WHERE department_uuid=? AND staff_uuid=? AND create_by=?',[$seed['department'],$seed['staff'],$seed['marker']]);}else{$k=['date_menu_hardware_img'=>'image','initial_menu'=>'menu'][$t]??$t;$found=smRows($db,'SELECT id FROM ydy_'.$t.' WHERE uuid=?',[$seed[$k]]);}
 if(count($found)!==1||(int)$found[0]['id']<=0){throw new RuntimeException('Inserted ownership not unique');}$ids[$t]=(int)$found[0]['id'];$state['inserted_ids']=$ids;$state['pending']=null;smSave('setup-intent-private.json',$state);
}$db->commit();$state['phase']='committed';smSave('setup-intent-private.json',$state);$own=hcOwnRows($db,$seed,$ids);$after=hcSnapshot($db,$seed,$ids);if($after!==$pre['before']){throw new RuntimeException('Natural source changed');}
$zero=[];foreach($own as $t=>$r){foreach($r as $f=>$v){if(preg_match('/money|balance|cash|subsidy|gift|price/',$f)&&$v!==null){if(!is_numeric($v)||bccomp((string)$v,'0',8)!==0){throw new RuntimeException('New fixture funds not zero');}$zero[]=$t.'.'.$f;}}}
smSave('fixture-private.json',['seed'=>$seed,'ids'=>$ids,'own_rows'=>$own,'natural_before'=>$pre['before'],'natural_after'=>$after,'fund_fields_zero'=>$zero,'retained'=>true,'meal_updates'=>0]);echo json_encode(['lane'=>getenv('SM7_LANE'),'inserted_rows'=>7,'ids'=>$ids,'natural_unchanged'=>true,'funds_zero'=>true,'retained'=>true]),PHP_EOL;
}catch(Throwable $e){if($db->inTransaction()){$db->rollBack();}$state['phase']='failed-no-automatic-replay';$state['error_hash']=hash('sha256',$e->getMessage());smSave('setup-intent-private.json',$state);smSave('setup-error-private.json',['message'=>$e->getMessage()]);echo json_encode(['status'=>'fail','phase'=>$state['phase'],'committed_or_attempted_ids'=>$ids,'error_hash'=>$state['error_hash']]),PHP_EOL;exit(1);}
