<?php
declare(strict_types=1);
function current_user(){ return $_SESSION['user'] ?? null; }
function require_login($role=null){
    if (empty($_SESSION['user'])){ header('Location: login.php'); exit; }
    if ($role && ($_SESSION['user']['role'] ?? '') !== $role){ header('Location: index.php'); exit; }
}
function load_users(): array {    
    // fix append issue in Python—they'll be written below correctly
    $users=[];
    if(file_exists(USERS_PATH)){
        if(($h=fopen(USERS_PATH,'r'))){
            $header=fgetcsv($h);
            while(($r=fgetcsv($h))!==false){ $users[]=array_combine($header,$r); }
            fclose($h);
        }
    }
    $hasAdmin=false; foreach($users as $u){ if(($u['role']??'')==='admin'){ $hasAdmin=true; break; } }
    if(!$hasAdmin){
        $users[]=['email'=>'admin@example.com','name'=>'Administrator','password_hash'=>'','role'=>'admin'];
        save_users($users);
    }
    return $users;
}
function save_users(array $users): bool {
    if(!file_exists(DATA_DIR)) @mkdir(DATA_DIR,0775,true);
    $h=fopen(USERS_PATH,'w');
    fputcsv($h,['email','name','password_hash','role']);
    foreach($users as $u){ fputcsv($h, [$u['email'],$u['name'],$u['password_hash'],$u['role']]); }
    fclose($h); return true;
}
function find_user($email){
    $users=load_users(); foreach($users as $u){ if(strtolower($u['email'])===strtolower($email)) return $u; } return null;
}
function register_student($name,$email,$password): bool {
    $email=trim(strtolower($email)); if(!filter_var($email, FILTER_VALIDATE_EMAIL)) return false;
    $users=load_users(); foreach($users as $u){ if(strtolower($u['email'])===$email) return false; }
    $hash=password_hash($password, PASSWORD_BCRYPT);
    $users[]=['email'=>$email,'name'=>$name,'password_hash'=>$hash,'role'=>'student'];
    return save_users($users);
}
function verify_login($email,$password){
    $u=find_user($email); if(!$u) return null;
    $role=$u['role'] ?? 'student'; $hash=$u['password_hash'] ?? '';
    if($role==='admin' && $hash===''){ if($password==='admin123'){ $_SESSION['user']=['email'=>$u['email'],'name'=>$u['name'],'role'=>'admin']; return $_SESSION['user']; } }
    if($hash!=='' && password_verify($password,$hash)){ $_SESSION['user']=['email'=>$u['email'],'name'=>$u['name'],'role'=>$role]; return $_SESSION['user']; }
    return null;
}
function logout(){ unset($_SESSION['user']); }
