<?php
declare(strict_types=1);

require_once __DIR__ . '/db.php';

function start_session(): void {
  if (session_status() === PHP_SESSION_NONE) {
    // cookies seguras (en local igual funciona)
    session_start();
  }
}

function has_role(string $role): bool {
  $roles = $_SESSION['roles'] ?? [];
  return in_array($role, $roles, true);
}

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

function login(string $identifier, string $password): bool {
  $pdo = db();

  // identifier puede ser username o CI
  $stmt = $pdo->prepare(
    "SELECT id, username, ci, password_hash, nombres, apellidos, tipo, activo
     FROM usuarios
     WHERE (username = ? OR ci = ?)
     LIMIT 1"
  );
  $stmt->execute([$identifier, $identifier]);
  $user = $stmt->fetch();

  if (!$user) return false;
  if ((int)$user['activo'] !== 1) return false;

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

  // cargar roles
  $r = $pdo->prepare(
    "SELECT r.nombre
     FROM usuario_roles ur
     JOIN roles r ON r.id = ur.rol_id
     WHERE ur.usuario_id = ?"
  );
  $r->execute([(int)$user['id']]);
  $roles = array_map(fn($x) => $x['nombre'], $r->fetchAll());

  // sesión
  start_session();
  session_regenerate_id(true);

  $_SESSION['uid'] = (int)$user['id'];
  $_SESSION['username'] = (string)$user['username'];
  $_SESSION['ci'] = $user['ci'] ?? null;
  $_SESSION['tipo'] = $user['tipo'] ?? null;
  $_SESSION['roles'] = $roles;

  // ultimo login
  $pdo->prepare("UPDATE usuarios SET ultimo_login = NOW() WHERE id=?")->execute([(int)$user['id']]);

  return true;
}

function logout(): void {
  start_session();
  $_SESSION = [];

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