<?php
// install.php - Installer wizard for Team Mania Pro
session_start();

$lock_file = __DIR__ . '/data/install.lock';
$db_file = __DIR__ . '/data/club.sqlite';

// If already locked, redirect to main application
if (file_exists($lock_file)) {
    header("Location: index.php");
    exit;
}

require_once __DIR__ . '/db_schema.php';

$errors = [];
$success = false;

// Basic environment check
$sqlite_ok = class_exists('PDO') && in_array('sqlite', PDO::getAvailableDrivers());
$data_dir_writable = is_writable(__DIR__ . '/data') || (!file_exists(__DIR__ . '/data') && is_writable(__DIR__));
$uploads_dir_writable = is_writable(__DIR__ . '/uploads') || (!file_exists(__DIR__ . '/uploads') && is_writable(__DIR__));

if (!$sqlite_ok) {
    $errors[] = "PDO SQLite Extension ist nicht auf dem Server installiert. Bitte aktivieren Sie diese in Ihrer php.ini.";
}
if (!$data_dir_writable) {
    $errors[] = "Das Verzeichnis '/data' ist nicht beschreibbar. Bitte korrigieren Sie die Ordnerrechte (CHMOD 775/777).";
}
if (!$uploads_dir_writable) {
    $errors[] = "Das Verzeichnis '/uploads' ist nicht beschreibbar. Bitte korrigieren Sie die Ordnerrechte (CHMOD 775/777).";
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($errors)) {
    $admin_username = trim($_POST['username'] ?? '');
    $admin_email = trim($_POST['email'] ?? '');
    $admin_password = $_POST['password'] ?? '';
    $admin_password_confirm = $_POST['password_confirm'] ?? '';
    $first_name = trim($_POST['first_name'] ?? '');
    $last_name = trim($_POST['last_name'] ?? '');

    if (empty($admin_username) || empty($admin_email) || empty($admin_password) || empty($first_name) || empty($last_name)) {
        $errors[] = "Bitte füllen Sie alle Felder aus.";
    } elseif (!filter_var($admin_email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Bitte geben Sie eine gültige E-Mail-Adresse ein.";
    } elseif ($admin_password !== $admin_password_confirm) {
        $errors[] = "Die Passwörter stimmen nicht überein.";
    } elseif (strlen($admin_password) < 6) {
        $errors[] = "Das Passwort muss mindestens 6 Zeichen lang sein.";
    }

    if (empty($errors)) {
        try {
            // Create data directory if not exists
            if (!file_exists(__DIR__ . '/data')) {
                mkdir(__DIR__ . '/data', 0777, true);
            }
            if (!file_exists(__DIR__ . '/uploads')) {
                mkdir(__DIR__ . '/uploads', 0777, true);
            }

            // Connect and initialize
            $pdo = new PDO("sqlite:" . $db_file);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            
            init_database($pdo);

            // Create admin user
            $password_hash = password_hash($admin_password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO users (username, password_hash, email, first_name, last_name, role) VALUES (:username, :password_hash, :email, :first_name, :last_name, 'admin')");
            $stmt->execute([
                ':username' => $admin_username,
                ':password_hash' => $password_hash,
                ':email' => $admin_email,
                ':first_name' => $first_name,
                ':last_name' => $last_name
            ]);

            // Create default legal pages (pre-filled with dummy text)
            $stmt = $pdo->prepare("INSERT INTO pages (slug, title, content, updated_by) VALUES (:slug, :title, :content, 1)");
            
            $stmt->execute([
                ':slug' => 'impressum',
                ':title' => 'Impressum',
                ':content' => '<h1>Impressum</h1><p>Angaben gemäß § 5 TMG:</p><p>Dein Verein e.V.<br>Musterstraße 1<br>12345 Musterstadt</p><p><strong>Vertreten durch:</strong><br>1. Vorsitzende(r)</p><p><strong>Kontakt:</strong><br>E-Mail: info@deinverein.de</p>'
            ]);
            
            $stmt->execute([
                ':slug' => 'agb',
                ':title' => 'Allgemeine Geschäftsbedingungen (AGB)',
                ':content' => '<h1>Allgemeine Geschäftsbedingungen</h1><p>§ 1 Geltungsbereich: Diese AGB gelten für alle Dienstleistungen und Mitgliedschaften des Vereins.</p><p>§ 2 Mitgliedschaft: Die Anmeldung erfolgt schriftlich oder digital. Die Kündigungsfrist beträgt 3 Monate zum Jahresende.</p>'
            ]);
            
            $stmt->execute([
                ':slug' => 'datenschutz',
                ':title' => 'Datenschutzerklärung',
                ':content' => '<h1>Datenschutzerklärung</h1><p>1. Datenschutz auf einen Blick: Der Schutz Ihrer persönlichen Daten ist uns ein wichtiges Anliegen.</p><p>2. Datenerfassung: Personenbezogene Daten werden nur zur Verwaltung der Mitgliedschaft und zur Organisation des Sportbetriebs erfasst und verarbeitet.</p>'
            ]);

            // Set installed flag in settings
            $stmt = $pdo->prepare("UPDATE settings SET value = '1' WHERE key = 'installed'");
            $stmt->execute();

            // Create lock file
            file_put_contents($lock_file, "Installed on " . date('Y-m-d H:i:s'));
            
            $success = true;
        } catch (Exception $e) {
            $errors[] = "Fehler bei der Installation: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Installation - Team Mania Pro</title>
    <style>
        :root {
            --bg-color: #0f172a;
            --card-bg: #1e293b;
            --text-color: #f8fafc;
            --text-muted: #94a3b8;
            --primary: #10b981;
            --primary-hover: #059669;
            --danger: #ef4444;
            --border: #334155;
        }
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, Roboto, Helvetica, Arial, sans-serif;
        }
        body {
            background-color: var(--bg-color);
            color: var(--text-color);
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            background-color: var(--card-bg);
            border: 1px solid var(--border);
            border-radius: 12px;
            width: 100%;
            max-width: 500px;
            padding: 40px;
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.3), 0 4px 6px -4px rgba(0, 0, 0, 0.3);
        }
        .logo-area {
            text-align: center;
            margin-bottom: 30px;
        }
        .logo-area h1 {
            font-size: 28px;
            color: var(--primary);
            font-weight: 800;
            letter-spacing: -0.5px;
        }
        .logo-area p {
            color: var(--text-muted);
            font-size: 14px;
            margin-top: 5px;
        }
        .error-box {
            background-color: rgba(239, 68, 68, 0.1);
            border: 1px solid var(--danger);
            color: #fca5a5;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
        }
        .error-box ul {
            margin-left: 20px;
        }
        .success-box {
            background-color: rgba(16, 185, 129, 0.1);
            border: 1px solid var(--primary);
            color: #a7f3d0;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
            text-align: center;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }
        label {
            display: block;
            margin-bottom: 8px;
            font-size: 13px;
            font-weight: 600;
            color: var(--text-muted);
        }
        input {
            width: 100%;
            padding: 12px;
            background-color: #0f172a;
            border: 1px solid var(--border);
            border-radius: 6px;
            color: #fff;
            font-size: 14px;
            transition: border-color 0.2s;
        }
        input:focus {
            outline: none;
            border-color: var(--primary);
        }
        .btn {
            display: block;
            width: 100%;
            padding: 14px;
            background-color: var(--primary);
            color: #fff;
            border: none;
            border-radius: 6px;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            text-align: center;
            text-decoration: none;
            transition: background-color 0.2s;
            margin-top: 25px;
        }
        .btn:hover {
            background-color: var(--primary-hover);
        }
        .btn-disabled {
            background-color: #475569;
            cursor: not-allowed;
        }
        .footer-note {
            text-align: center;
            margin-top: 30px;
            font-size: 11px;
            color: var(--text-muted);
        }
    </style>
</head>
<body>

<div class="container">
    <div class="logo-area">
        <h1>Team Mania PRO</h1>
        <p>Installations-Assistent</p>
    </div>

    <?php if (!empty($errors)): ?>
        <div class="error-box">
            <strong>Bitte beheben Sie folgende Fehler:</strong>
            <ul style="margin-top: 5px;">
                <?php foreach ($errors as $error): ?>
                    <li><?= htmlspecialchars($error) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <?php if ($success): ?>
        <div class="success-box">
            <h3 style="margin-bottom: 10px;">Installation erfolgreich!</h3>
            <p>Team Mania PRO wurde erfolgreich eingerichtet.</p>
            <a href="index.php" class="btn">Zum Login</a>
        </div>
    <?php else: ?>
        <form method="POST" action="">
            <div class="form-row">
                <div class="form-group">
                    <label for="first_name">Vorname</label>
                    <input type="text" id="first_name" name="first_name" value="<?= htmlspecialchars($_POST['first_name'] ?? '') ?>" required <?= (!$sqlite_ok || !$data_dir_writable || !$uploads_dir_writable) ? 'disabled' : '' ?>>
                </div>
                <div class="form-group">
                    <label for="last_name">Nachname</label>
                    <input type="text" id="last_name" name="last_name" value="<?= htmlspecialchars($_POST['last_name'] ?? '') ?>" required <?= (!$sqlite_ok || !$data_dir_writable || !$uploads_dir_writable) ? 'disabled' : '' ?>>
                </div>
            </div>

            <div class="form-group">
                <label for="username">Admin Benutzername</label>
                <input type="text" id="username" name="username" value="<?= htmlspecialchars($_POST['username'] ?? '') ?>" required <?= (!$sqlite_ok || !$data_dir_writable || !$uploads_dir_writable) ? 'disabled' : '' ?>>
            </div>

            <div class="form-group">
                <label for="email">Admin E-Mail</label>
                <input type="email" id="email" name="email" value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" required <?= (!$sqlite_ok || !$data_dir_writable || !$uploads_dir_writable) ? 'disabled' : '' ?>>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label for="password">Passwort</label>
                    <input type="password" id="password" name="password" required <?= (!$sqlite_ok || !$data_dir_writable || !$uploads_dir_writable) ? 'disabled' : '' ?>>
                </div>
                <div class="form-group">
                    <label for="password_confirm">Passwort bestätigen</label>
                    <input type="password" id="password_confirm" name="password_confirm" required <?= (!$sqlite_ok || !$data_dir_writable || !$uploads_dir_writable) ? 'disabled' : '' ?>>
                </div>
            </div>

            <?php if ($sqlite_ok && $data_dir_writable && $uploads_dir_writable): ?>
                <button type="submit" class="btn">Installation starten</button>
            <?php else: ?>
                <button type="button" class="btn btn-disabled" disabled>Installation blockiert</button>
            <?php endif; ?>
        </form>
    <?php endif; ?>

    <div class="footer-note">
        Powered by Team Mania PRO - development by sixdev for MORINA SOLUTIONS UG
    </div>
</div>

</body>
</html>
