<?php
declare(strict_types=1);

/* ===============================
   CONFIG & BASE-PATH HELPERS
   =============================== */
$__cfg = @parse_ini_file(__DIR__ . '/../config.ini') ?: [];
$__base_override = '';
if (!empty($__cfg['base_path'])) {
    $__base_override = rtrim((string)$__cfg['base_path'], '/');
}

if (!function_exists('app_base_path')) {
    function app_base_path(): string {
        if (!empty($GLOBALS['__base_override'])) {
            return $GLOBALS['__base_override'] === '/' ? '' : $GLOBALS['__base_override'];
        }
        $script = $_SERVER['SCRIPT_NAME'] ?? '/';
        $dir = rtrim(str_replace('\\','/', dirname($script)), '/');
        if ($dir !== '' && $dir !== '/') return $dir;

        $appRootFs = dirname(__DIR__);
        $docRoot   = rtrim(str_replace('\\','/', $_SERVER['DOCUMENT_ROOT'] ?? ''), '/');
        $appRootFs = rtrim(str_replace('\\','/', realpath($appRootFs) ?: $appRootFs), '/');
        if ($docRoot && strncmp($appRootFs, $docRoot, strlen($docRoot)) === 0) {
            $base = substr($appRootFs, strlen($docRoot));
            $base = str_replace('\\','/',$base);
            return $base === '' ? '' : $base;
        }
        return '';
    }
}

if (!function_exists('url_for')) {
    function url_for(string $path): string { return app_base_path() . '/' . ltrim($path, '/'); }
}
if (!function_exists('redirect')) {
    function redirect(string $path, int $status = 302): void {
        header('Location: ' . url_for($path), true, $status);
        // ensure non-empty body for LiteSpeed quirks
        echo "<!doctype html><meta http-equiv='refresh' content='0;url=" . htmlspecialchars(url_for($path), ENT_QUOTES, 'UTF-8') . "'>";
        exit;
    }
}

/* ===============================
   GLOBAL CONFIG EXPORT + CONSTANTS
   =============================== */
$CONFIG = array_merge([
    'debug'            => false,
    'timezone'         => @date_default_timezone_get() ?: 'UTC',
    // DB
    'DB_MODE'          => 'sqlite',   // 'sqlite' or 'mysql'
    'DB_HOST'          => '127.0.0.1',
    'DB_NAME'          => '',
    'DB_USER'          => '',
    'DB_PASS'          => '',
    'DB_CHARSET'       => 'utf8mb4',
    // reCAPTCHA
    'RECAPTCHA_SITEKEY'=> '',
    'RECAPTCHA_SECRET' => '',
    // base_path may be present and handled above
], $__cfg);

if (!defined('APP_BASE_DIR'))  define('APP_BASE_DIR', realpath(dirname(__DIR__)));
if (!defined('APP_API_DIR'))   define('APP_API_DIR', realpath(APP_BASE_DIR . '/api') ?: (APP_BASE_DIR . '/api'));
if (!defined('APP_SQLITE_FILE')) {
    // IMPORTANT: admin + API share the SAME SQLite DB file
    define('APP_SQLITE_FILE', APP_API_DIR . '/.db.db');
}

if (!defined('DB_MODE'))            define('DB_MODE',            (string)$CONFIG['DB_MODE']);
if (!defined('RECAPTCHA_SITEKEY'))  define('RECAPTCHA_SITEKEY',  (string)$CONFIG['RECAPTCHA_SITEKEY']);
if (!defined('RECAPTCHA_SECRET'))   define('RECAPTCHA_SECRET',   (string)$CONFIG['RECAPTCHA_SECRET']);

/* ===============================
   TIMEZONE
   =============================== */
@date_default_timezone_set((string)$CONFIG['timezone']);

/* ===============================
   DEBUG + LOGGING
   =============================== */
$debug = !empty($CONFIG['debug']);
ini_set('display_errors', $debug ? '1' : '0');
ini_set('display_startup_errors', $debug ? '1' : '0');
error_reporting(E_ALL);

if (!function_exists('__app_init_logging')) {
    function __app_init_logging(): string {
        $logDir = APP_BASE_DIR . '/logs';
        if (!is_dir($logDir)) { @mkdir($logDir, 0755, true); }
        $primary = $logDir . '/app_error.log';
        $ok = @file_put_contents($primary, (file_exists($primary) ? "" : "=== app_error.log initialized at " . date('c') . " ===\n"), FILE_APPEND);
        if ($ok !== false) {
            ini_set('log_errors', '1');
            ini_set('error_log', $primary);
            return $primary;
        }
        $tmp = rtrim(sys_get_temp_dir(), '/\\') . '/youtivi_app_error.log';
        @file_put_contents($tmp, (file_exists($tmp) ? "" : "=== app_error.log (tmp) initialized at " . date('c') . " ===\n"), FILE_APPEND);
        ini_set('log_errors', '1');
        ini_set('error_log', $tmp);
        return $tmp;
    }
}
$__log_path = __app_init_logging();
@file_put_contents($__log_path, "[BOOT] " . date('c') . " base=" . (app_base_path() ?: '/') . " mode=" . DB_MODE . " sqlite=" . APP_SQLITE_FILE . "\n", FILE_APPEND);

if (!function_exists('__app_fatal_logger')) {
    function __app_fatal_logger() {
        $e = error_get_last();
        if ($e && in_array($e['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR], true)) {
            $msg = sprintf("[FATAL] %s in %s:%d", $e['message'], $e['file'], $e['line']);
            error_log($msg);
            if (!headers_sent()) header('Content-Type: text/plain; charset=UTF-8');
            // Only echo details in debug; otherwise generic text
            $isDebug = !empty($GLOBALS['CONFIG']['debug']);
            echo $isDebug ? ("Application fatal error.\n" . $msg . "\n") : "Application error.\n";
        }
    }
    register_shutdown_function('__app_fatal_logger');
}
if (!function_exists('__app_error_handler')) {
    function __app_error_handler($errno, $errstr, $errfile, $errline) {
        $msg = sprintf("[PHP-%d] %s in %s:%d", $errno, $errstr, $errfile, $errline);
        error_log($msg);
        return false; // let PHP handle severity for notices/warnings
    }
    set_error_handler('__app_error_handler');
}

/* ===============================
   SESSIONS — STABLE & SUBFOLDER SAFE
   =============================== */
$base = app_base_path() ?: '/';
$sessionName = 'YTVSESSID_' . substr(md5($base), 0, 8);

if (session_status() !== PHP_SESSION_ACTIVE) {
    ini_set('session.name', $sessionName);
    ini_set('session.cookie_path', $base ?: '/');
    ini_set('session.use_only_cookies', '1');
    ini_set('session.use_cookies', '1');
    ini_set('session.use_trans_sid', '0');
    ini_set('session.cookie_httponly', '1');
    if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') {
        ini_set('session.cookie_secure', '1');
    }
}

if (session_status() !== PHP_SESSION_ACTIVE) {
    $started = @session_start();
    if (!$started || session_status() !== PHP_SESSION_ACTIVE) {
        @session_write_close();
        ini_set('session.save_handler', 'files');
        @session_start();
        error_log("[SESS] Fell back to file sessions");
    }
}

// Idle timeout 15min
$timeout = 900;
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - (int)$_SESSION['LAST_ACTIVITY']) > $timeout) {
    session_unset();
    session_destroy();
    @session_start();
}
$_SESSION['LAST_ACTIVITY'] = time();

/* ===============================
   DEBUG-ONLY OUTPUT BUFFER DIAG (safe)
   =============================== */
if ($debug && !function_exists('__app_ob_diag')) {
    // Only run if explicitly requested, to avoid polluting JSON/API output.
    if (isset($_GET['obdiag'])) {
        if (!ob_get_level()) { ob_start(); }
        function __app_ob_diag() {
            $len = ob_get_length();
            if ($len === false || $len === 0) {
                if (!headers_sent()) header('Content-Type: text/plain; charset=UTF-8');
                echo "OB_EMPTY_DIAG\n";
                echo "BASE=" . (app_base_path() ?: '/') . "\n";
                echo "SESSION_NAME=" . session_name() . "\n";
                echo "SESSION_ID=" . session_id() . "\n";
                echo "COOKIE_PATH=" . ini_get('session.cookie_path') . "\n";
                echo "ERROR_LOG=" . ini_get('error_log') . "\n";
            }
        }
        register_shutdown_function('__app_ob_diag');
    }
}
