<?php
// Authentication + Authorization (RBAC)

function auth_user(): ?array {
  if (!isset($_SESSION['uid'])) return null;
  $u = db_one("SELECT id,name,email,role,is_active FROM users WHERE id=? LIMIT 1", [intval($_SESSION['uid'])]);
  if (!$u) return null;
  if (intval($u['is_active']) !== 1) return null;
  return $u;
}

function auth_require(): void {
  if (!auth_user()) {
    redirect(url('/login.php'));
  }
}

function auth_attempt(string $email, string $password): bool {
  $u = db_one("SELECT * FROM users WHERE email=? LIMIT 1", [$email]);
  if (!$u) return false;
  if (intval($u['is_active']) !== 1) return false;
  if (!password_verify($password, (string)$u['password_hash'])) return false;

  $_SESSION['uid'] = intval($u['id']);
  $_SESSION['role'] = (string)$u['role'];
  unset($_SESSION['perm_cache']);
  return true;
}

function auth_logout(): void {
  unset($_SESSION['uid'], $_SESSION['role'], $_SESSION['perm_cache']);
}

function auth_role(): string {
  return (string)($_SESSION['role'] ?? 'viewer');
}

function auth_is_admin(): bool {
  return auth_role() === 'admin';
}

/**
 * Check permission for current user.
 * Uses role_permissions table. Admin is always allowed.
 */
function auth_can(string $perm_key): bool {
  if (auth_is_admin()) return true;

  $role = auth_role();
  if ($role === '') return false;

  // cache per role in session
  if (!isset($_SESSION['perm_cache']) || !is_array($_SESSION['perm_cache']) || ($_SESSION['perm_cache_role'] ?? '') !== $role) {
    $rows = db_all("SELECT perm_key, allowed FROM role_permissions WHERE role=?", [$role]);
    $map = [];
    foreach ($rows as $r) $map[(string)$r['perm_key']] = intval($r['allowed']) === 1;
    $_SESSION['perm_cache'] = $map;
    $_SESSION['perm_cache_role'] = $role;
  }

  $map = $_SESSION['perm_cache'];
  return isset($map[$perm_key]) ? (bool)$map[$perm_key] : false;
}

function require_perm(string $perm_key): void {
  if (!auth_can($perm_key)) {
    http_response_code(403);
    echo "<h1 style='font-family:Tahoma,Arial,sans-serif'>403 Forbidden</h1>";
    echo "<p style='font-family:Tahoma,Arial,sans-serif'>ليس لديك صلاحية: <b>" . htmlspecialchars($perm_key, ENT_QUOTES, 'UTF-8') . "</b></p>";
    exit;
  }
}

// Backward compatibility
function auth_can_manage_users(): bool { return auth_can('manage_users'); }
function auth_can_delete(): bool { return auth_can('admin_only_delete'); }

// Backward-compatible helper (some pages call can())
if (!function_exists('can')) {
  function can($perm_key) {
    return auth_can($perm_key);
  }
}
