<?php
declare(strict_types=1);

/**
 * ERP SESSION GATE
 * - Only logged-in users may view the SPA (index.html)
 * - If not logged in, redirect to /erp/login.php
 */

$https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443);
ini_set('session.use_strict_mode', '1');
ini_set('session.cookie_httponly', '1');
ini_set('session.cookie_secure', $https ? '1' : '0');

session_set_cookie_params([
  'lifetime' => 0,
  'path' => '/erp',
  'domain' => '',
  'secure' => $https,
  'httponly' => true,
  'samesite' => 'Strict',
]);
session_start();

if (empty($_SESSION['erp_user'])) {
  header("Location: /erp/login.php");
  exit;
}

// Serve the existing SPA file
$spa = __DIR__ . "/index.html";
if (!is_file($spa)) {
  http_response_code(500);
  header("Content-Type: text/plain; charset=utf-8");
  echo "index.html not found in /erp/.";
  exit;
}

header("Content-Type: text/html; charset=utf-8");
readfile($spa);
