<?php
// /includes/session_staff.php
declare(strict_types=1);

// antes de session_start()
$cookieParams = session_get_cookie_params();
$path = "/lanchonete/public"; // ✅ deve cobrir /garcom, /cartao, /caixa, /balcao

session_set_cookie_params([
  'lifetime' => 0,
  'path' => $path,
  'domain' => $cookieParams['domain'] ?? '',
  'secure' => !empty($_SERVER['HTTPS']),
  'httponly' => true,
  'samesite' => 'Lax',
]);


if (session_status() !== PHP_SESSION_ACTIVE) {
  session_start();
}

if (!defined('APP_BASE')) {
  define('APP_BASE', '/lanchonete/public');
}
 // <<< ajuste se necessário

function staff_login_url(): string  { return APP_BASE . "/login.php"; }
function staff_logout_url(): string { return APP_BASE . "/logout.php"; }

function staff_role_perms(string $role): array {
  switch ($role) {
    case 'ADMIN':
      return ['balcao','garcom','cartao','caixa'];
    case 'GARCOM':
      return ['garcom'];
    case 'CAIXA':
      return ['caixa'];
    case 'BALCAO':
      return ['balcao','garcom'];
    default:
      return [];
  }
}


function staff_current(): ?array {
  return $_SESSION['staff'] ?? null;
}

function staff_is_logged(): bool {
  $s = staff_current();
  return is_array($s) && !empty($s['id']);
}

function staff_forbidden(): void {
  http_response_code(403);
  header("Content-Type: text/html; charset=utf-8");
  echo "<h1>403 - Acesso negado</h1>";
  echo "<p>Você não tem permissão para acessar este módulo.</p>";
  echo "<p><a href='".htmlspecialchars(staff_logout_url(), ENT_QUOTES, 'UTF-8')."'>Sair</a></p>";
  exit;
}

/**
 * require_staff('garcom'|'cartao'|'balcao'|'caixa')
 */
function require_staff(?string $module = null): void {
  if (!staff_is_logged()) {
    $next = $_SERVER['REQUEST_URI'] ?? '/';
    $url = staff_login_url() . "?next=" . rawurlencode($next);
    header("Location: " . $url);
    exit;
  }

  if ($module) {
    $s = staff_current();
    $role  = (string)($s['role'] ?? '');
    $perms = $s['perms'] ?? staff_role_perms($role);
    if (!is_array($perms) || !in_array($module, $perms, true)) {
      staff_forbidden();
    }
  }
}
