
­­­­­­­­­­­­­­­­­­
<!DOCTYPE html>
<html>
<?php
declare(strict_types=1);

function auth_user(PDO $pdo): ?array {
  $id = $_SESSION['user_id'] ?? null;
  if (!$id) return null;
  static $cache = null;
  if ($cache && (int)$cache['id'] === (int)$id) return $cache;

  $st = $pdo->prepare("SELECT u.*, r.code AS role_code, r.name_en AS role_name_en, r.name_ar AS role_name_ar,
                              b.name_en AS branch_name_en, b.name_ar AS branch_name_ar
                       FROM users u
                       JOIN roles r ON r.id=u.role_id
                       LEFT JOIN branches b ON b.id=u.branch_id
                       WHERE u.id=? AND u.is_active=1");
  $st->execute([$id]);
  $u = $st->fetch();
  $cache = $u ?: null;
  return $cache;
}

function require_login(PDO $pdo, array $config): array {
  $u = auth_user($pdo);
  if (!$u) {
    redirect(base_url($config, '/index.php?r=auth/login'));
  }
  return $u;
}

function login(PDO $pdo, string $email, string $password): bool {
  $st = $pdo->prepare("SELECT * FROM users WHERE email=? AND is_active=1");
  $st->execute([$email]);
  $u = $st->fetch();
  if (!$u) return false;
  if (!password_verify($password, $u['password_hash'])) return false;
  $_SESSION['user_id'] = $u['id'];
  return true;
}

function logout(): void {
  session_destroy();
}
