<?php
// Production error handling: log everything, display nothing to visitors.
// (Flip display_errors to 1 only for local debugging.)
ini_set('display_errors', '0');
ini_set('display_startup_errors', '0');
ini_set('log_errors', '1');
error_reporting(E_ALL);

// Harden the session cookie before any session is started. This runs early
// because common.php is required near the top of every page. Guard on
// headers_sent() so pages that (legacy) include this after output don't warn.
if (session_status() === PHP_SESSION_NONE && !headers_sent()) {
    ini_set('session.use_strict_mode', '1');
    ini_set('session.cookie_httponly', '1');
    ini_set('session.cookie_samesite', 'Lax');
    if (!empty($_SERVER['HTTPS'])) {
        ini_set('session.cookie_secure', '1');
    }
}

// Dynamically build the path based on the location of the common.php file
$config_path = __DIR__ . '/config.php';
$functions_path = __DIR__ . '/functions.php';
$external_functions_path = __DIR__ . '/external-functions.php';
$vars_path = __DIR__ . '/vars.php';

// Check if the configuration file exists before requiring it.
// A missing config.php on a fresh copy means the app hasn't been installed
// yet — send the visitor to the web installer if it is still present.
if (file_exists($config_path)) {
    require_once($config_path);
} elseif (is_dir(__DIR__ . '/install') && !headers_sent()) {
    header('Location: install/');
    exit;
} else {
    die('Configuration file missing! Copy config-sample.php to config.php and fill in your settings.');
}

// Check for functions file
if (file_exists($functions_path)) {
    require_once($functions_path);
} else {
    die('Functions file missing!');
}

// Check for external functions file
if (file_exists($external_functions_path)) {
    require_once($external_functions_path);
} else {
    die('External functions file missing!');
}

// Check for variables file
if (file_exists($vars_path)) {
    require_once($vars_path);
} else {
    die('Variables file missing!');
}

// Example: Adding a polyfill for a PHP 7 or 8 feature if the environment is PHP 5.6
if (version_compare(PHP_VERSION, '7.0.0', '<')) {
    // Polyfill for PHP 7+ function if needed, e.g., `random_bytes`
    if (!function_exists('random_bytes')) {
        function random_bytes($length) {
            $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $pieces = [];
            $max = mb_strlen($keyspace, '8bit') - 1;
            for ($i = 0; $i < $length; ++$i) {
                $pieces[] = $keyspace[random_int(0, $max)];
            }
            return implode('', $pieces);
        }
    }
}
?>
