<?php
/**
 * Savit Unified Platform — Common Bootstrap
 *
 * Every engine includes this file first. It:
 *  1. Loads the root .env
 *  2. Sets up error reporting, timezone, session
 *  3. Exposes a shared PDO factory via SavitDB
 *
 * Each engine then defines its own CONSTANTS (e.g. ANALYTICS_ROOT)
 * and registers its own autoloader on top of this.
 */
declare(strict_types=1);

// ── Platform root (Savit/) ──────────────────────────────────────────────────
if (!defined('SAVIT_ROOT')) {
    define('SAVIT_ROOT', dirname(__DIR__));
}

// ── Load .env ───────────────────────────────────────────────────────────────
_savit_load_env(SAVIT_ROOT . '/.env');

// ── Error reporting ─────────────────────────────────────────────────────────
if (filter_var($_ENV['APP_DEBUG'] ?? false, FILTER_VALIDATE_BOOL)) {
    ini_set('display_errors', '1');
    error_reporting(E_ALL);
} else {
    ini_set('display_errors', '0');
    error_reporting(0);
}

// ── Timezone ────────────────────────────────────────────────────────────────
date_default_timezone_set($_ENV['APP_TIMEZONE'] ?? 'UTC');

// ── Session (shared name, write-close to prevent locking) ───────────────────
if (PHP_SAPI !== 'cli') {
    session_name($_ENV['SESSION_NAME'] ?? 'savit_session');
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
        session_write_close();
    }
}

// ── Shared DB config helper ─────────────────────────────────────────────────
// Returns the DB config array sourced from .env (no engine-specific file needed)
function savit_db_config(): array
{
    return [
        'host'    => $_ENV['DB_HOST']    ?? '127.0.0.1',
        'port'    => (int)($_ENV['DB_PORT'] ?? 3306),
        'dbname'  => $_ENV['DB_NAME']    ?? 'savit_platform',
        'username'=> $_ENV['DB_USER']    ?? 'root',
        'password'=> $_ENV['DB_PASS']    ?? '',
        'charset' => $_ENV['DB_CHARSET'] ?? 'utf8mb4',
        'options' => [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ],
    ];
}

// ── Simple .env loader (no external deps) ──────────────────────────────────
function _savit_load_env(string $path): void
{
    if (!is_file($path)) {
        return;
    }
    $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line === '' || $line[0] === '#') {
            continue;
        }
        $parts = explode('=', $line, 2);
        if (count($parts) !== 2) {
            continue;
        }
        $key   = trim($parts[0]);
        $value = trim($parts[1]);
        // Strip surrounding quotes
        if (strlen($value) >= 2 &&
            (($value[0] === '"' && $value[-1] === '"') ||
             ($value[0] === "'" && $value[-1] === "'"))) {
            $value = substr($value, 1, -1);
        }
        $_ENV[$key] = $value;
        putenv($key . '=' . $value);
    }
}
