<?php
ob_start();

// Ensure session is available globally across directories (root and /api/)
$cookieParams = session_get_cookie_params();
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/', // Global path
    'domain' => $_SERVER['HTTP_HOST'],
    'secure' => isset($_SERVER['HTTPS']),
    'httponly' => true,
    'samesite' => 'Lax'
]);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}



// Constants for roles
define('ROLE_SUPER_ADMIN', 'admin'); // Mantener 'admin' como super usuario por compatibilidad
define('ROLE_SHIP_ADMIN', 'sub-adm'); // Admin asignado a un buque
define('ROLE_USER', 'user'); // Usuario común

function checkLogin()
{
    if (!isset($_SESSION['user_id'])) {
        header("Location: index.php");
        exit();
    }
}

function isLoggedIn()
{
    return isset($_SESSION['user_id']);
}

function checkApiLogin()
{
    if (!isLoggedIn()) {
        header('Content-Type: application/json; charset=utf-8');
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'No autorizado']);
        exit;
    }
}

function refreshUserSessionShips($pdo = null)
{
    if (!isset($_SESSION['user_id']))
        return;

    if (!$pdo) {
        require_once 'config.php';
        $pdo = getDBConnection();
    }

    if (!$pdo)
        return;

    try {
        $stmt = $pdo->prepare("SELECT ship_id FROM user_ships WHERE user_id = :uid");
        $stmt->execute([':uid' => $_SESSION['user_id']]);
        $_SESSION['assigned_ships'] = $stmt->fetchAll(PDO::FETCH_COLUMN);
        unset($_SESSION['user_ships_updated']);
    } catch (Exception $e) {
        error_log("Error refreshing session ships: " . $e->getMessage());
    }
}

function hasShipAccess($targetShipId)
{
    if (!isset($_SESSION['role']))
        return false;

    // Force refresh if requested by another action
    if (isset($_SESSION['user_ships_updated'])) {
        refreshUserSessionShips();
    }

    // Super admin has access to everything
    if ($_SESSION['role'] === ROLE_SUPER_ADMIN)
        return true;

    // Others only to their assigned ships
    $assigned = $_SESSION['assigned_ships'] ?? [];
    return in_array($targetShipId, $assigned);
}

function canManageUsers()
{
    return isset($_SESSION['role']) &&
        ($_SESSION['role'] === ROLE_SUPER_ADMIN || $_SESSION['role'] === ROLE_SHIP_ADMIN);
}
