<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

/* ===== OBTENER URL ACTUAL ===== */
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
$link = $scheme . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

/* ===== PÁGINAS LIBRES ===== */
$public_pages = ['login.php', 'register.php'];

/* ===== SI NO ESTÁ LOGUEADO ===== */
if (!isset($_SESSION['userdata']) || !isset($_SESSION['userdata']['id'])) {
    foreach ($public_pages as $page) {
        if (strpos($link, $page) !== false) {
            return; // puede acceder
        }
    }
    redirect('login.php');
    exit;
}

/* ===== SI YA ESTÁ LOGUEADO Y VA A LOGIN ===== */
if (isset($_SESSION['userdata']['id'])) {
    foreach ($public_pages as $page) {
        if (strpos($link, $page) !== false) {
            redirect('index.php');
            exit;
        }
    }
}

/* ===== VALIDAR ROL EXISTENTE ===== */
if (!isset($_SESSION['userdata']['role'])) {
    // Sesión inválida o incompleta
    session_destroy();
    redirect('login.php');
    exit;
}

