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

$stmt = db()->query('SELECT COUNT(*) AS total FROM users WHERE is_system_admin = 1');
$adminCount = (int)$stmt->fetch()['total'];
$authPage = true;
$pageTitle = 'Prvo podešavanje';
$pageSubtitle = 'Kreiranje prvog administratorskog naloga';
$errors = [];
$created = false;

if ($adminCount > 0) {
    require_once __DIR__ . '/app/header.php';
    ?>
    <section class="card login-card">
        <span class="badge badge-warning">Zaključano</span>
        <h2>Administrator već postoji</h2>
        <p class="muted">Iz bezbednosnih razloga obrišite <code>create_admin.php</code> sa hostinga nakon prvog podešavanja.</p>
        <a class="button button-primary" href="<?= e(url('login.php')) ?>">Idi na prijavu</a>
    </section>
    <?php
    require_once __DIR__ . '/app/footer.php';
    exit;
}

if (is_post()) {
    validate_csrf();
    $name = trim((string)($_POST['name'] ?? ''));
    $email = strtolower(trim((string)($_POST['email'] ?? '')));
    $password = (string)($_POST['password'] ?? '');

    if (mb_strlen($name) < 2) {
        $errors[] = 'Ime mora imati najmanje 2 karaktera.';
    }
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Unesite validnu email adresu.';
    }
    if (strlen($password) < 12) {
        $errors[] = 'Administratorska lozinka mora imati najmanje 12 karaktera.';
    }

    if (!$errors) {
        try {
            db()->beginTransaction();
            $stmt = db()->prepare('INSERT INTO users (name, email, password_hash, is_system_admin, is_active, created_at, updated_at) VALUES (?, ?, ?, 1, 1, NOW(), NOW())');
            $stmt->execute([$name, $email, password_hash($password, PASSWORD_DEFAULT)]);
            $newAdminId = (int)db()->lastInsertId();
            sync_user_roles(db(), $newAdminId, ['USERF'], $newAdminId);
            db()->commit();
            $created = true;
        } catch (Throwable $e) {
            if (db()->inTransaction()) {
                db()->rollBack();
            }
            $errors[] = 'Administrator nije kreiran. Proverite da li je importovana poslednja SQL šema.';
        }
    }
}

require_once __DIR__ . '/app/header.php';
?>
<section class="card login-card">
    <?php if ($created): ?>
        <span class="badge badge-success">Kreirano</span>
        <h2>Administrator je kreiran</h2>
        <p class="muted">Sada obrišite <code>create_admin.php</code> sa servera, pa se prijavite.</p>
        <a class="button button-primary" href="<?= e(url('login.php')) ?>">Idi na prijavu</a>
    <?php else: ?>
        <span class="badge">Prvo podešavanje</span>
        <h2>Kreiranje administratora</h2>
        <p class="muted">Ova stranica radi samo dok u bazi ne postoji administratorski nalog.</p>
        <?php foreach ($errors as $error): ?>
            <div class="alert alert-danger"><?= e($error) ?></div>
        <?php endforeach; ?>
        <form method="post" class="stacked-form">
            <?= csrf_field() ?>
            <label>Ime i prezime
                <input type="text" name="name" required value="<?= e($_POST['name'] ?? '') ?>">
            </label>
            <label>Email adresa
                <input type="email" name="email" required value="<?= e($_POST['email'] ?? '') ?>">
            </label>
            <label>Lozinka
                <input type="password" name="password" required minlength="12">
            </label>
            <button class="button button-primary" type="submit">Kreiraj administratora</button>
        </form>
    <?php endif; ?>
</section>
<?php require_once __DIR__ . '/app/footer.php'; ?>
