<?php
// Single entry point for shared setup. Include this at the top of every script.
$https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
      || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https')
      || (($_SERVER['SERVER_PORT'] ?? '') == 443);
if (session_status() === PHP_SESSION_NONE) {
  ini_set('session.use_strict_mode', '1');   // reject attacker-supplied session ids
  session_set_cookie_params([
    'httponly' => true,
    'samesite' => 'Lax',
    'secure'   => $https,   // only send the session cookie over HTTPS
  ]);
  session_start();
}
error_reporting(E_ALL & ~E_DEPRECATED);
ini_set('display_errors', '0');   // never leak errors/paths to visitors (log-only)
// Composer / vendor autoloader (TCPDF for certificate PDFs). Optional — the
// certificate engine falls back to print-ready HTML if this is absent.
if (is_file(dirname(__DIR__) . '/vendor/autoload.php')) require dirname(__DIR__) . '/vendor/autoload.php';
require __DIR__ . '/db.php';
require __DIR__ . '/helpers.php';
require __DIR__ . '/icons.php';   // NTPPA icon system — icon() / icons_js() (single source of truth)
require __DIR__ . '/render.php';
require __DIR__ . '/certificates.php'; // Certificate generation and management
require __DIR__ . '/security.php'; // security monitor — event log, IP blocklist, alerts
require __DIR__ . '/partners.php'; // CMS-managed associate partners + slider
require __DIR__ . '/hosting.php';  // CMS-managed hosting plans + reseller handoff

// ─── Site timezone (Admin → Settings; default America/New_York — Tampa). ───
// try/catch: on a brand-new install the settings table may not exist yet.
try { $tz = trim((string) setting('timezone', '')); } catch (\Throwable $e) { $tz = ''; }
if ($tz === '' || !in_array($tz, timezone_identifiers_list(), true)) $tz = 'America/New_York';
date_default_timezone_set($tz);

// ─── HTTPS enforcement (Admin → Settings → "Force HTTPS"). ───
// Needs a valid certificate first (cPanel AutoSSL) — see DEPLOY-CPANEL.md.
// On: plain-http requests get a 301 (308 for POSTs, preserving the method)
// to the https:// URL, and secure responses carry an HSTS header.
try { $forceHttps = ((string) setting('force_https', '0') === '1'); } catch (\Throwable $e) { $forceHttps = false; }
if ($forceHttps && PHP_SAPI !== 'cli') {
  if ($https) {
    header('Strict-Transport-Security: max-age=15552000'); // 180 days
  } elseif (!empty($_SERVER['HTTP_HOST'])) {
    $code = in_array($_SERVER['REQUEST_METHOD'] ?? 'GET', ['GET', 'HEAD'], true) ? 301 : 308;
    header('Location: https://' . $_SERVER['HTTP_HOST'] . ($_SERVER['REQUEST_URI'] ?? '/'), true, $code);
    exit;
  }
}

// ─── Baseline security headers on every response (admin adds stricter ones). ───
security_headers(false);

// ─── Security monitor: enforce IP blocklist + flag malicious URL probes. ───
security_boot();
