<?php
function user(){ return isset($_SESSION['user'])?$_SESSION['user']:null; }
function login_user($email,$password){
    $row=db_one('SELECT id, name, email, password_hash, role, status FROM users WHERE email=? LIMIT 1',array(strtolower(trim($email))));
    if(!$row || $row['status']!=='active' || !password_verify($password,$row['password_hash'])) return false;
    unset($row['password_hash']); $_SESSION['user']=$row; db_exec('UPDATE users SET last_login_at=NOW() WHERE id=?',array($row['id'])); return true;
}
function logout_user(){ $_SESSION=array(); if(ini_get('session.use_cookies')){ $p=session_get_cookie_params(); setcookie(session_name(),'',time()-42000,$p['path'],$p['domain'],$p['secure'],$p['httponly']); } session_destroy(); }
function require_login($roles=array()){
    $u=user(); if(!$u){ flash('warning','Please sign in to continue.'); redirect('auth/login.php'); }
    if($roles && !in_array($u['role'],$roles,true)){ http_response_code(403); exit('Access denied'); }
}
