<?php
/**
 * Hostiva v3 — install wizard
 * Visit /install.php to set up the database & admin.
 * DELETE this file after install.
 */
declare(strict_types=1);
$sampleCfg = __DIR__ . '/config/config.sample.php';
$cfgPath   = __DIR__ . '/config/config.php';
$sqlPath   = __DIR__ . '/database/hostiva_v3.sql';

$step = $_GET['step'] ?? '1';
$msg = ''; $err = '';

function h($value): string { return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
function valid_identifier(string $value, string $label): string {
    $value = trim($value);
    if (!preg_match('/^[A-Za-z0-9_]+$/', $value)) {
        throw new Exception($label . ' may contain only letters, numbers, and underscores.');
    }
    return $value;
}
function quote_identifier(string $value): string { return '`' . str_replace('`', '``', $value) . '`'; }

$alreadyInstalled = file_exists($cfgPath) && (($_GET['force'] ?? '') !== '1');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$alreadyInstalled) {
    if ($step === '2') {
        try {
            $cfg = require $sampleCfg;
            $appUrl = rtrim(trim($_POST['app_url'] ?? 'http://localhost/hostiva'), '/');
            if (!filter_var($appUrl, FILTER_VALIDATE_URL)) throw new Exception('App URL must be a valid URL.');
            $cfg['app']['url']  = $appUrl;
            $path = parse_url($appUrl, PHP_URL_PATH);
            $cfg['app']['base_path'] = ($path && $path !== '/') ? rtrim($path, '/') : '';
            $cfg['app']['name'] = trim($_POST['app_name'] ?? 'Hostiva') ?: 'Hostiva';
            $cfg['app']['env']  = in_array($_POST['env'] ?? 'production', ['production','development'], true) ? $_POST['env'] : 'production';
            $cfg['app']['debug'] = $cfg['app']['env'] === 'development';
            $cfg['app']['key']  = bin2hex(random_bytes(32));
            $cfg['db']['host']  = trim($_POST['db_host'] ?? '127.0.0.1');
            $cfg['db']['port']  = (int)($_POST['db_port'] ?? 3306);
            $cfg['db']['name']  = valid_identifier($_POST['db_name'] ?? 'hostiva', 'Database name');
            $cfg['db']['user']  = trim($_POST['db_user'] ?? 'root');
            $cfg['db']['pass']  = (string)($_POST['db_pass'] ?? '');
            $cfg['security']['cookie_secure'] = parse_url($appUrl, PHP_URL_SCHEME) === 'https';

            if (!extension_loaded('pdo_mysql')) throw new Exception('PDO MySQL extension is not enabled.');
            if (!is_readable($sqlPath)) throw new Exception('Database SQL file is missing or unreadable.');

            $pdo = new PDO("mysql:host={$cfg['db']['host']};port={$cfg['db']['port']};charset=utf8mb4",
                $cfg['db']['user'], $cfg['db']['pass'], [PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
            $pdo->exec('CREATE DATABASE IF NOT EXISTS ' . quote_identifier($cfg['db']['name']) . ' CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci');
            $pdo->exec('USE ' . quote_identifier($cfg['db']['name']));
            $sql = file_get_contents($sqlPath);
            $sql = preg_replace('/CREATE\s+DATABASE\s+IF\s+NOT\s+EXISTS\s+`?[^`;]+`?.*?;/i', '', $sql);
            $sql = preg_replace('/USE\s+`?[^`;]+`?\s*;/i', '', $sql);
            $pdo->exec($sql);

            if (!empty($_POST['admin_email'])) {
                $adminEmail = strtolower(trim($_POST['admin_email']));
                if (!filter_var($adminEmail, FILTER_VALIDATE_EMAIL)) throw new Exception('Admin email is invalid.');
                $adminPass = (string)($_POST['admin_pass'] ?: 'Admin@12345');
                if (strlen($adminPass) < 8) throw new Exception('Admin password must be at least 8 characters.');
                $hash = password_hash($adminPass, PASSWORD_BCRYPT);
                $st = $pdo->prepare('UPDATE users SET email=?, password=?, name=? WHERE id=1');
                $st->execute([$adminEmail, $hash, trim($_POST['admin_name'] ?? '') ?: 'Super Admin']);
            }

            $export = "<?php\nreturn " . var_export($cfg, true) . ";\n";
            if (false === file_put_contents($cfgPath, $export, LOCK_EX)) {
                throw new Exception('Could not write config/config.php — check permissions.');
            }
            @chmod($cfgPath, 0640);
            $msg = 'Installation complete!';
            $step = 'done';
        } catch (Throwable $e) {
            $err = $e->getMessage();
        }
    }
}
?><!doctype html><html lang="en" data-theme="dark"><head>
<meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/>
<title>Hostiva — Install</title>
<link rel="stylesheet" href="assets/css/hostiva.css"/>
</head><body><div class="auth-wrap"><div class="auth-card" style="max-width:600px">
<div class="auth-logo"><div class="mark">H</div><div class="name">Hostiva Installer</div></div>
<?php if ($err): ?><div class="toast error" style="position:static;margin-bottom:14px"><?=h($err)?></div><?php endif; ?>
<?php if ($alreadyInstalled): ?>
  <h2>Already installed</h2>
  <p style="color:var(--text-dim)">A live configuration already exists. For safety, the installer is locked.</p>
  <p style="color:var(--text-dim)">Delete <code>install.php</code> now, or temporarily open <code>install.php?force=1</code> only if you intentionally need to reinstall.</p>
  <a class="btn btn-primary btn-block" href="pages/login.html">Open Hostiva</a>
<?php elseif ($step === 'done'): ?>
  <h2>✓ All set</h2>
  <p>Your platform is ready. For your safety, <strong>delete <code>install.php</code> now</strong>.</p>
  <a class="btn btn-primary btn-block" href="pages/login.html">Open Hostiva</a>
<?php elseif ($step === '1'): ?>
  <h2>Welcome</h2>
  <p style="color:var(--text-dim)">This wizard will create the database, seed default data, and write your config.</p>
  <ul style="color:var(--text-dim);font-size:13px">
    <li>PHP <?= PHP_VERSION ?> — <?= version_compare(PHP_VERSION,'7.4','>=')?'<span style="color:#86efac">OK</span>':'<span style="color:#fca5a5">needs ≥ 7.4</span>' ?></li>
    <li>PDO MySQL — <?= extension_loaded('pdo_mysql')?'<span style="color:#86efac">OK</span>':'<span style="color:#fca5a5">missing</span>' ?></li>
    <li>config/ writable — <?= is_writable(__DIR__.'/config')?'<span style="color:#86efac">OK</span>':'<span style="color:#fca5a5">not writable</span>' ?></li>
    <li>logs/ writable — <?= is_writable(__DIR__.'/logs')?'<span style="color:#86efac">OK</span>':'<span style="color:#fca5a5">not writable</span>' ?></li>
  </ul>
  <a class="btn btn-primary btn-block" href="?step=2">Continue →</a>
<?php else: ?>
  <h2>Configure & install</h2>
  <form method="post" action="?step=2">
    <h3 style="margin-top:14px">App</h3>
    <div class="row"><div class="field"><label>App URL</label><input name="app_url" value="http://localhost/hostiva" required/></div>
      <div class="field"><label>App Name</label><input name="app_name" value="Hostiva"/></div></div>
    <div class="field"><label>Environment</label><select name="env"><option value="production">production</option><option value="development">development</option></select></div>
    <h3>Database</h3>
    <div class="row"><div class="field"><label>Host</label><input name="db_host" value="127.0.0.1" required/></div>
      <div class="field"><label>Port</label><input name="db_port" value="3306"/></div></div>
    <div class="field"><label>Database name</label><input name="db_name" value="hostiva" pattern="[A-Za-z0-9_]+" required/></div>
    <div class="row"><div class="field"><label>User</label><input name="db_user" value="root" required/></div>
      <div class="field"><label>Password</label><input name="db_pass" type="password"/></div></div>
    <h3>Admin user (optional)</h3>
    <div class="row"><div class="field"><label>Admin name</label><input name="admin_name" placeholder="Super Admin"/></div>
      <div class="field"><label>Admin email</label><input name="admin_email" type="email" placeholder="you@company.com"/></div></div>
    <div class="field"><label>Admin password (min 8)</label><input name="admin_pass" type="password" minlength="8" placeholder="Leave blank for Admin@12345"/></div>
    <button class="btn btn-primary btn-block" type="submit">Install Hostiva</button>
  </form>
<?php endif; ?>
</div></div></body></html>
