<?php

declare(strict_types=1);

$projectRoot = dirname(__DIR__, 2);
$appRoot = dirname(__DIR__);

require_once $appRoot . '/system/support/Support.php';
require_once $appRoot . '/system/database/MigrationRunner.php';
require_once $appRoot . '/system/shell/FlashNotifications.php';
require_once $appRoot . '/system/install/InstallerState.php';
require_once $appRoot . '/system/install/InstallerEnvWriter.php';
require_once $appRoot . '/system/install/InstallerConfigService.php';
require_once $appRoot . '/system/install/InstallerExecutionService.php';
require_once $appRoot . '/modules/identity/AuthRepository.php';
require_once $appRoot . '/jsonm/php/runtime/autoload.php';
require_once $appRoot . '/modules/design/DefinitionFontHeadRenderer.php';

MyronEnv::load($projectRoot . '/.env');
myronEnsureSession();

$state = MyronInstallerState::fromProjectRoot($projectRoot);
$flashMessages = [];
$values = [
    'db_host' => (string) ($_POST['db_host'] ?? '127.0.0.1'),
    'db_port' => (string) ($_POST['db_port'] ?? '3306'),
    'db_name' => (string) ($_POST['db_name'] ?? ''),
    'db_user' => (string) ($_POST['db_user'] ?? ''),
    'db_pass' => '',
    'site_title' => (string) ($_POST['site_title'] ?? 'My MyronCMS Site'),
    'site_url' => (string) ($_POST['site_url'] ?? myronInstallerDefaultSiteUrl()),
    'public_base_path' => (string) ($_POST['public_base_path'] ?? '/'),
    'admin_login_path' => (string) ($_POST['admin_login_path'] ?? '/control-room'),
    'admin_email' => (string) ($_POST['admin_email'] ?? ''),
];

if ($state->isInstalled()) {
    myronRedirect($state->adminLoginUrl());
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        myronRequireCsrf($_POST['csrf_token'] ?? null);

        $configService = new MyronInstallerConfigService($appRoot);
        $envWriter = new MyronInstallerEnvWriter($state->envPath(), $projectRoot . '/.env.example');
        $execution = new MyronInstallerExecutionService($projectRoot, $appRoot, $state, $configService, $envWriter);
        $result = $execution->install($_POST);
        myronSetAuthenticatedUserId((string) ($result['user']['id'] ?? ''));
        myronRedirect((string) $result['publicUrl']);
    } catch (Throwable $exception) {
        $flashMessages[] = myronCreateFlashMessage($exception->getMessage(), 'error');
        foreach (array_keys($values) as $key) {
            if ($key === 'db_pass') {
                continue;
            }
            $values[$key] = (string) ($_POST[$key] ?? $values[$key]);
        }
    }
}

$csrfToken = myronCsrfToken();
$definitionFontHeadTags = (new MyronDefinitionFontHeadRenderer())->render();

function myronInstallerDefaultSiteUrl(): string
{
    $origin = myronRequestOrigin();
    return $origin !== null ? $origin : 'https://example.com';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Install MyronCMS</title>
  <?= $definitionFontHeadTags . "\n" ?>
  <link rel="stylesheet" href="<?= myronEscape(myronBuildAssetUrl('runtime/css/tokens.css')) ?>">
  <link rel="stylesheet" href="<?= myronEscape(myronBuildAssetUrl('runtime/css/runtime-fonts.css')) ?>">
  <link rel="stylesheet" href="<?= myronEscape(myronBuildAssetUrl('runtime/css/base.css')) ?>">
  <link rel="stylesheet" href="<?= myronEscape(myronBuildAssetUrl('runtime/css/components.css')) ?>">
  <link rel="stylesheet" href="<?= myronEscape(myronBuildAssetUrl('runtime/css/style-guide.css')) ?>">
  <script src="<?= myronEscape(myronBuildAssetUrl('runtime/js/interactive-atoms.min.js')) ?>" defer></script>
</head>
<body>
  <?php myronRenderFlashToastRegion($flashMessages); ?>
  <main class="mc-page-canvas mc-page-canvas--site mc-auth-layout">
    <section class="myron-auth-form myron-auth-form--wide">
      <div class="mc-workspace__header mc-workspace__header--auth">
        <span class="mc-workspace__eyebrow">First-Run Setup</span>
        <div class="mc-workspace__title-row">
          <h1 class="mc-workspace__title">Install MyronCMS</h1>
        </div>
        <p class="mc-workspace__subtitle">Configure the database, site identity, and first administrator account.</p>
      </div>

      <form method="post" class="sg-form-grid" autocomplete="off">
        <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">

        <div class="sg-field sg-field--full">
          <span class="sg-field__label">Step 1 · MySQL / MariaDB Database</span>
        </div>
        <input type="hidden" name="db_driver" value="mysql">

        <label class="sg-field">
          <span class="sg-field__label">Database Host</span>
          <input class="sg-field__control" type="text" name="db_host" required value="<?= myronEscape($values['db_host']) ?>" placeholder="127.0.0.1">
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Database Port</span>
          <input class="sg-field__control" type="text" name="db_port" required inputmode="numeric" pattern="[0-9]{2,5}" value="<?= myronEscape($values['db_port']) ?>" placeholder="3306">
          <span class="sg-field__hint">Use 3306 for most web hosts. MAMP often uses 8889.</span>
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Database Name</span>
          <input class="sg-field__control" type="text" name="db_name" required value="<?= myronEscape($values['db_name']) ?>" placeholder="myroncms">
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Database Username</span>
          <input class="sg-field__control" type="text" name="db_user" required value="<?= myronEscape($values['db_user']) ?>" placeholder="database user">
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Database Password</span>
          <input class="sg-field__control" type="password" name="db_pass" value="" placeholder="database password">
        </label>

        <div class="sg-field sg-field--full">
          <span class="sg-field__label">Step 2 · Site Identity</span>
        </div>

        <label class="sg-field">
          <span class="sg-field__label">Site Name</span>
          <input class="sg-field__control" type="text" name="site_title" required value="<?= myronEscape($values['site_title']) ?>" placeholder="My Site">
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Site URL</span>
          <input class="sg-field__control" type="url" name="site_url" required value="<?= myronEscape($values['site_url']) ?>" placeholder="https://example.com">
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Public Website Path</span>
          <input class="sg-field__control" type="text" name="public_base_path" required value="<?= myronEscape($values['public_base_path']) ?>" placeholder="/">
          <span class="sg-field__hint">Use <code>/</code> for a normal domain-root website.</span>
        </label>

        <div class="sg-field sg-field--full">
          <span class="sg-field__label">Step 3 · Administrator</span>
        </div>

        <label class="sg-field">
          <span class="sg-field__label">Administrator Email</span>
          <input class="sg-field__control" type="email" name="admin_email" required value="<?= myronEscape($values['admin_email']) ?>" placeholder="admin@example.com">
        </label>

        <label class="sg-field">
          <span class="sg-field__label">Administrator Password</span>
          <input class="sg-field__control" type="password" name="admin_password" required value="" placeholder="At least 8 characters">
        </label>

        <label class="sg-field sg-field--full">
          <span class="sg-field__label">Admin Login Path</span>
          <input class="sg-field__control" type="text" name="admin_login_path" required value="<?= myronEscape($values['admin_login_path']) ?>" placeholder="/control-room">
          <span class="sg-field__hint">Avoid predictable paths. The login route will live under this path.</span>
        </label>

        <div class="sg-card__actions">
          <button class="sg-button sg-button--primary" type="submit">Install MyronCMS</button>
        </div>
      </form>
    </section>
  </main>
</body>
</html>
