<?php
/**
 * config.php
 *
 * Bootstraps environment, secure session, PDO. Reads secrets from a
 * .osce_env file located OUTSIDE the webroot. See env_loader.php.
 */

require_once __DIR__ . '/env_loader.php';

osce_load_env();

// -------- First-run redirect --------
// If no .osce_env exists and DB credentials are not provided via real env vars,
// kick the user to the setup wizard. The wizard handles its own bootstrap.
$script = basename($_SERVER['SCRIPT_NAME'] ?? '');
$unconfigured = !osce_env_present() && (osce_env('DB_NAME', '') === '' || osce_env('DB_USER', '') === '');
if ($unconfigured && !in_array($script, ['setup.php'], true)) {
    if (!headers_sent()) {
        header('Location: setup.php');
        exit;
    }
}

$appEnv   = osce_env('APP_ENV', 'production');
$appDebug = (int) osce_env('APP_DEBUG', 0) === 1;

// ---------------- Timezone (PHP + MySQL aligned) ----------------
$tz = osce_env('APP_TIMEZONE', 'Asia/Dubai');
@date_default_timezone_set($tz);

if ($appDebug) {
    ini_set('display_errors', '1');
    error_reporting(E_ALL);
} else {
    ini_set('display_errors', '0');
    error_reporting(E_ALL);
}
ini_set('log_errors', '1');

// ---------------- Security headers (best effort, before any output) ----------------
if (!headers_sent()) {
    header('X-Content-Type-Options: nosniff');
    header('X-Frame-Options: SAMEORIGIN');
    header('Referrer-Policy: strict-origin-when-cross-origin');
    header('Permissions-Policy: geolocation=(), microphone=(self), camera=(self)');
    // Strict-Transport-Security only meaningful over HTTPS.
    if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
        header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
    }
    // Modest CSP - allows inline styles/scripts because the legacy pages use them.
    // Tighten later by extracting inline JS into /assets/js/.
    header("Content-Security-Policy: default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; media-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'self'");
}

// ---------------- Secure session ----------------
if (session_status() === PHP_SESSION_NONE) {
    $secureFlag = ((int) osce_env('SESSION_SECURE', 1)) === 1;
    $sameSite   = osce_env('SESSION_SAMESITE', 'Lax');

    session_set_cookie_params([
        'lifetime' => 0,
        'path'     => '/',
        'domain'   => '',
        'secure'   => $secureFlag,
        'httponly' => true,
        'samesite' => $sameSite,
    ]);
    session_name('OSCESESSID');
    session_start();
}

// ---------------- Database ----------------
$dbHost = osce_env('DB_HOST', 'localhost');
$dbName = osce_env('DB_NAME', '');
$dbUser = osce_env('DB_USER', '');
$dbPass = osce_env('DB_PASS', '');

if ($dbName === '' || $dbUser === '') {
    http_response_code(500);
    error_log('OSCE Nexus: missing DB configuration in .osce_env');
    die('Application is not configured. Please contact the administrator.');
}

try {
    $pdo = new PDO(
        'mysql:host=' . $dbHost . ';dbname=' . $dbName . ';charset=utf8mb4',
        $dbUser,
        $dbPass,
        [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ]
    );
    // Force MySQL to PHP's timezone so date()/NOW()/TIMESTAMPDIFF all agree.
    try {
        $offset = (new DateTime('now'))->format('P'); // e.g. '+04:00'
        $pdo->exec("SET time_zone = '$offset'");
    } catch (Throwable $ignore) {}
} catch (Throwable $e) {
    error_log('OSCE Nexus DB connect failed: ' . $e->getMessage());
    http_response_code(500);
    if ($appDebug) {
        die('DB connect failed: ' . htmlspecialchars($e->getMessage()));
    }
    die('Service temporarily unavailable. Please try again later.');
}

// ---------------- Library autoloads ----------------
require_once __DIR__ . '/lib/csrf.php';
require_once __DIR__ . '/lib/audit.php';
require_once __DIR__ . '/lib/ratelimit.php';
require_once __DIR__ . '/lib/validation.php';
require_once __DIR__ . '/lib/perms.php';
require_once __DIR__ . '/lib/barcode.php';
