<?php
require_once '../../config/config.php';
require_once '../helper/audit_log.php';
header('Content-Type: application/json');
try {
	$id=(int)($_POST['id']??0);
	$college_id=(int)($_POST['college_id']??0);
	$external_college_name=trim($_POST['external_college_name']??'');
	$staff_code=trim($_POST['staff_code']??'');
	$first_name=trim($_POST['first_name']??'');
	$last_name=trim($_POST['last_name']??'');
	$email=trim($_POST['email']??'');
	$phone=trim($_POST['phone']??'');
	$designation=trim($_POST['designation']??'');
	$institution_address=trim($_POST['institution_address']??'');
	$specialization_ug=trim($_POST['specialization_ug']??'');
	$specialization_pg=trim($_POST['specialization_pg']??'');
	$teaching_experience_years=(int)($_POST['teaching_experience_years']??0);
	$subjects_taught=trim($_POST['subjects_taught']??'');
	$other_information=trim($_POST['other_information']??'');
	$roles = $_POST['roles'] ?? []; // Array of role NAMES from UI
	$status=trim($_POST['status']??'Active');
	
	$errors=[]; 
	if($id<=0)$errors[]='Invalid ID.'; 
	if($staff_code==='')$errors[]='Staff Code required.'; 
	if($first_name==='')$errors[]='First name required.'; 
	if($email===''||!filter_var($email,FILTER_VALIDATE_EMAIL))$errors[]='Valid email required.'; 
	if(empty($roles) || !is_array($roles))$errors[]='At least one role is required.'; 
	if(!in_array($status,['Active','Inactive']))$errors[]='Invalid status.'; 
	
	if($errors){ echo json_encode(['status'=>'error','message'=>$errors]); exit; }
	
	$before=null; 
	try{ 
		$b=$pdo->prepare('SELECT s.*, GROUP_CONCAT(sr.role_id) as role_ids FROM staff s LEFT JOIN staff_roles sr ON s.staff_id = sr.staff_id WHERE s.staff_id=? GROUP BY s.staff_id'); 
		$b->execute([$id]); 
		$before=$b->fetch(PDO::FETCH_ASSOC);
	}catch(Throwable $e){}
	
	$pdo->beginTransaction();
	
	// Normalize: manual name overrides college_id
	$collegeIdToStore = $external_college_name!=='' ? null : ($college_id?:null);

	// Update staff record (handle optional external_college_name column)
	$hasExternal = false;
	try{ $chk=$pdo->query("SHOW COLUMNS FROM staff LIKE 'external_college_name'"); $hasExternal = $chk && $chk->rowCount()>0; }catch(Throwable $e){ $hasExternal=false; }
	$cols = [];
	try{ $cols = $pdo->query("SHOW COLUMNS FROM staff")->fetchAll(PDO::FETCH_COLUMN,0);}catch(Throwable $e){ $cols=[]; }
	$hasProfile = in_array('designation',$cols);
	if($hasExternal){
		if($hasProfile){
			$stmt=$pdo->prepare('UPDATE staff SET college_id=?, external_college_name=?, staff_code=?, first_name=?, last_name=?, email=?, phone=?, designation=?, institution_address=?, specialization_ug=?, specialization_pg=?, teaching_experience_years=?, subjects_taught=?, other_information=?, status=? WHERE staff_id=?');
			$stmt->execute([$collegeIdToStore,$external_college_name?:null,$staff_code,$first_name,$last_name,$email,$phone,$designation?:null,$institution_address?:null,$specialization_ug?:null,$specialization_pg?:null,$teaching_experience_years?:null,$subjects_taught?:null,$other_information?:null,$status,$id]);
		}else{
			$stmt=$pdo->prepare('UPDATE staff SET college_id=?, external_college_name=?, staff_code=?, first_name=?, last_name=?, email=?, phone=?, status=? WHERE staff_id=?');
			$stmt->execute([$collegeIdToStore,$external_college_name?:null,$staff_code,$first_name,$last_name,$email,$phone,$status,$id]);
		}
	}else{
		if($hasProfile){
			$stmt=$pdo->prepare('UPDATE staff SET college_id=?, staff_code=?, first_name=?, last_name=?, email=?, phone=?, designation=?, institution_address=?, specialization_ug=?, specialization_pg=?, teaching_experience_years=?, subjects_taught=?, other_information=?, status=? WHERE staff_id=?');
			$stmt->execute([$collegeIdToStore,$staff_code,$first_name,$last_name,$email,$phone,$designation?:null,$institution_address?:null,$specialization_ug?:null,$specialization_pg?:null,$teaching_experience_years?:null,$subjects_taught?:null,$other_information?:null,$status,$id]);
		}else{
			$stmt=$pdo->prepare('UPDATE staff SET college_id=?, staff_code=?, first_name=?, last_name=?, email=?, phone=?, status=? WHERE staff_id=?');
			$stmt->execute([$collegeIdToStore,$staff_code,$first_name,$last_name,$email,$phone,$status,$id]);
		}
	}
	
	// Update staff roles - delete existing and insert new mapping via roles table (FK: staff_roles.role_id -> roles.id)
	$pdo->prepare('DELETE FROM staff_roles WHERE staff_id = ?')->execute([$id]);
	$selRoleId = $pdo->prepare('SELECT id FROM roles WHERE name = ? LIMIT 1');
	$insStaffRole = $pdo->prepare('INSERT INTO staff_roles (staff_id, role_id) VALUES (?, ?)');
	$inserted = 0;
	foreach($roles as $role_name) {
		$role_name = trim((string)$role_name);
		if($role_name==='') continue;
		$selRoleId->execute([$role_name]);
		$role_id = (int)$selRoleId->fetchColumn();
		if($role_id>0){
			$insStaffRole->execute([$id, $role_id]);
			$inserted++;
		} else {
			throw new Exception('Role not found in roles table: ' . $role_name);
		}
	}
	if($inserted===0){ throw new Exception('No valid roles selected.'); }
	
	$pdo->commit();
	
	write_audit_log($pdo, ['module'=>'People','action'=>'update','entity_table'=>'staff','entity_id'=>$id,'before_data'=>$before,'after_data'=>compact('college_id','external_college_name','staff_code','first_name','last_name','email','phone','designation','institution_address','specialization_ug','specialization_pg','teaching_experience_years','subjects_taught','other_information','roles','status'),'message'=>'Staff updated with roles']);
	echo json_encode(['status'=>'success','message'=>'Staff updated successfully.']);
} catch (Throwable $e){ 
	if($pdo->inTransaction()) $pdo->rollBack();
	http_response_code(500); 
	echo json_encode(['status'=>'error','message'=>$e->getMessage()]); 
}
?>


