<?php
// Prevent double bootstrapping
if (!defined('ADMIN_BOOTSTRAPPED')) {
    define('ADMIN_BOOTSTRAPPED', true);

    // Debug (turn off in production)
    if (!defined('APP_DEBUG')) { define('APP_DEBUG', true); }
    error_reporting(APP_DEBUG ? E_ALL : 0);
    ini_set('display_errors', APP_DEBUG ? '1' : '0');

    // Safe session start
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }

    // Load core
    require_once __DIR__ . '/../db.php';
    require_once __DIR__ . '/../auth_guard.php';
    require_admin();

    // Base URL detection (or use config['base_url'])
    $config  = require __DIR__ . '/../config.php';
    $cfgBase = isset($config['base_url']) ? trim($config['base_url']) : '';

    if ($cfgBase !== '') {
        $BASE_URL = rtrim($cfgBase, '/');
    } else {
        $projectRoot = realpath(__DIR__ . '/..');
        $docRoot     = realpath($_SERVER['DOCUMENT_ROOT'] ?? $projectRoot);
        $base        = str_replace('\\', '/', str_replace($docRoot, '', $projectRoot));
        if ($base === '' || $base[0] !== '/') { $base = '/' . ltrim($base, '/'); }
        $BASE_URL = rtrim($base, '/');
    }

    // Define url_for only once
    if (!function_exists('url_for')) {
        function url_for($path) {
            $base = $GLOBALS['BASE_URL'] ?? '';
            return rtrim($base, '/') . $path;
        }
    }
}
