<?php require dirname(__DIR__).'/app/core.php';require_roles(['admin','standard']);csrf();$f=$_FILES['csv']??null;if(!$f||$f['error']||$f['size']>5000000)exit('Invalid upload');$h=fopen($f['tmp_name'],'r');$head=fgetcsv($h);$head[0]=ltrim($head[0],"\xEF\xBB\xBF");$need=['serial_number','owned_by','owner_client','country_code','model','condition','designation','current_location','recertification_expiration_date','notes'];if(array_diff($need,$head))exit('Missing columns');$ix=array_flip($head);$n=0;try{$pdo->beginTransaction();while($row=fgetcsv($h)){$g=fn($k)=>trim($row[$ix[$k]]??'');$s=norm_serial($g('serial_number'));if(!valid_serial($s))throw new Exception('Invalid serial row '.($n+2));$o=strtolower($g('owned_by'));$cid=null;if($o==='client'){$cc=strtoupper($g('country_code'));$q=$pdo->prepare('SELECT id FROM clients WHERE name=? COLLATE NOCASE AND country_code=?');$q->execute([$g('owner_client'),$cc]);$cid=$q->fetchColumn();if(!$cid){$pdo->prepare('INSERT INTO clients(name,country_code) VALUES(?,?)')->execute([$g('owner_client'),$cc]);$cid=$pdo->lastInsertId();}}$c=strtolower($g('condition'));$d=$c==='new'?'For sale':($c==='scrap'?null:$g('designation'));$pdo->prepare("INSERT INTO afguards(serial_number,owned_by,owner_client_id,model,asset_condition,designation,current_location,recertification_expiration_date,record_updated_by,notes) VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT(serial_number) DO UPDATE SET owned_by=excluded.owned_by,owner_client_id=excluded.owner_client_id,model=excluded.model,asset_condition=excluded.asset_condition,designation=excluded.designation,current_location=excluded.current_location,recertification_expiration_date=excluded.recertification_expiration_date,record_updated_by=excluded.record_updated_by,notes=excluded.notes")->execute([$s,$o,$cid,$g('model'),$c,$d,$g('current_location'),$g('recertification_expiration_date')?:null,user()['username'],$g('notes')]);$n++;}$pdo->commit();audit('import','ASSET_IMPORT','success',null,null,"$n rows");queue_event('ASSET_IMPORT_COMPLETE','AFGTrac import complete',"$n rows imported");flash("Imported $n rows.");}catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();audit('import','ASSET_IMPORT','failure',null,null,$e->getMessage());flash($e->getMessage(),'error');}go('assets.php#import');