<?php
// =============================================================================
// Bootstrap — required by every admin page and AJAX endpoint
// =============================================================================

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/error_log.php';   // installs handlers before anything else
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/csrf.php';
require_once __DIR__ . '/auth.php';

// Session bootstrap — skip on CLI (cron) to avoid session-related warnings.
if (PHP_SAPI !== 'cli' && session_status() === PHP_SESSION_NONE) {
    session_name(PANEL_SESSION_NAME);
    $cookie_path = function_exists('panel_base_path') ? panel_base_path() : '/';
    $is_https    = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
    $proxy_https = ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https';
    session_set_cookie_params([
        'lifetime' => 0,
        'path'     => $cookie_path,
        'secure'   => $is_https || $proxy_https,
        'httponly' => true,
        'samesite' => 'Lax',
    ]);
    session_start();
}

if (PANEL_DEBUG) {
    error_reporting(E_ALL);
    ini_set('display_errors', '1');
} else {
    error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE);
    ini_set('display_errors', '0');
}

// Touch the DB once at boot so the schema + seed get applied on the very first
// request; subsequent calls are cached by the static $pdo. panel_db() also
// applies the panel's configured timezone the first time it runs, so both
// admin pages (via this bootstrap) AND the public webview endpoints (which
// skip bootstrap to keep X-Frame-Options sane for iframe previews) end up
// with consistent date() behavior.
panel_db();
