<?php
declare(strict_types=1);

require_once __DIR__ . '/database.php';
require_once __DIR__ . '/../core/Performance.php';
require_once __DIR__ . '/../models/SiteSetting.php';

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_name(SESSION_NAME);
    session_start();
}

$scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
$requestUri = (string)($_SERVER['REQUEST_URI'] ?? '/');
$isGetRequest = ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET';
$isAuthenticated = isset($_SESSION['auth']);
$isSensitivePage = Performance::isSensitiveScript($scriptName) || str_starts_with($scriptName, '/admin/');

$performanceDefaults = [
    'perf_public_cache_enabled' => '1',
    'perf_public_cache_ttl' => '45',
    'perf_client_cache_seconds' => '120',
    'perf_html_compress_enabled' => '1',
];

try {
    $performanceSettings = array_merge(
        $performanceDefaults,
        (new SiteSetting())->getMany(array_keys($performanceDefaults))
    );
} catch (Throwable $e) {
    $performanceSettings = $performanceDefaults;
}

$publicCacheEnabled = ($performanceSettings['perf_public_cache_enabled'] ?? '1') === '1';
$publicCacheTtl = max(5, (int)($performanceSettings['perf_public_cache_ttl'] ?? '45'));
$clientCacheSeconds = max(0, (int)($performanceSettings['perf_client_cache_seconds'] ?? '120'));
$htmlCompressEnabled = ($performanceSettings['perf_html_compress_enabled'] ?? '1') === '1';

if (!headers_sent()) {
    if ($isSensitivePage || $isAuthenticated) {
        header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
        header('Pragma: no-cache');
    } else {
        header('Cache-Control: public, max-age=' . $clientCacheSeconds . ', stale-while-revalidate=60');
    }
}

if (!ob_get_level()) {
    if (extension_loaded('zlib') && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
        ob_start('ob_gzhandler');
    } else {
        ob_start();
    }
}

if ($htmlCompressEnabled && !Performance::isSensitiveScript($scriptName)) {
    ob_start(static function (string $buffer): string {
        if ($buffer === '') {
            return $buffer;
        }
        return preg_replace('/>\s+</', '><', $buffer) ?? $buffer;
    });
}

Performance::boot();
Performance::startPublicCache(
    $publicCacheEnabled,
    $publicCacheTtl,
    $isGetRequest,
    $isAuthenticated,
    $isSensitivePage,
    $requestUri
);

function ensureDefaultAdmins(): void
{
    $defaults = [
        ['username' => 'peimanpoor12', 'password' => 'peimanpoor12'],
        ['username' => 'hoseinpoor22', 'password' => 'hoseinpoor22'],
    ];

    foreach ($defaults as $admin) {
        $check = db()->prepare('SELECT id FROM users WHERE username = :username LIMIT 1');
        $check->execute(['username' => $admin['username']]);
        if ($check->fetch()) {
            continue;
        }

        $insert = db()->prepare('INSERT INTO users (full_name, username, password_hash, role) VALUES (:full_name, :username, :password_hash, :role)');
        $insert->execute([
            'full_name' => 'ادمین سیستم',
            'username' => $admin['username'],
            'password_hash' => password_hash($admin['password'], PASSWORD_DEFAULT),
            'role' => 'admin',
        ]);
    }
}
