<?php
/**
 * Shared user form fields (create & edit).
 * Expects: $formUser (optional for edit), $allRoles, $userRoles
 */
$fu        = $formUser ?? null;
$allRoles  = $allRoles ?? [];
$userRoles = $userRoles ?? ($_POST['roles'] ?? []);

// Auto-protection : interdire à un admin de retirer son propre app_admin
$isSelfEdit  = $fu && (int)($fu['id'] ?? 0) === (int)Session::get('user_id');
$selfHasApp  = $isSelfEdit && in_array(ROLE_APP_ADMIN, $userRoles, true);

// Grouper les rôles par module pour un affichage plus lisible
$rolesByModule = [];
foreach ($allRoles as $r) {
    $key = $r['module'] ?: '__system__';
    $rolesByModule[$key][] = $r;
}
?>

<div class="form-group">
    <label for="username"><?= t('auth.username') ?> *</label>
    <?php if ($fu): ?>
    <input type="text" value="<?= htmlspecialchars($fu['username']) ?>" disabled>
    <?php else: ?>
    <input type="text" id="username" name="username"
           value="<?= htmlspecialchars($_POST['username'] ?? '') ?>"
           required autocomplete="off">
    <?php endif; ?>
</div>

<div class="form-group">
    <label for="email"><?= t('user.email') ?></label>
    <input type="email" id="email" name="email"
           value="<?= htmlspecialchars($fu['email'] ?? $_POST['email'] ?? '') ?>">
</div>

<?php if (!$fu): ?>
<div class="form-group">
    <label for="password"><?= t('auth.password') ?> *</label>
    <input type="password" id="password" name="password" minlength="8" autocomplete="new-password">
</div>
<?php endif; ?>

<div class="form-group">
    <label><?= t('user.roles') ?> *</label>
    <?php foreach ($rolesByModule as $modKey => $modRoles): ?>
        <?php
            // Libellé du groupe (système ou nom du module)
            if ($modKey === '__system__') {
                $groupLabel = t('user.roles_system');
                $modActive  = true;
            } else {
                $modDesc    = $moduleRegistry->get($modKey);
                $groupLabel = $modDesc['label'] ?? $modKey;
                $modActive  = (bool)($modDesc['active'] ?? 0);
            }
            // Module désactivé : on ne PROPOSE pas ses profils. On préserve
            // toutefois ceux déjà attribués à l'utilisateur (champ caché) pour
            // ne pas les retirer lors d'une simple édition.
            if (!$modActive) {
                foreach ($modRoles as $r) {
                    if (in_array($r['name'], $userRoles, true)) {
                        echo '<input type="hidden" name="roles[]" value="'
                           . htmlspecialchars($r['name']) . '">';
                    }
                }
                continue;
            }
        ?>
        <fieldset style="border:1px solid var(--color-border,#ddd);border-radius:4px;padding:.4rem .75rem;margin-bottom:.5rem">
            <legend style="font-size:.82rem;padding:0 .35rem">
                <?= htmlspecialchars($groupLabel) ?>
            </legend>
            <?php foreach ($modRoles as $r): ?>
                <?php
                    $checked = in_array($r['name'], $userRoles, true);
                    $isLockedSelfApp = $isSelfEdit && $r['name'] === ROLE_APP_ADMIN && $selfHasApp;
                ?>
                <label style="display:inline-block;margin-right:1rem">
                    <input type="checkbox" name="roles[]" value="<?= htmlspecialchars($r['name']) ?>"
                           <?= $checked ? 'checked' : '' ?>
                           <?= $isLockedSelfApp ? 'disabled' : '' ?>>
                    <?= htmlspecialchars(t('role.' . $r['name'])) ?>
                    <?php if ($isLockedSelfApp): ?>
                        <small style="color:var(--color-text-muted)">— <?= t('user.role_self_locked') ?></small>
                        <input type="hidden" name="roles[]" value="<?= ROLE_APP_ADMIN ?>">
                    <?php endif; ?>
                </label>
            <?php endforeach; ?>
        </fieldset>
    <?php endforeach; ?>
    <small><?= t('user.roles_hint') ?></small>
</div>

<div class="form-group">
    <label for="auth_method"><?= t('auth.method') ?></label>
    <select id="auth_method" name="auth_method">
        <?php foreach ([AUTH_LOCAL, AUTH_OAUTH, AUTH_LDAP] as $m): ?>
        <option value="<?= $m ?>"
            <?= (($fu['auth_method'] ?? $_POST['auth_method'] ?? AUTH_LOCAL) === $m) ? 'selected' : '' ?>>
            <?= t('auth.method_' . $m) ?>
        </option>
        <?php endforeach; ?>
    </select>
</div>

<div class="form-group">
    <label for="language"><?= t('user.language') ?></label>
    <select id="language" name="language">
        <option value=""><?= t('settings.default_lang') ?></option>
        <?php foreach (LANGUAGES as $code): ?>
        <option value="<?= $code ?>"
            <?= (($fu['language'] ?? null) === $code) ? 'selected' : '' ?>>
            <?= t('lang.' . $code) ?>
        </option>
        <?php endforeach; ?>
    </select>
</div>

<div class="form-group">
    <label for="theme"><?= t('user.theme') ?></label>
    <select id="theme" name="theme">
        <option value=""><?= t('settings.default_theme') ?></option>
        <?php foreach (THEMES as $themeKey): ?>
        <option value="<?= $themeKey ?>"
            <?= (($fu['theme'] ?? null) === $themeKey) ? 'selected' : '' ?>>
            <?= t('theme.' . $themeKey) ?>
        </option>
        <?php endforeach; ?>
    </select>
</div>

<div class="form-group form-check">
    <input type="checkbox" id="active" name="active" value="1"
           <?= (($fu['active'] ?? 1) ? 'checked' : '') ?>>
    <label for="active"><?= t('user.active') ?></label>
</div>
