<?php require dirname(__DIR__).'/app/core.php';csrf();$id=(int)($_POST['afguard_id']??0);$type=$_POST['intake_type']??'';$s=$pdo->prepare('SELECT * FROM afguards WHERE id=?');$s->execute([$id]);$a=$s->fetch()?:exit('Not found');$client=$a['owned_by']==='client';$so=$client?strtoupper(trim($_POST['sales_order_number']??'')):null;if($client&&$so==='')exit('Sales Order Number required');$allowed=$client?['Client Annual Recertification']:['Rental Return','Loan Return','GmbH Recalibration Return'];if(!in_array($type,$allowed,true))exit('Invalid intake');$designation=$client?'Recertification':'Interim Recert';$workflow=$client?'Annual Recertification':'Interim Recertification';try{$pdo->beginTransaction();$pdo->prepare("INSERT INTO receiving_intakes(afguard_id,intake_type,client_id,sales_order_number,received_condition,received_by,resulting_designation) VALUES(?,?,?,?, 'used',?,?)")->execute([$id,$type,$a['owner_client_id'],$so,$_SESSION['user'],$designation]);$intake=$pdo->lastInsertId();$pdo->prepare("INSERT INTO recertification_workflows(afguard_id,receiving_intake_id,workflow_type,client_id,record_updated_by) VALUES(?,?,?,?,?)")->execute([$id,$intake,$workflow,$a['owner_client_id'],$_SESSION['user']]);$pdo->prepare("UPDATE afguards SET asset_condition='used',designation=?,current_location='Laboratory',record_updated_by=? WHERE id=?")->execute([$designation,$_SESSION['user'],$id]);$pdo->commit();flash('Intake complete. Route sensor to Laboratory.');}catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();flash($e->getMessage(),'error');}go('receiving.php');