<?php
/* =========================================================
   CMS INSTALLATION
   - Auto-Detect BASE_URL
   - Erstellt DB, Tabellen, Admin
   - Schreibt config.php
   - Sperrt sich selbst (install.lock)
========================================================= */

ini_set('display_errors', 1);
error_reporting(E_ALL);

/* ------------------------------
   Installation gesperrt?
------------------------------ */
if (file_exists(__DIR__ . '/install.lock')) {
    exit('❌ CMS ist bereits installiert. (install.lock vorhanden)');
}

/* ------------------------------
   BASE_URL automatisch erkennen
------------------------------ */
$docRoot = realpath($_SERVER['DOCUMENT_ROOT']);
$cmsDir  = realpath(__DIR__);

$autoBaseUrl = str_replace($docRoot, '', $cmsDir);
$autoBaseUrl = $autoBaseUrl === '' ? '/' : $autoBaseUrl;

/* ------------------------------
   Status
------------------------------ */
$errors = [];
$success = false;

/* ------------------------------
   Formular verarbeitet?
------------------------------ */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $baseUrl   = rtrim($_POST['base_url'] ?? '', '/');
    $adminUser = trim($_POST['admin_user'] ?? '');
    $adminPass = $_POST['admin_pass'] ?? '';
    $tinyPath  = trim($_POST['tiny_path'] ?? '');

    if ($baseUrl === '') $baseUrl = '/';

    if (!$adminUser || !$adminPass || !$tinyPath) {
        $errors[] = 'Bitte alle Felder ausfüllen.';
    }

    if (!$errors) {
        try {

            /* ------------------------------
               Datenbank
            ------------------------------ */
            $dbFile = __DIR__ . '/cms.sqlite';
            $db = new PDO('sqlite:' . $dbFile);
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            /* ------------------------------
               Tabellen
            ------------------------------ */
            $db->exec("
                CREATE TABLE IF NOT EXISTS contents (
                    slug TEXT PRIMARY KEY,
                    content TEXT
                );

                CREATE TABLE IF NOT EXISTS users (
                    username TEXT PRIMARY KEY,
                    password TEXT
                );
            ");

            /* ------------------------------
               Admin anlegen
            ------------------------------ */
            $hash = password_hash($adminPass, PASSWORD_DEFAULT);
            $stmt = $db->prepare("INSERT OR REPLACE INTO users (username,password) VALUES (?,?)");
            $stmt->execute([$adminUser, $hash]);

            /* ------------------------------
               Upload-Verzeichnis
            ------------------------------ */
            $uploadDir = __DIR__ . '/uploads';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0775, true);
            }
            if (!is_writable($uploadDir)) {
                throw new Exception('Upload-Verzeichnis ist nicht beschreibbar.');
            }

            /* ------------------------------
               config.php schreiben
            ------------------------------ */
            $config = [
                'BASE_URL' => $baseUrl,
                'DB'       => $dbFile,
                'TINYMCE'  => $tinyPath
            ];

            $configPhp =
                "<?php\n".
                "// automatisch erzeugt durch install.php\n".
                "return " . var_export($config, true) . ";\n";

            file_put_contents(__DIR__ . '/config.php', $configPhp);

            /* ------------------------------
               Install sperren
            ------------------------------ */
            file_put_contents(__DIR__ . '/install.lock', date('c'));

            $success = true;

        } catch (Throwable $e) {
            $errors[] = $e->getMessage();
        }
    }
}
?>
<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CMS Installation</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">

<div class="container py-5" style="max-width:520px">

<h3 class="mb-3">CMS Installation</h3>

<?php if ($success): ?>
  <div class="alert alert-success">
    ✅ <strong>Installation erfolgreich!</strong><br><br>
    <a href="<?= htmlspecialchars($baseUrl) ?>/login.php" class="btn btn-primary">
      Zum Login
    </a>
  </div>

<?php else: ?>

<?php foreach ($errors as $e): ?>
  <div class="alert alert-danger"><?= htmlspecialchars($e) ?></div>
<?php endforeach; ?>

<form method="post" class="card p-4 shadow-sm">

  <label class="form-label">Base URL</label>
  <input class="form-control mb-2"
         name="base_url"
         value="<?= htmlspecialchars($autoBaseUrl) ?>"
         required>

  <div class="form-text mb-3">
    Automatisch erkannt. Beispiel: <code>/phpcms</code>
  </div>

  <label class="form-label">TinyMCE Pfad</label>
  <input class="form-control mb-3"
         name="tiny_path"
         value="tinymce/tinymce.min.js"
         required>

  <label class="form-label">Admin Benutzer</label>
  <input class="form-control mb-2"
         name="admin_user"
         required>

  <label class="form-label">Admin Passwort</label>
  <input class="form-control mb-3"
         type="password"
         name="admin_pass"
         required>

  <button class="btn btn-success w-100">
    CMS installieren
  </button>

</form>

<?php endif; ?>

<hr class="my-4">

<div class="text-muted small">
  Installationspfad: <code><?= htmlspecialchars($cmsDir) ?></code><br>
  Erkannte BASE_URL: <code><?= htmlspecialchars($autoBaseUrl) ?></code>
</div>

</div>
</body>
</html>
