<?php

declare(strict_types=1);

/**
 * Installer entry point for deployments whose web-server DOCUMENT ROOT is the app's
 * public/ folder — the very common cPanel/Plesk "point the domain at /public" setup.
 *
 * The bundle-root install.php lives one level ABOVE such a doc-root, so it is not
 * reachable, and public/index.php's "not installed" redirect to ../install.php would
 * bounce back through the front controller forever (the redirect loop). This sibling
 * runs the SAME installer, but with assets and the post-install link resolved to THIS
 * location, so it works whether the doc-root is the bundle root or its public/ folder.
 */

$root = dirname(__DIR__);

$__tz = (string) (((array) (is_file($root . '/config/app.php') ? require $root . '/config/app.php' : []))['timezone'] ?? 'Asia/Kathmandu');
if ($__tz !== '') { @date_default_timezone_set($__tz); if (!defined('PP_TIMEZONE')) define('PP_TIMEZONE', $__tz); }

// Already installed → the app is served from this same folder here.
if (file_exists($root . '/config/database.php')) {
    header('Location: ./');
    exit;
}

require_once $root . '/core/Autoloader.php';
$autoloader = new \PpPhp\Core\Autoloader();
$autoloader->addNamespace('PpPhp\\Core\\', $root . '/core/');
$autoloader->register();

// Authenticity gate — identical to the bundle-root installer.
if (is_file($root . '/release.json') && class_exists('\PpPhp\Core\Licensing\CodeIntegrity')) {
    if (!extension_loaded('sodium') || !function_exists('sodium_crypto_sign_verify_detached')) {
        http_response_code(500);
        header('Content-Type: text/plain; charset=utf-8');
        exit("PPPHP installer: the PHP \"sodium\" extension is required to verify this build's signature, but it is not enabled on this server.\n\n"
            . "Fix: in cPanel/Plesk open \"Select PHP Version\" → Extensions → tick \"sodium\" (libsodium), save, then reload install.php.\n");
    }
    try {
        $integrity = \PpPhp\Core\Licensing\CodeIntegrity::verify($root);
    } catch (\Throwable $e) {
        http_response_code(500);
        header('Content-Type: text/plain; charset=utf-8');
        exit("PPPHP installer: the build signature could not be checked on this server.\n\nDetail: " . $e->getMessage() . "\n");
    }
    if (($integrity['status'] ?? '') !== 'ok') {
        http_response_code(403);
        header('Content-Type: text/plain; charset=utf-8');
        exit("This copy of PPPHP could not be verified as a genuine, unmodified build from the vendor, so installation has been stopped.\n"
            . "Reason: " . (($integrity['reason'] ?? '') ?: 'integrity check failed') . "\n");
    }
}

// This entry point sits INSIDE public/, so /assets is a sibling ("{base}/assets") and
// the installed app is served from this same base ("{base}/") — not "{base}/public/".
$baseUrl = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/');
$controller = new \PpPhp\Core\Installer\Controller($root, $baseUrl, $baseUrl . '/assets', $baseUrl . '/');
$controller->run();
