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

if (!(defined('ALLOW_PUBLIC_REGISTRATION') && ALLOW_PUBLIC_REGISTRATION)) {
    http_response_code(403);
    exit('Javna registracija je isključena. Administrator treba da kreira nalog.');
}

if (current_user()) {
    redirect('dashboard.php');
}

$authPage = true;
$pageTitle = 'Registracija';
$pageSubtitle = 'Kreiranje korisničkog naloga';
$errors = [];

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) < 10) {
        $errors[] = 'Lozinka mora imati najmanje 10 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 (?, ?, ?, 0, 1, NOW(), NOW())');
            $stmt->execute([$name, $email, password_hash($password, PASSWORD_DEFAULT)]);
            $registeredRole = defined('DEFAULT_REGISTERED_ROLE') ? strtoupper((string)DEFAULT_REGISTERED_ROLE) : base_user_role_code();
            if ($registeredRole === 'USER') {
                $registeredRole = base_user_role_code();
            }
            if (!in_array($registeredRole, base_user_role_codes(), true)) {
                $registeredRole = base_user_role_code();
            }
            sync_user_roles(db(), (int)db()->lastInsertId(), normalize_role_codes([$registeredRole]), 0);
            db()->commit();
            flash('success', 'Nalog je kreiran. Možete da se prijavite.');
            redirect('login.php');
        } catch (Throwable $e) {
            if (db()->inTransaction()) {
                db()->rollBack();
            }
            $errors[] = $e instanceof PDOException && (string)$e->getCode() === '23000'
                ? 'Email adresa je već registrovana.'
                : 'Nalog nije kreiran. Proverite da li je importovana migracija upgrade_v3_16.sql.';
        }
    }
}

require_once __DIR__ . '/app/header.php';
?>
<form method="post" class="card login-card form-card">
    <?= csrf_field() ?>
    <span class="badge">Registracija</span>
    <h2>Kreiranje naloga</h2>
    <p class="muted">Javna registracija treba da bude uključena samo ako za to postoji jasna interna potreba.</p>

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

    <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="10">
    </label>
    <button class="button button-primary" type="submit">Kreiraj nalog</button>
    <p class="muted"><a href="<?= e(url('login.php')) ?>">Nazad na prijavu</a></p>
</form>
<?php require_once __DIR__ . '/app/footer.php'; ?>
