<?php
declare(strict_types=1);
date_default_timezone_set('Asia/Shanghai');require __DIR__.'/common.php';$pre=smLoad('preflight-private.json');$db=smPdo();$lane=getenv('SM7_LANE');$marker='CDXDMENU10'.$lane.strtoupper(bin2hex(random_bytes(4)));$uuid=smGuid();$now=date('Y-m-d H:i:s');
if(is_file(getenv('SM7_RUNTIME').'/actor-private.json')||is_file(getenv('SM7_RUNTIME').'/actor-intent-private.json')){throw new RuntimeException('Never duplicate actor setup');}
if(smRows($db,'SELECT id FROM ydy_user WHERE uuid=? OR account=?',[$uuid,$marker])){throw new RuntimeException('Actor collision');}
smSave('actor-intent-private.json',['marker'=>$marker,'uuid'=>$uuid,'insert_attempted'=>true,'natural_user_before'=>$pre['natural_user_before']]);
$s=$db->prepare('INSERT INTO ydy_user (UUID,ACCOUNT,PWD,SALT,NAME,TYPE,STATUS,CREATE_TIME,CREATE_BY,IS_DELETE) VALUES (?,?,?,?,?,0,0,?,?,0)');$s->execute([$uuid,$marker,'DISABLED',strtoupper(bin2hex(random_bytes(8))),$marker,$now,$marker]);
$rows=smRows($db,'SELECT * FROM ydy_user WHERE UUID=? AND ACCOUNT=? AND CREATE_BY=?',[$uuid,$marker,$marker]);if(count($rows)!==1||(int)$rows[0]['id']<=0||(int)$rows[0]['type']!==0||(int)$rows[0]['status']!==0){throw new RuntimeException('Actor exact ownership');}
$funds=[];foreach($rows[0] as $k=>$v){if(preg_match('/money|balance|cash|subsidy|gift/',$k)&&$v!==null){if(!is_numeric($v)||bccomp((string)$v,'0',8)!==0){throw new RuntimeException('Actor nonzero fund '.$k);}$funds[$k]='0';}}
$after=smUserDigest($db,(int)$rows[0]['id']);if($after!==$pre['natural_user_before']){throw new RuntimeException('Natural user changed');}
smSave('actor-private.json',['id'=>(int)$rows[0]['id'],'uuid'=>$uuid,'marker'=>$marker,'type'=>0,'status'=>0,'source'=>$rows[0],'fund_zero'=>$funds,'natural_user_unchanged'=>true]);
echo json_encode(['lane'=>$lane,'owned_actor_id'=>(int)$rows[0]['id'],'marker'=>$marker,'type'=>0,'status'=>0,'only_account_insert_rows'=>1,'fund_fields_zero'=>array_keys($funds),'natural_user_unchanged'=>true,'retained'=>true]),PHP_EOL;
