<?php
declare(strict_types=1);

require_once __DIR__ . '/db.php'; // ← app_pdo(), json_ok(), json_err() vienen de aquí



function start_session(): void {
  if (session_status() === PHP_SESSION_NONE && !headers_sent()) {
    session_name('sa_sess');
    session_set_cookie_params([
      'lifetime' => 0,
      'path'     => '/',
      'secure'   => isset($_SERVER['HTTPS']),
      'httponly' => true,
      'samesite' => 'Lax',
    ]);
    session_start();
  } elseif (session_status() === PHP_SESSION_NONE) {
    session_start();
  }
}

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

function login_with_dni(string $dni, string $pass): bool {
  start_session();
  $pdo = app_pdo();
  $s   = $pdo->prepare(
    'SELECT id,dni,full_name,role,password_hash,is_active
     FROM users WHERE dni=? LIMIT 1'
  );
  $s->execute([$dni]);
  $u = $s->fetch();
  if (!$u || !(int)$u['is_active']) return false;
  if (!password_verify($pass, $u['password_hash'])) return false;
  $_SESSION['user'] = [
    'id'        => (int)$u['id'],
    'dni'       => $u['dni'],
    'full_name' => $u['full_name'],
    'role'      => $u['role'],
  ];
  session_regenerate_id(true);
  return true;
}

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

function require_login(): array {
  $u = current_user();
  if (!$u) {
    header('Location: /sistemaescolar/login.php');
    exit;
  }
  return $u;
}

function require_role(string $role): array {
  $u = require_login();
  if ($u['role'] !== $role) {
    header('Location: ' . redirect_by_role($u['role']));
    exit;
  }
  return $u;
}

function redirect_by_role(string $role): string {
  return match($role) {
    'ADMIN'   => '/sistemaescolar/admin/',
    'DOCENTE' => '/sistemaescolar/docente/',
    'ALUMNO'  => '/sistemaescolar/alumno/',
    default   => '/sistemaescolar/login.php',
  };
}

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

function csrf_verify(): void {
  $token = $_POST['csrf'] ?? ($_SERVER['HTTP_X_CSRF_TOKEN'] ?? '');
  if (!hash_equals(csrf_token(), $token)) {
    http_response_code(419);
    exit(json_encode(['ok' => false, 'msg' => 'Token CSRF inválido.']));
  }
}

function is_ajax(): bool {
  return ($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '') === 'XMLHttpRequest';
}

function set_flash(string $type, string $msg): void {
  start_session();
  $_SESSION['flash'] = ['type' => $type, 'msg' => $msg];
}

function get_flash(): ?array {
  start_session();
  $f = $_SESSION['flash'] ?? null;
  unset($_SESSION['flash']);
  return $f;
}

if (!function_exists('notif_create')) {



