<?php
// includes/auth.php
declare(strict_types=1);
require_once __DIR__.'/../config/db.php';
require_once __DIR__.'/csrf.php';

function sanitize_email(string $email): string {
  return filter_var(trim($email), FILTER_SANITIZE_EMAIL) ?: '';
}

function auth_login(string $email, string $password): bool {
  global $pdo;
  $email = sanitize_email($email);
  $stmt = $pdo->prepare("SELECT id, name, email, password, role, status FROM users WHERE email = ? LIMIT 1");
  $stmt->execute([$email]);
  $user = $stmt->fetch();

  if (!$user || $user['status'] !== 'active') return false;
  if (!password_verify($password, $user['password'])) return false;

  session_regenerate_id(true);
  $_SESSION['user'] = [
    'id'    => (int)$user['id'],
    'name'  => $user['name'],
    'email' => $user['email'],
    'role'  => $user['role'],
  ];
  return true;
}

function auth_logout(): void {
  $_SESSION = [];
  if (ini_get('session.use_cookies')) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time()-42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
  }
  session_destroy();
}

function current_user(): ?array {
  return $_SESSION['user'] ?? null;
}

function require_login(): void {
  if (!current_user()) {
    header('Location: /ldp/public/index.php?msg=login_required');
    exit;
  }
}

function require_role(string ...$roles): void {
  require_login();
  $user = current_user();
  if (!in_array($user['role'], $roles, true)) {
    http_response_code(403);
    exit('Forbidden');
  }
}
