<?php require dirname(__DIR__).'/app/core.php';csrf();$id=(int)($_POST['workflow_id']??0);$result=$_POST['result']??'';if(!in_array($result,['Pass','Fail'],true))exit('Invalid result');$s=$pdo->prepare('SELECT r.*,a.serial_number,a.recertification_expiration_date,ri.sales_order_number FROM recertification_workflows r JOIN afguards a ON a.id=r.afguard_id JOIN receiving_intakes ri ON ri.id=r.receiving_intake_id WHERE r.id=?');$s->execute([$id]);$r=$s->fetch()?:exit('Workflow not found');$vr=null;$vn=null;$vat=null;$vby=null;if($r['workflow_type']==='Annual Recertification'&&$result==='Pass'){$input=$_POST['voucher_required']??null;if(!in_array($input,['0','1'],true))exit('Select whether a voucher is required.');$vr=(int)$input;$raw=norm_voucher($_POST['voucher_number']??'');if($vr===1){if(!valid_voucher($raw))exit('Voucher must have four groups of 3–4 letters/numbers separated by hyphens.');$vn=$raw;$vat=now_utc();$vby=$_SESSION['user'];}elseif($raw!=='')exit('Leave voucher blank when Not Required is selected.');}
try{$pdo->beginTransaction();if($result==='Fail'){$designation='Recalibration';$location='Shipping';$status='Preparing for GmbH';$dest=$pdo->query("SELECT id FROM shipping_destinations WHERE code='GMBH-DE'")->fetchColumn();$pdo->prepare("INSERT INTO shipments(afguard_id,workflow_id,shipment_type,destination_id,sales_order_number,shipping_status,record_updated_by) VALUES(?,?,'GmbH Recalibration',?,?,'Required',?)")->execute([$r['afguard_id'],$id,$dest,$r['sales_order_number'],$_SESSION['user']]);}elseif($r['workflow_type']==='Annual Recertification'){$designation='Recertification';$location='Shipping';$status='Released to Shipping';$pdo->prepare("INSERT INTO shipments(afguard_id,workflow_id,shipment_type,client_id,sales_order_number,voucher_number,shipping_status,record_updated_by) VALUES(?,?,'Return to Client',?,?,?,'Required',?)")->execute([$r['afguard_id'],$id,$r['client_id'],$r['sales_order_number'],$vn,$_SESSION['user']]);}else{$designation=annual_valid($r['recertification_expiration_date'])?'Rental':'For sale';$location='Laboratory';$status='Complete';}$pdo->prepare('UPDATE recertification_workflows SET workflow_status=?,test_result=?,test_completed_at=?,tested_by=?,voucher_required=?,voucher_number=?,voucher_recorded_at=?,voucher_recorded_by=?,record_updated_by=? WHERE id=?')->execute([$status,$result,now_utc(),$_SESSION['user'],$vr,$vn,$vat,$vby,$_SESSION['user'],$id]);$pdo->prepare('UPDATE afguards SET designation=?,current_location=?,record_updated_by=? WHERE id=?')->execute([$designation,$location,$_SESSION['user'],$r['afguard_id']]);$pdo->commit();flash($result==='Fail'?'Failed: mandatory GmbH shipment created.':'Passed and workflow advanced.');}catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();flash($e->getMessage(),'error');}go('recertification.php');