<?php
require_once __DIR__ . '/bootstrap.php';

$pdo = $GLOBALS['pdo'];

$userCount = $pdo->query("SELECT COUNT(*) as count FROM users")->fetch();
if (($userCount['count'] ?? 0) > 0) {
    header('Location: /admin/login.php');
    exit;
}

$errorMessage = null;
$successMessage = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf_token'] ?? '';
    if (!\Core\Auth::verifyCsrfToken($token)) {
        http_response_code(403);
        die('CSRF token validation failed.');
    }

    $siteTitle = trim($_POST['site_title'] ?? '');
    $siteUrl = trim($_POST['site_url'] ?? '');
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = trim($_POST['password'] ?? '');
    $passwordConfirm = trim($_POST['password_confirm'] ?? '');

    if ($siteTitle === '' || $username === '' || $email === '' || $password === '' || $passwordConfirm === '') {
        $errorMessage = 'All fields are required.';
    } elseif ($password !== $passwordConfirm) {
        $errorMessage = 'Passwords do not match.';
    } elseif (strlen($password) < 8) {
        $errorMessage = 'Password must be at least 8 characters long.';
    } else {
        $hash = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("INSERT INTO users (username, password, email, role) VALUES (?, ?, ?, 'admin')");
        $stmt->execute([$username, $hash, $email]);

        \Models\Meta::set(0, 'site', 'site_title', $siteTitle);
        if ($siteUrl !== '') {
            \Models\Meta::set(0, 'site', 'site_url', $siteUrl);
        }
        \Models\Meta::set(0, 'site', 'admin_email', $email);

        $successMessage = 'Installation complete. You can now log in.';
    }
}

$pageTitle = 'Install';
$currentPage = '';

ob_start();
?>

<div class="columns">
    <div class="column is-6 is-offset-3">
        <div class="admin-card">
            <h2 class="card-header-title">
                <span class="icon mr-2"><i class="fas fa-rocket"></i></span>
                Initial Setup
            </h2>
            <p class="mb-4">
                Create your admin account and set basic site information.
            </p>
            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?= \Core\Auth::generateCsrfToken() ?>">

                <div class="field">
                    <label class="label">Site Title</label>
                    <div class="control">
                        <input class="input" type="text" name="site_title" required>
                    </div>
                </div>

                <div class="field">
                    <label class="label">Site URL</label>
                    <div class="control">
                        <input class="input" type="url" name="site_url" placeholder="https://example.com">
                    </div>
                </div>

                <div class="field">
                    <label class="label">Admin Username</label>
                    <div class="control">
                        <input class="input" type="text" name="username" required>
                    </div>
                </div>

                <div class="field">
                    <label class="label">Admin Email</label>
                    <div class="control">
                        <input class="input" type="email" name="email" required>
                    </div>
                </div>

                <div class="field">
                    <label class="label">Password</label>
                    <div class="control">
                        <input class="input" type="password" name="password" required>
                    </div>
                </div>

                <div class="field">
                    <label class="label">Confirm Password</label>
                    <div class="control">
                        <input class="input" type="password" name="password_confirm" required>
                    </div>
                </div>

                <div class="field">
                    <div class="control">
                        <button type="submit" class="button is-primary">
                            Complete Installation
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<?php
$content = ob_get_clean();
include __DIR__ . '/layouts/admin_layout.php';
