<?php
// includes/auth.php
require_once __DIR__ . '/db.php';
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

function csrf_token(): string {
  if (empty($_SESSION['csrf'])) {
    $_SESSION['csrf'] = bin2hex(random_bytes(16));
  }
  return $_SESSION['csrf'];
}

function csrf_check() {
  if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf'] ?? '';
    if (!$token || !hash_equals($_SESSION['csrf'] ?? '', $token)) {
      http_response_code(400);
      exit('CSRF inválido');
    }
  }
}

function find_user_by_email(string $email) {
  $st = pdo()->prepare('SELECT * FROM users WHERE email = ? LIMIT 1');
  $st->execute([$email]);
  return $st->fetch(PDO::FETCH_ASSOC);
}

function login(string $email, string $password): bool {
  $user = find_user_by_email($email);
  if (!$user) return false;

  if (!password_verify($password, $user['password_hash'])) return false;

  // Validar expiración del usuario si aplica
  if (!empty($user['expires_at'])) {
    $now = new DateTime();
    $expires = new DateTime($user['expires_at']);
    if ($expires < $now) {
      $_SESSION['login_error'] = 'Usuario caducado. Contacta al administrador.';
      return false;
    }
  }

  // Guardar datos esenciales en sesión con clave 'user_role'
  $_SESSION['uid'] = (int)$user['id'];
  $_SESSION['user_role'] = $user['role'];  // <- clave corregida aquí
  $_SESSION['email'] = $user['email'];

  return true;
}

function logout() {
  $_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() {
  if (empty($_SESSION['uid'])) return null;

  $st = pdo()->prepare('SELECT * FROM users WHERE id = ? LIMIT 1');
  $st->execute([$_SESSION['uid']]);
  return $st->fetch(PDO::FETCH_ASSOC);
}

function require_login() {
  if (empty($_SESSION['uid'])) {
    header('Location: /miportal_pro/public/login.php');
    exit;
  }
}

// Modificado para aceptar string o array de roles
function require_role(string|array $roles): void {
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }

    if (!isset($_SESSION['user_role'])) {
        http_response_code(403);
        exit('Acceso denegado: no autenticado');
    }

    $userRole = $_SESSION['user_role'];

    if (is_string($roles)) {
        $roles = [$roles];
    }

    if (!in_array($userRole, $roles, true)) {
        http_response_code(403);
        exit('Acceso denegado: rol insuficiente');
    }
}
