<?php
declare(strict_types=1);
require_once __DIR__.'/../../authentication/api/connect.php';
$actor=require_auth();
if (!in_array($actor['role'] ?? '', ['admin','staff'], true)) { reply(403,['status'=>'error','message'=>'Only an administrator or staff account can manage HODs.']); }
$method=$_SERVER['REQUEST_METHOD']??'GET';
if($method==='GET'){
    $records=db()->query("SELECT u.id AS user_id,u.full_name,u.email,u.is_active,u.created_at,s.staff_number,s.identity_number AS nrc,d.department_name,c.campus_name FROM hod_assignments h JOIN users u ON u.id=h.user_id JOIN departments d ON d.id=h.department_id JOIN campuses c ON c.id=h.campus_id LEFT JOIN staff s ON s.user_id=u.id WHERE u.role='hod' ORDER BY d.department_name,c.campus_name,u.full_name")->fetchAll();
    reply(200,['status'=>'success','records'=>$records]);
}
if($method!=='POST'){header('Allow: GET, POST');reply(405,['status'=>'error','message'=>'Use GET or POST.']);}
start_auth_session();$token=(string)($_SERVER['HTTP_X_CSRF_TOKEN']??'');if(!hash_equals($_SESSION['csrf_token'],$token))reply(403,['status'=>'error','message'=>'Your form session expired. Refresh and try again.']);
$name=trim((string)($_POST['full_name']??''));$email=strtolower(trim((string)($_POST['email']??'')));$nrc=trim((string)($_POST['nrc']??''));$dep=filter_var($_POST['department_id']??null,FILTER_VALIDATE_INT);$camp=filter_var($_POST['campus_id']??null,FILTER_VALIDATE_INT);
if($name===''||mb_strlen($name)>150||!filter_var($email,FILTER_VALIDATE_EMAIL)||!preg_match('/^\d{6}\/\d{2}\/\d$/',$nrc)||!$dep||!$camp)reply(422,['status'=>'error','message'=>'Complete all fields and enter the NRC as XXXXXX/XX/X.']);
$photo=$_FILES['profile_picture']??null;if(!$photo||$photo['error']!==UPLOAD_ERR_OK||$photo['size']<1||$photo['size']>5242880)reply(422,['status'=>'error','message'=>'Upload a profile photo no larger than 5 MB.']);$mime=(new finfo(FILEINFO_MIME_TYPE))->file($photo['tmp_name']);if(!in_array($mime,['image/jpeg','image/png','image/webp'],true))reply(422,['status'=>'error','message'=>'Use a JPG, PNG or WebP photo.']);$bytes=file_get_contents($photo['tmp_name']);
$q=db()->prepare('SELECT department_name FROM departments WHERE id=? AND is_active=1');$q->execute([$dep]);$department=$q->fetchColumn();if(!$department)reply(422,['status'=>'error','message'=>'Select an active department.']);$q=db()->prepare('SELECT campus_name FROM campuses WHERE id=? AND is_active=1');$q->execute([$camp]);$campusName=$q->fetchColumn();if(!$campusName)reply(422,['status'=>'error','message'=>'Select an active campus.']);
$digits=preg_replace('/\D/','',$nrc);$password=substr($digits,0,6).'@#';$hash=password_hash($password,PASSWORD_DEFAULT);$staffNo='HOD-'.strtoupper(bin2hex(random_bytes(5)));
try{db()->beginTransaction();$db=db();$db->prepare("INSERT INTO users(username,full_name,email,password_hash,role,is_active) VALUES(?,?,?,?,'hod',1)")->execute([$email,$name,$email,$hash]);$uid=$db->lastInsertId();$db->prepare('INSERT INTO staff(user_id,staff_number,department,designation,campus_id,identity_number) VALUES(?,?,?,\'Head of Department\',?,?)')->execute([$uid,$staffNo,$department,(int)$camp,$nrc]);$db->prepare('INSERT INTO user_profile_pictures(user_id,image_data,mime_type) VALUES(?,?,?)')->execute([$uid,$bytes,$mime]);$db->prepare('INSERT INTO hod_assignments(user_id,department_id,campus_id,assigned_by) VALUES(?,?,?,?)')->execute([$uid,(int)$dep,(int)$camp,(int)$actor['id']]);$db->commit();}catch(Throwable $e){if(db()->inTransaction())db()->rollBack();if($e instanceof mysqli_sql_exception&&in_array((int)$e->getCode(),[1062,1452],true))reply(409,['status'=>'error','message'=>'This department and campus already have an HOD, or the email/NRC is already in use.']);throw $e;}
$body="Hello $name,\n\nYour Rockview University SLPS HOD account is ready.\nDepartment: $department\nCampus: $campusName\nLogin ID: $email\nInitial password: $password\n\nSign in through the university SLPS login page and change this initial password as soon as account password settings are available.\n";$sent=send_system_mail($email,'Rockview University SLPS HOD account',$body);
audit_event((int)$actor['id'],'admin','hod_assignment',(int)$uid,'create',$department.' HOD assigned to '.$campusName);
reply(201,['status'=>'success','message'=>$sent?'HOD account created and initial credentials emailed.':'HOD account created, but email delivery failed. Configure outbound mail before sharing the initial password.']);
