<?php
declare(strict_types=1);
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
$manifest = require __DIR__ . '/database/install-manifest.php'; $error = null; $done = false;
function installer_prefix(string $value): string { $value=trim($value); if(!preg_match('/^[A-Za-z][A-Za-z0-9_]{0,45}$/',$value)){throw new RuntimeException('Das Tabellenpräfix darf nur Buchstaben, Zahlen und Unterstriche enthalten und muss mit einem Buchstaben beginnen.');}return str_ends_with($value,'_')?$value:$value.'_'; }
function installer_sql(PDO $pdo,string $sql,string $prefix):void{$sql=str_replace(['{{PREFIX}}','travel_1_'],$prefix,$sql);$sql=preg_replace_callback('/\bCONSTRAINT\s+(`?)(fk_[A-Za-z0-9_]+)\1/i',static fn(array $m):string=>'CONSTRAINT '.$prefix.$m[2],$sql)??$sql;foreach(preg_split('/;\s*(?=(?:--[^\n]*\n|\/\*.*?\*\/\s*)*(?:CREATE|ALTER|INSERT|UPDATE|DELETE|SET)\b)/is',$sql)?:[] as $statement){if(trim($statement)!==''){$pdo->exec($statement);}}}
function installer_config(array $v):string{return "<?php\ndeclare(strict_types=1);\n\nreturn ".var_export(['app'=>['name'=>'TripTale','base_url'=>$v['base_url'],'language'=>'de','version'=>$v['version']],'database'=>['host'=>$v['host'],'name'=>$v['database'],'user'=>$v['user'],'password'=>$v['password'],'charset'=>'utf8mb4','prefix'=>$v['prefix']]],true).";\n";}
if($_SERVER['REQUEST_METHOD']==='POST'){$host=trim((string)($_POST['host']??''));$database=trim((string)($_POST['database']??''));$user=trim((string)($_POST['user']??''));$password=(string)($_POST['password']??'');$baseUrl=rtrim(trim((string)($_POST['base_url']??'')),'/');$first=trim((string)($_POST['first_name']??''));$last=trim((string)($_POST['last_name']??''));$email=trim((string)($_POST['email']??''));$adminPassword=(string)($_POST['admin_password']??'');try{$prefix=installer_prefix((string)($_POST['prefix']??'triptale_'));if($host===''||$database===''||$user===''||!filter_var($baseUrl,FILTER_VALIDATE_URL)){throw new RuntimeException('Bitte Datenbankangaben und die vollständige Adresse der Anwendung eintragen.');}if($first===''||$last===''||!filter_var($email,FILTER_VALIDATE_EMAIL)||strlen($adminPassword)<12){throw new RuntimeException('Bitte vollständige Hauptadmin-Daten angeben. Das Passwort benötigt mindestens 12 Zeichen.');}$pdo=new PDO('mysql:host='.$host.';dbname='.$database.';charset=utf8mb4',$user,$password,[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);$exists=$pdo->prepare('SHOW TABLES LIKE :name');$exists->execute([':name'=>$prefix.'users']);if($exists->fetchColumn()){throw new RuntimeException('Für dieses Präfix existieren bereits Tabellen. Bitte ein anderes Präfix verwenden.');}foreach(array_merge([$manifest['schema']],$manifest['migrations']) as $file){$path=__DIR__.'/database/'.$file;if(!is_file($path)){throw new RuntimeException('Installationsdatei fehlt: '.$file);}installer_sql($pdo,(string)file_get_contents($path),$prefix);}$pdo->exec('CREATE TABLE '.$prefix.'app_meta (meta_key VARCHAR(100) NOT NULL,meta_value VARCHAR(255) NULL,PRIMARY KEY(meta_key)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci');$q=$pdo->prepare('INSERT INTO '.$prefix.'users (first_name,last_name,email,password_hash,role,status) VALUES (:first,:last,:email,:hash,\'main_admin\',\'active\')');$q->execute([':first'=>$first,':last'=>$last,':email'=>$email,':hash'=>password_hash($adminPassword,PASSWORD_DEFAULT)]);$q=$pdo->prepare('INSERT INTO '.$prefix.'app_meta (meta_key,meta_value) VALUES (\'version\',:version)');$q->execute([':version'=>$manifest['version']]);if(!is_dir(__DIR__.'/config')&&!mkdir(__DIR__.'/config',0755,true)){throw new RuntimeException('Der Ordner config konnte nicht angelegt werden.');}if(file_put_contents(__DIR__.'/config/config.php',installer_config(['host'=>$host,'database'=>$database,'user'=>$user,'password'=>$password,'base_url'=>$baseUrl,'prefix'=>$prefix,'version'=>$manifest['version']]),LOCK_EX)===false){throw new RuntimeException('Die Konfigurationsdatei konnte nicht gespeichert werden.');}if(!is_dir(__DIR__.'/uploads')&&!mkdir(__DIR__.'/uploads',0755,true)){throw new RuntimeException('Der Upload-Ordner konnte nicht angelegt werden.');}$done=true;}catch(Throwable $e){$error=$e->getMessage();}}
?><!doctype html><html lang="de"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>TripTale installieren</title><style>body{font-family:system-ui,sans-serif;background:#f4f6f8;margin:0;padding:32px;color:#17202a}main{max-width:650px;margin:auto;background:#fff;padding:28px;border-radius:14px;box-shadow:0 4px 18px #0001}label{display:block;margin-top:14px;font-weight:650}input{box-sizing:border-box;width:100%;margin-top:6px;padding:11px;border:1px solid #b9c1c8;border-radius:7px;font:inherit}button{margin-top:22px;padding:12px 16px;border:0;border-radius:7px;background:#126e82;color:#fff;font-weight:700;font:inherit}.error{background:#ffe6e3;padding:12px;border-radius:7px}.done{background:#e6f5e9;padding:16px;border-radius:7px;color:#1d6831}h2{margin-top:28px;font-size:1.12rem}@media(max-width:600px){body{padding:12px}main{padding:18px}}</style><main><h1>TripTale installieren</h1><?php if($done):?><div class="done"><strong>Installation abgeschlossen.</strong><p>Du kannst dich jetzt anmelden. Lösche anschließend unbedingt <code>setup.php</code> und <code>installer.php</code> vom Server.</p><p><a href="/login.php">Zur Anmeldung</a></p></div><?php else:?><p>Diese Seite richtet eine neue, leere TripTale-Installation ein.</p><?php if($error):?><p class="error"><?=htmlspecialchars($error,ENT_QUOTES,'UTF-8')?></p><?php endif;?><form method="post"><h2>Datenbank</h2><label>Host<input name="host" required value="<?=htmlspecialchars((string)($_POST['host']??''),ENT_QUOTES,'UTF-8')?>"></label><label>Datenbankname<input name="database" required value="<?=htmlspecialchars((string)($_POST['database']??''),ENT_QUOTES,'UTF-8')?>"></label><label>Benutzername<input name="user" required value="<?=htmlspecialchars((string)($_POST['user']??''),ENT_QUOTES,'UTF-8')?>"></label><label>Passwort<input name="password" type="password" required></label><label>Tabellenpräfix<input name="prefix" value="<?=htmlspecialchars((string)($_POST['prefix']??'triptale_'),ENT_QUOTES,'UTF-8')?>" required></label><h2>Anwendung und Hauptadministrator</h2><label>Adresse der Anwendung<input name="base_url" type="url" placeholder="https://triptale.example.de" required value="<?=htmlspecialchars((string)($_POST['base_url']??''),ENT_QUOTES,'UTF-8')?>"></label><label>Vorname<input name="first_name" required value="<?=htmlspecialchars((string)($_POST['first_name']??''),ENT_QUOTES,'UTF-8')?>"></label><label>Nachname<input name="last_name" required value="<?=htmlspecialchars((string)($_POST['last_name']??''),ENT_QUOTES,'UTF-8')?>"></label><label>E-Mail<input name="email" type="email" required value="<?=htmlspecialchars((string)($_POST['email']??''),ENT_QUOTES,'UTF-8')?>"></label><label>Passwort für Hauptadmin<input name="admin_password" type="password" minlength="12" required></label><button>Installation starten</button></form><?php endif;?></main></html>
