<?php
declare(strict_types=1);
require_once __DIR__ . '/connect.php';
$token=(string)($_GET['token']??'');if(!preg_match('/^[a-f0-9]{64}$/',$token)){http_response_code(400);echo 'Invalid verification link.';exit;}
$db=db();$db->beginTransaction();
try{$q=$db->prepare('SELECT id,user_id FROM student_email_verifications WHERE token_hash=? AND used_at IS NULL AND expires_at>UTC_TIMESTAMP() FOR UPDATE');$q->execute([hash('sha256',$token)]);$row=$q->fetch();if(!$row){$db->rollBack();http_response_code(410);echo 'This verification link has expired or was already used.';exit;}
$db->prepare('UPDATE student_email_verifications SET used_at=UTC_TIMESTAMP() WHERE id=?')->execute([$row['id']]);$db->prepare('UPDATE users SET is_active=1 WHERE id=?')->execute([$row['user_id']]);$db->prepare('UPDATE students SET status=\'active\',email_verified_at=UTC_TIMESTAMP() WHERE user_id=?')->execute([$row['user_id']]);$db->commit();
header('Location: '.app_path().'/authentication/views/login.php?verified=1',true,303);exit;}catch(Throwable $e){if($db->inTransaction())$db->rollBack();throw $e;}
