<?php
declare(strict_types=1);
require_once __DIR__ . '/connect.php';
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') { header('Allow: POST'); reply(405,['status'=>'error','message'=>'Use POST.']); }
require_once __DIR__.'/../../shared/lib/system_settings.php';
if(!platform_settings()['registration_open'])reply(403,['status'=>'error','message'=>'Student registration is currently closed. Contact university administration.']);
start_auth_session();
$token=is_string($_POST['csrf_token']??null)?$_POST['csrf_token']:'';
if (!hash_equals($_SESSION['csrf_token'],$token)) reply(403,['status'=>'error','message'=>'Your registration form expired. Refresh the page and try again.']);
rate_limit('student-register-ip',client_ip(),8,3600);
$name=trim((string)($_POST['full_name']??''));$email=strtolower(trim((string)($_POST['email']??'')));
$studentNo=strtoupper(trim((string)($_POST['student_number']??'')));$identityType=(string)($_POST['identity_type']??'nrc');
$identity=trim((string)($_POST['identity_number']??''));$year=filter_var($_POST['year_of_study']??null,FILTER_VALIDATE_INT);
$department=filter_var($_POST['department_id']??null,FILTER_VALIDATE_INT);$campus=filter_var($_POST['campus_id']??null,FILTER_VALIDATE_INT);
if($name===''||mb_strlen($name)>150||!filter_var($email,FILTER_VALIDATE_EMAIL)||!preg_match('/^[A-Z0-9\/\-]{5,20}$/',$studentNo)||!in_array($year,[1,2,3,4],true)||!in_array($identityType,['nrc','passport'],true)||!$department||!$campus) reply(422,['status'=>'error','message'=>'Check the required fields and use the student number format RVU/2024/00123.']);
if($identityType==='nrc'&&!preg_match('/^\d{6}\/\d{2}\/\d$/',$identity)) reply(422,['status'=>'error','message'=>'Enter an NRC in the format 157486/79/1.']);
if($identityType==='passport'&&!preg_match('/^[A-Za-z0-9]{6,20}$/',$identity)) reply(422,['status'=>'error','message'=>'Enter a valid passport number (6–20 letters or digits).']);
$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 picture 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 profile picture.']);
$photoBytes=file_get_contents($photo['tmp_name']);if($photoBytes===false) reply(422,['status'=>'error','message'=>'The profile picture could not be read.']);
$check=db()->prepare('SELECT id FROM departments WHERE id=? AND is_active=1');$check->execute([$department]);if(!$check->fetch()) reply(422,['status'=>'error','message'=>'Select an active department.']);
$check=db()->prepare('SELECT id FROM campuses WHERE id=? AND is_active=1');$check->execute([$campus]);if(!$check->fetch()) reply(422,['status'=>'error','message'=>'Select an active campus.']);
// Requested first-login credential rule. Accounts stay inactive until the address is verified.
$digits=preg_replace('/\D/','',$identity);$seed=$identityType==='nrc'?substr($digits,0,6):substr($identity,0,6);
if(strlen($seed)<6) reply(422,['status'=>'error','message'=>'The identity number does not contain six usable characters.']);
$password=$seed.'@#';$passwordHash=password_hash($password,PASSWORD_DEFAULT);$verifyToken=bin2hex(random_bytes(32));$tokenHash=hash('sha256',$verifyToken);
try {
 db()->beginTransaction();
 $db=db();
 $db->prepare("INSERT INTO users(username,full_name,email,password_hash,role,is_active) VALUES(?,?,?, ?,'student',0)")->execute([$studentNo,$name,$email,$passwordHash]);$userId=$db->lastInsertId();
 $db->prepare("INSERT INTO students(user_id,student_number,identity_number,identity_type,department_id,campus_id,year_of_study,status,enrollment_date) VALUES(?,?,?,?,?,?,?,'inactive',UTC_DATE())")->execute([$userId,$studentNo,$identity,$identityType,$department,$campus,$year]);
 $db->prepare('INSERT INTO user_profile_pictures(user_id,image_data,mime_type) VALUES(?,?,?)')->execute([$userId,$photoBytes,$mime]);
 $db->prepare('INSERT INTO student_email_verifications(user_id,token_hash,expires_at) VALUES(?,?,DATE_ADD(UTC_TIMESTAMP(),INTERVAL 24 HOUR))')->execute([$userId,$tokenHash]);
 db()->commit();
} catch(Throwable $e) { if(db()->inTransaction()) db()->rollBack(); if($e instanceof mysqli_sql_exception && (int)$e->getCode()===1062) reply(409,['status'=>'error','message'=>'That student number, email or identity number is already registered.']); throw $e; }
$verifyUrl=rtrim(env_value('APP_URL','http://localhost'),'/').app_path().'/authentication/api/verify_email.php?token='.rawurlencode($verifyToken);
$subject='Rockview University SLPS account verification';
$body="Hello $name,\n\nYour Student Learning Practical System account has been created.\nStudent number: $studentNo\nInitial password: $password\n\nVerify your email within 24 hours: $verifyUrl\n\nFor security, sign in after verification and change this initial password as soon as password change is available in your account settings.\n";
$sent=send_system_mail($email,$subject,$body);
if(!$sent){ reply(202,['status'=>'pending_email','message'=>'Your registration is saved, but the system could not send the verification email. Ask the system administrator to configure outbound email and resend verification.']); }
reply(201,['status'=>'success','message'=>'Account created. Check your email for the initial password and verification link.']);
