<?php
declare(strict_types=1);
require_once __DIR__.'/../../authentication/api/connect.php';$u=require_auth();$id=(int)$u['id'];
try{
 $action=$_GET['action']??'view';$method=$_SERVER['REQUEST_METHOD']??'GET';
 if($method==='GET'&&$action==='photo'){$q=db()->prepare('SELECT image_data,mime_type FROM user_profile_pictures WHERE user_id=?');$q->execute([$id]);$p=$q->fetch();if(!$p)reply(404,['message'=>'No profile photo.']);header('Content-Type: '.$p['mime_type']);header('X-Content-Type-Options: nosniff');header('Cache-Control: private, no-store');echo $p['image_data'];exit;}
 db()->prepare('INSERT IGNORE INTO user_profile_details(user_id) VALUES (?)')->execute([$id]);
 if($method==='GET'){
  $q=db()->prepare('SELECT u.id,u.username,u.full_name,u.email,u.role,u.created_at,u.last_login,d.preferred_name,d.phone,d.country,d.city,d.bio,d.revision,EXISTS(SELECT 1 FROM user_profile_pictures p WHERE p.user_id=u.id) AS has_photo FROM users u JOIN user_profile_details d ON d.user_id=u.id WHERE u.id=?');$q->execute([$id]);$profile=$q->fetch();$academic=[];
  if($u['role']==='student'){$q=db()->prepare('SELECT s.student_number,s.year_of_study,s.status,d.department_name,c.campus_name FROM students s JOIN departments d ON d.id=s.department_id JOIN campuses c ON c.id=s.campus_id WHERE s.user_id=?');$q->execute([$id]);$academic=$q->fetch()?:[];}
  elseif($u['role']==='hod'){$q=db()->prepare('SELECT d.department_name,c.campus_name FROM hod_assignments h JOIN departments d ON d.id=h.department_id JOIN campuses c ON c.id=h.campus_id WHERE h.user_id=?');$q->execute([$id]);$academic=$q->fetch()?:[];}
  elseif($u['role']==='staff'){$q=db()->prepare('SELECT s.staff_number,s.designation,COALESCE(NULLIF(s.department,\'\'),\'All departments\') AS department_name,COALESCE(c.campus_name,\'All campuses\') AS campus_name FROM staff s LEFT JOIN campuses c ON c.id=s.campus_id WHERE s.user_id=?');$q->execute([$id]);$academic=$q->fetch()?:[];}
  else{$q=db()->prepare('SELECT c.campus_name FROM admins a LEFT JOIN campuses c ON c.id=a.campus_id WHERE a.user_id=?');$q->execute([$id]);$academic=$q->fetch()?:[];}
  reply(200,['profile'=>$profile,'academic'=>$academic]);
 }
 if($method!=='POST')reply(405,['message'=>'Use GET or POST.']);
 if($action==='photo'){
  if(!hash_equals($_SESSION['csrf_token']??'',$_SERVER['HTTP_X_CSRF_TOKEN']??''))reply(403,['message'=>'Refresh the page and try again.']);$f=$_FILES['photo']??null;if(!$f||$f['error']!==UPLOAD_ERR_OK||$f['size']<1||$f['size']>5242880)throw new InvalidArgumentException('Choose a JPG, PNG or WebP photo up to 5 MB.');$mime=(new finfo(FILEINFO_MIME_TYPE))->file($f['tmp_name']);$size=@getimagesize($f['tmp_name']);if(!in_array($mime,['image/jpeg','image/png','image/webp'],true)||!$size||$size[0]>4096||$size[1]>4096)throw new InvalidArgumentException('Use a valid photo no larger than 4096 pixels on either side.');$q=db()->prepare('INSERT INTO user_profile_pictures(user_id,image_data,mime_type) VALUES (?,?,?) ON DUPLICATE KEY UPDATE image_data=VALUES(image_data),mime_type=VALUES(mime_type),updated_at=CURRENT_TIMESTAMP');$q->execute([$id,file_get_contents($f['tmp_name']),$mime]);reply(200,['message'=>'Profile photo updated.']);
 }
 $data=post_data(15000);
 if($action==='save'){
  $name=text_field($data,'full_name',150);$email=text_field($data,'email',254);if(!$name||in_array(strtolower($name),['null','undefined'],true)||!filter_var($email,FILTER_VALIDATE_EMAIL))throw new InvalidArgumentException('Enter your full name and a valid email address.');$details=[];foreach(['preferred_name'=>100,'phone'=>40,'country'=>100,'city'=>100,'bio'=>1000] as $field=>$length)$details[$field]=text_field($data,$field,$length);
  db()->beginTransaction();try{$q=db()->prepare('SELECT u.email,u.password_hash,d.revision FROM users u JOIN user_profile_details d ON d.user_id=u.id WHERE u.id=? FOR UPDATE');$q->execute([$id]);$old=$q->fetch();if((int)($data['revision']??0)!==(int)$old['revision']){db()->rollBack();reply(409,['message'=>'Your profile changed elsewhere. Reload it before saving.']);}
   if(strcasecmp($email,$old['email'])!==0&&!password_verify((string)($data['current_password']??''),$old['password_hash'])){db()->rollBack();reply(403,['message'=>'Enter your current password to change your email.']);}
   $q=db()->prepare('SELECT id FROM users WHERE (email=? OR username=?) AND id<>?');$q->execute([$email,$email,$id]);if($q->fetch()){db()->rollBack();reply(409,['message'=>'That email is already associated with another account.']);}
   db()->prepare('UPDATE users SET full_name=?,email=? WHERE id=?')->execute([$name,$email,$id]);db()->prepare('UPDATE user_profile_details SET preferred_name=?,phone=?,country=?,city=?,bio=?,revision=revision+1 WHERE user_id=?')->execute(array_merge(array_values($details),[$id]));if($u['role']==='student'&&strcasecmp($email,$old['email'])!==0)db()->prepare('UPDATE students SET email_verified_at=NULL WHERE user_id=?')->execute([$id]);db()->commit();
  }catch(Throwable $e){if(db()->inTransaction())db()->rollBack();throw $e;}reply(200,['message'=>'Your profile has been updated.','revision'=>(int)$old['revision']+1]);
 }
 if($action==='password'){
  $current=(string)($data['current_password']??'');$next=(string)($data['new_password']??'');if(strlen($next)<12||strlen($next)>128||$next!==($data['confirm_password']??''))throw new InvalidArgumentException('Use a matching new password of 12–128 characters.');
  db()->beginTransaction();try{$q=db()->prepare('SELECT password_hash FROM users WHERE id=? FOR UPDATE');$q->execute([$id]);$old=$q->fetchColumn();if(!password_verify($current,$old)){db()->rollBack();reply(403,['message'=>'Current password is incorrect.']);}if(password_verify($next,$old))throw new InvalidArgumentException('Choose a different new password.');$hash=password_hash($next,PASSWORD_DEFAULT);db()->prepare('UPDATE users SET password_hash=? WHERE id=?')->execute([$hash,$id]);db()->commit();}catch(Throwable $e){if(db()->inTransaction())db()->rollBack();throw $e;}session_regenerate_id(true);$_SESSION['password_fingerprint']=hash('sha256',$hash);reply(200,['message'=>'Password updated. Other sessions will need to sign in again.']);
 }
 reply(405,['message'=>'Unsupported action.']);
}catch(InvalidArgumentException $e){reply(422,['message'=>$e->getMessage()]);}catch(Throwable $e){if($e instanceof mysqli_sql_exception&&(int)$e->getCode()===1062)reply(409,['message'=>'That email is already in use.']);error_log('SLPS profile: '.get_class($e).' '.$e->getCode());reply(503,['message'=>'Profile is unavailable. Check the profile migration and database access.']);}
