<?php
class Auth {
 private Database $db;
 function __construct(Database $db){$this->db=$db;}
 function login($email,$password){
  $u=$this->db->one('SELECT * FROM users WHERE email=? AND deleted_at IS NULL LIMIT 1',[$email]);
  if(!$u||!password_verify($password,$u['password_hash'])||$u['status']!=='active')return false;
  session_regenerate_id(true); $_SESSION['user']=$u;
  $this->db->exec('UPDATE users SET last_seen_at=NOW() WHERE id=?',[$u['id']]);
  $this->db->exec('INSERT INTO sessions(user_id,session_hash,ip_hash,user_agent,last_seen_at) VALUES(?,?,?,?,NOW())',[$u['id'],hash('sha256',session_id()),hash('sha256',$_SERVER['REMOTE_ADDR']??''),substr($_SERVER['HTTP_USER_AGENT']??'',0,500)]);
  return true;
 }
 function refresh(){if(!empty($_SESSION['user']['id'])){$u=$this->db->one('SELECT * FROM users WHERE id=?',[$_SESSION['user']['id']]);if($u)$_SESSION['user']=$u;}}
 function logout(){unset($_SESSION['user']);session_regenerate_id(true);}
}
