<?php require dirname(__DIR__) . '/layouts/app.php'; ?>

<?php $isEdit = !empty($formUser['id']); ?>

<section class="page-heading">
    <div>
        <p class="eyebrow">Administration</p>
        <h1><?= $isEdit ? 'Modifier utilisateur' : 'Ajouter utilisateur' ?></h1>
    </div>
    <a class="button-link secondary" href="<?= url('/users') ?>">Retour</a>
</section>

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

<form class="form-panel" method="post" action="<?= url($isEdit ? '/users/update' : '/users/store') ?>">
    <input type="hidden" name="_token" value="<?= csrf_token() ?>">
    <?php if ($isEdit): ?>
        <input type="hidden" name="id" value="<?= (int) $formUser['id'] ?>">
    <?php endif; ?>

    <div class="form-grid">
        <label>
            Nom
            <input type="text" name="name" value="<?= e($formUser['name']) ?>" required>
        </label>

        <label>
            Email
            <input type="email" name="email" value="<?= e($formUser['email']) ?>" required>
        </label>

        <label>
            Mot de passe
            <input type="password" name="password" <?= $isEdit ? '' : 'required' ?>>
        </label>

        <label>
            Role
            <select name="role">
                <option value="admin" <?= $formUser['role'] === 'admin' ? 'selected' : '' ?>>Administrateur</option>
                <option value="manager" <?= $formUser['role'] === 'manager' ? 'selected' : '' ?>>Gestionnaire</option>
            </select>
        </label>

        <label>
            Statut
            <select name="status">
                <option value="active" <?= $formUser['status'] === 'active' ? 'selected' : '' ?>>Actif</option>
                <option value="inactive" <?= $formUser['status'] === 'inactive' ? 'selected' : '' ?>>Inactif</option>
            </select>
        </label>
    </div>

    <section class="permissions-panel">
        <h2>Permissions</h2>
        <div class="permission-grid">
            <?php foreach ($permissions as $key => $label): ?>
                <label class="check-row">
                    <input
                        type="checkbox"
                        name="permissions[]"
                        value="<?= e($key) ?>"
                        <?= in_array($key, $formUser['permissions'], true) ? 'checked' : '' ?>
                    >
                    <span><?= e($label) ?></span>
                </label>
            <?php endforeach; ?>
        </div>
    </section>

    <div class="form-actions">
        <button type="submit"><?= $isEdit ? 'Enregistrer' : 'Ajouter' ?></button>
    </div>
</form>

<?php require dirname(__DIR__) . '/layouts/app_footer.php'; ?>
