<?php

declare(strict_types=1);

/**
 * Karvi Partner Contract — shared web bootstrap (root + subfolder index.php).
 */

if (defined('KARVI_FRONT_LOADED')) {
    return;
}
define('KARVI_FRONT_LOADED', true);

if (!defined('KARVI_ROOT')) {
    define('KARVI_ROOT', dirname(__DIR__));
}

if (version_compare(PHP_VERSION, '8.0.0', '<')) {
    http_response_code(500);
    header('Content-Type: text/html; charset=utf-8');
    echo '<!DOCTYPE html><html><body style="font-family:sans-serif;padding:2rem">';
    echo '<h1>PHP 8.0+ required</h1><p>Current: ' . htmlspecialchars(PHP_VERSION, ENT_QUOTES, 'UTF-8') . '</p>';
    echo '</body></html>';
    exit;
}

$requiredFiles = [
    'router.php',
    'pages/home.php',
    'pages/admin_login.php',
    'lang/en.php',
    'config/config.php',
];

$missing = array_filter($requiredFiles, static fn (string $file): bool => !is_file(KARVI_ROOT . '/' . $file));
if ($missing !== []) {
    http_response_code(500);
    header('Content-Type: text/html; charset=utf-8');
    echo '<!DOCTYPE html><html><body style="font-family:sans-serif;padding:2rem">';
    echo '<h1>Incomplete upload</h1><p>Missing files:</p><ul>';
    foreach ($missing as $file) {
        echo '<li><code>' . htmlspecialchars($file, ENT_QUOTES, 'UTF-8') . '</code></li>';
    }
    echo '</ul><p>Re-upload the full zip to the server folder (not inside a nested subfolder).</p>';
    echo '<p><a href="health.php">health.php</a></p></body></html>';
    exit;
}

foreach (['uploads/contracts', 'uploads/signatures', 'uploads/signed', 'database'] as $dir) {
    $path = KARVI_ROOT . '/' . $dir;
    if (!is_dir($path)) {
        @mkdir($path, 0755, true);
    }
}

$dbFile = KARVI_ROOT . '/database/data.json';
if (!is_file($dbFile)) {
    @file_put_contents($dbFile, "[]\n");
}

if (!is_file(KARVI_ROOT . '/config/config.local.php') && is_file(KARVI_ROOT . '/install.php')) {
    header('Location: install.php', true, 302);
    exit;
}

try {
    require KARVI_ROOT . '/router.php';
} catch (Throwable $e) {
    error_log('[Karvi] ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
    http_response_code(500);
    header('Content-Type: text/html; charset=utf-8');
    echo '<!DOCTYPE html><html><body style="font-family:sans-serif;padding:2rem;max-width:720px">';
    echo '<h1>Application error</h1>';
    echo '<pre style="background:#f5f5f5;padding:1rem;border-radius:8px;font-size:13px;overflow:auto">';
    echo htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8');
    echo '</pre>';
    echo '<p><a href="health.php">health.php</a> | <a href="install.php">install.php</a></p>';
    echo '</body></html>';
    exit;
}
