<?php
declare(strict_types=1);
$done = file_exists(__DIR__.'/app/config.php');
$installRequestStartedDone = $done;
if ($installRequestStartedDone) { http_response_code(404); exit('Nicht gefunden.'); }
$error = '';
$installDeleted = false;
$installDeleteWarning = '';
function make_table_prefix(): string { return 'qr_' . bin2hex(random_bytes(4)) . '_'; }
function valid_prefix(string $prefix): bool { return (bool)preg_match('/^[a-zA-Z0-9_]{1,32}$/', $prefix); }
function h($v){return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');}
function remove_installer_after_success(): array {
    $file = __FILE__;
    if (!is_file($file)) return [true, ''];
    if (@unlink($file)) return [true, 'install.php wurde automatisch gelöscht.'];
    return [false, 'Installation abgeschlossen. install.php konnte wegen Server-Dateirechten nicht automatisch gelöscht werden. Bitte die Datei manuell löschen.'];
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$done) {
    $base = rtrim(trim($_POST['base_url'] ?? ''), '/');
    $host = trim($_POST['db_host'] ?? 'localhost');
    $name = trim($_POST['db_name'] ?? '');
    $user = trim($_POST['db_user'] ?? '');
    $pass = $_POST['db_pass'] ?? '';
    $adminName = trim($_POST['admin_name'] ?? '');
    $email = trim($_POST['admin_email'] ?? '');
    $adminPass = $_POST['admin_password'] ?? '';
    $prefix = trim($_POST['table_prefix'] ?? '') ?: make_table_prefix();
    $registrationEnabled = isset($_POST['registration_enabled']);
    $forceSsl = isset($_POST['force_ssl']);
    $geoTracking = isset($_POST['geo_tracking']);
    $geoProviderRaw = $_POST['geo_provider'] ?? 'none';
    $geoProvider = in_array($geoProviderRaw, ['none','cloudflare','ipapi'], true) ? $geoProviderRaw : 'none';
    $mailTransport = ($_POST['mail_transport'] ?? 'mail') === 'smtp' ? 'smtp' : 'mail';
    $fromEmail = trim($_POST['from_email'] ?? $email);
    $fromName = trim($_POST['from_name'] ?? 'KuhRator');
    $smtpHost = trim($_POST['smtp_host'] ?? '');
    $smtpPort = (int)($_POST['smtp_port'] ?? 587);
    $smtpEncryption = in_array(($_POST['smtp_encryption'] ?? 'tls'), ['tls','ssl','none'], true) ? $_POST['smtp_encryption'] : 'tls';
    $smtpUser = trim($_POST['smtp_user'] ?? '');
    $smtpPass = $_POST['smtp_pass'] ?? '';
    $mailInvalid = !filter_var($fromEmail, FILTER_VALIDATE_EMAIL) || ($mailTransport === 'smtp' && ($smtpHost === '' || $smtpPort < 1));
    if (!filter_var($base, FILTER_VALIDATE_URL) || !$name || !$user || !filter_var($email, FILTER_VALIDATE_EMAIL) || strlen($adminPass) < 12 || !preg_match('/[A-Za-zÄÖÜäöü]/u', $adminPass) || !preg_match('/[0-9\\W_]/u', $adminPass) || !valid_prefix($prefix) || $mailInvalid) {
        $error = 'Bitte alle Felder korrekt ausfüllen. Das Admin-Passwort braucht mindestens 12 Zeichen, mindestens einen Buchstaben sowie mindestens eine Zahl oder ein Sonderzeichen. SMTP benötigt Host, Port und eine gültige Absenderadresse.';
    } else {
        try {
            $pdo = new PDO('mysql:host='.$host.';dbname='.$name.';charset=utf8mb4', $user, $pass, [PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
            $sql = file_get_contents(__DIR__.'/app/schema.sql');
            $sql = str_replace('{{prefix}}', $prefix, $sql);
            $pdo->exec($sql);
            $stmt = $pdo->prepare('INSERT INTO `'.$prefix.'users`(name,email,password_hash,role,email_verified_at) VALUES(?,?,?,?,NOW())');
            $stmt->execute([$adminName !== '' ? $adminName : null, $email, password_hash($adminPass, PASSWORD_DEFAULT), 'superadmin']);
            $config = "<?php\nreturn ".var_export([
                'base_url'=>$base,
                'db_host'=>$host,
                'db_name'=>$name,
                'db_user'=>$user,
                'db_pass'=>$pass,
                'table_prefix'=>$prefix,
                'geo_tracking'=>$geoTracking,
                'geo_provider'=>$geoProvider,
                'registration_enabled'=>$registrationEnabled,
                'force_ssl'=>$forceSsl,
                'trusted_proxies'=>[],
                'session_name'=>'qrmanager_'.bin2hex(random_bytes(6)),
                'stats_salt'=>bin2hex(random_bytes(32)),
                'reset_from_email'=>$fromEmail,
                'mail'=>[
                    'transport'=>$mailTransport,
                    'from_email'=>$fromEmail,
                    'from_name'=>$fromName ?: 'KuhRator',
                    'smtp_host'=>$smtpHost,
                    'smtp_port'=>$smtpPort,
                    'smtp_encryption'=>$smtpEncryption,
                    'smtp_user'=>$smtpUser,
                    'smtp_pass'=>$smtpPass,
                ],
            ], true).";\n";
            file_put_contents(__DIR__.'/app/config.php', $config, LOCK_EX);
            $done = true;
            [$installDeleted, $installDeleteWarning] = remove_installer_after_success();
        } catch (Throwable $e) { $error = 'Installation fehlgeschlagen: '.$e->getMessage(); }
    }
}
$defaultPrefix = 'qr_' . substr(bin2hex(random_bytes(4)), 0, 8) . '_';
$mailTransport = $_POST['mail_transport'] ?? 'mail';
?><!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>QR-Manager Installation</title><link rel="stylesheet" href="public/assets/style.css"><script>document.addEventListener('DOMContentLoaded',()=>{const radios=document.querySelectorAll('input[name="mail_transport"]');const box=document.querySelector('[data-smtp-settings]');const sync=()=>{box.style.display=document.querySelector('input[name="mail_transport"]:checked')?.value==='smtp'?'grid':'none'};radios.forEach(r=>r.addEventListener('change',sync));sync();});</script></head><body><main class="login install"><section class="card formgrid install-card"><h1>KuhRator installieren</h1><?php if($done): ?><?php if($installDeleted): ?><p class="notice ok"><?= h($installDeleteWarning) ?></p><?php elseif($installDeleteWarning): ?><p class="notice"><?= h($installDeleteWarning) ?></p><?php else: ?><p class="notice ok">Installation ist bereits abgeschlossen.</p><?php endif; ?><p><a class="btn" href="admin/login.php">Zum Login</a></p><?php else: ?><?php if($error): ?><p class="notice"><?= h($error) ?></p><?php endif; ?><form method="post" class="install-form"><label class="full">Basis-URL<input name="base_url" required placeholder="https://domain.ch/qr-tool" value="<?= h($_POST['base_url'] ?? '') ?>"></label><label>DB Host<input name="db_host" required value="<?= h($_POST['db_host'] ?? 'localhost') ?>"></label><label>DB Name<input name="db_name" required value="<?= h($_POST['db_name'] ?? '') ?>"></label><label>DB Benutzer<input name="db_user" required value="<?= h($_POST['db_user'] ?? '') ?>"></label><label>DB Passwort<input name="db_pass" type="password"></label><label class="full">Tabellenpräfix<input name="table_prefix" required pattern="[A-Za-z0-9_]{1,32}" value="<?= h($_POST['table_prefix'] ?? $defaultPrefix) ?>"><small>Wird pro Installation zufällig vorgeschlagen. Damit können mehrere Installationen dieselbe Datenbank nutzen.</small></label><label class="check full"><input name="registration_enabled" type="checkbox" value="1" <?= isset($_POST['registration_enabled']) || $_SERVER['REQUEST_METHOD'] !== 'POST' ? 'checked' : '' ?>> Benutzerregistrierung aktivieren</label><label class="check full"><input name="force_ssl" type="checkbox" value="1" <?= isset($_POST['force_ssl']) || $_SERVER['REQUEST_METHOD'] !== 'POST' ? 'checked' : '' ?>> SSL/HTTPS erzwingen</label><label class="check full"><input name="geo_tracking" type="checkbox" value="1"> Geo-Tracking aktivieren</label><label class="full">Geo-Anbieter<select name="geo_provider"><option value="none" selected>Kein Geo-Tracking</option><option value="cloudflare">Cloudflare Header</option><option value="ipapi">ipapi.co</option></select><small>Optional. Cloudflare-Header werden nur verwendet, wenn hier Cloudflare gewählt ist.</small></label><label>Admin Name <span class="muted">optional</span><input name="admin_name" maxlength="100" value="<?= h($_POST['admin_name'] ?? '') ?>"></label><label>Admin E-Mail<input name="admin_email" type="email" required value="<?= h($_POST['admin_email'] ?? '') ?>"></label><label>Admin Passwort<input name="admin_password" type="password" minlength="12" required></label><div class="full install-section"><h2>Mailversand für Passwort-Reset</h2><div class="radio-row"><label><input type="radio" name="mail_transport" value="mail" <?= $mailTransport !== 'smtp' ? 'checked' : '' ?>> Servermailer</label><label><input type="radio" name="mail_transport" value="smtp" <?= $mailTransport === 'smtp' ? 'checked' : '' ?>> SMTP</label></div></div><label>Absender E-Mail<input name="from_email" type="email" required value="<?= h($_POST['from_email'] ?? $_POST['admin_email'] ?? '') ?>"></label><label>Absendername<input name="from_name" value="<?= h($_POST['from_name'] ?? 'KuhRator') ?>"></label><div class="smtp-settings full" data-smtp-settings><label>SMTP Host<input name="smtp_host" value="<?= h($_POST['smtp_host'] ?? '') ?>" placeholder="smtp.example.ch"></label><label>SMTP Port<input name="smtp_port" type="number" min="1" value="<?= h($_POST['smtp_port'] ?? '587') ?>"></label><label>Verschlüsselung<select name="smtp_encryption"><option value="tls" <?= ($_POST['smtp_encryption'] ?? 'tls')==='tls'?'selected':'' ?>>STARTTLS</option><option value="ssl" <?= ($_POST['smtp_encryption'] ?? '')==='ssl'?'selected':'' ?>>SSL/TLS</option><option value="none" <?= ($_POST['smtp_encryption'] ?? '')==='none'?'selected':'' ?>>Keine</option></select></label><label>SMTP Benutzer<input name="smtp_user" value="<?= h($_POST['smtp_user'] ?? '') ?>"></label><label>SMTP Passwort<input name="smtp_pass" type="password" value="<?= h($_POST['smtp_pass'] ?? '') ?>"></label></div><button class="btn">Installieren</button></form><?php endif; ?></section></main></body></html>
