<?php ob_start(); ?>
<?php
$isEdit      = !empty($user);
$userId      = $isEdit ? (int) $user['id'] : 0;
$isSelf      = $isEdit && ($userId === $auth->userId());
$isOnlyAdmin = $isOnlyAdmin ?? false;
$old         = $old ?? $user ?? [];
$errors      = $errors ?? [];

$v = function(string $key, string $default = '') use ($old): string {
    return e($old[$key] ?? $default);
};
$err = function(string $key) use ($errors): string {
    return isset($errors[$key])
        ? '<span class="field-error">' . e($errors[$key]) . '</span>'
        : '';
};
?>

<?php admin_content_header($isEdit ? __('admin.users.edit') : __('admin.users.create'), 'users', [
    ['url' => admin_url('users'), 'label' => __('admin.users.back')],
]); ?>

<div class="form-layout">
    <form method="POST"
          action="<?= $isEdit ? admin_url('users/update/' . $userId) : admin_url('users/store') ?>"
          class="admin-form" autocomplete="off">

        <?= $csrf->field() ?>

        <div class="form-grid-2">

            <!-- ─── Left column ────────────────────── -->
            <div class="form-main">

                <div class="form-group <?= isset($errors['username']) ? 'has-error' : '' ?>">
                    <label for="username"><?= __('admin.users.username') ?> <span class="required">*</span></label>
                    <input type="text" id="username" name="username"
                           value="<?= $v('username') ?>"
                           required minlength="3"
                           pattern="[a-zA-Z0-9_\-]+"
                           title="<?= __('admin.users.username_hint') ?>"
                           autocomplete="off">
                    <?= $err('username') ?>
                    <small class="field-hint"><?= __('admin.users.username_help') ?></small>
                </div>

                <div class="form-group <?= isset($errors['email']) ? 'has-error' : '' ?>">
                    <label for="email"><?= __('admin.users.email') ?> <span class="required">*</span></label>
                    <input type="email" id="email" name="email"
                           value="<?= $v('email') ?>"
                           required autocomplete="off">
                    <?= $err('email') ?>
                </div>

                <div class="form-group <?= isset($errors['password']) ? 'has-error' : '' ?>">
                    <label for="password">
                        <?= __('admin.users.password') ?>
                        <?php if (!$isEdit): ?><span class="required">*</span><?php endif; ?>
                    </label>
                    <div class="input-password-wrap">
                        <input type="password" id="password" name="password"
                               value=""
                               <?= $isEdit ? '' : 'required' ?>
                               minlength="<?= \App\Core\Auth::MIN_PASSWORD_LENGTH ?>"
                               autocomplete="new-password">
                        <button type="button" class="password-toggle" aria-label="<?= __('auth.login_show_password') ?>">
                            <span class="icon-eye"><?= icon('eye', 18) ?></span>
                            <span class="icon-eye-off" style="display:none"><?= icon('eye-off', 18) ?></span>
                        </button>
                    </div>
                    <?= $err('password') ?>
                    <?php if ($isEdit): ?>
                    <small class="field-hint"><?= __('admin.users.password_help_edit') ?></small>
                    <?php else: ?>
                    <small class="field-hint"><?= __('admin.users.password_help_create') ?></small>
                    <?php endif; ?>
                </div>

            </div>

            <!-- ─── Right column (sidebar) ─────────── -->
            <div class="form-sidebar">

                <div class="sidebar-box">
                    <h3 class="sidebar-box__title"><?= __('admin.users.account_settings') ?></h3>

                    <div class="form-group <?= isset($errors['role']) ? 'has-error' : '' ?>">
                        <label for="role"><?= __('admin.users.role') ?></label>
                        <select id="role" name="role"
                                <?= ($isSelf && $isOnlyAdmin) ? 'disabled' : '' ?>>
                            <option value="editor" <?= ($v('role') === 'editor') ? 'selected' : '' ?>><?= __('admin.users.role_editor') ?></option>
                            <option value="admin"  <?= ($v('role') === 'admin')  ? 'selected' : '' ?>><?= __('admin.users.role_admin') ?></option>
                        </select>
                        <?php if ($isSelf && $isOnlyAdmin): ?>
                        <!-- Hidden fallback so form still submits the correct value when select is disabled -->
                        <input type="hidden" name="role" value="admin">
                        <?php endif; ?>
                        <?= $err('role') ?>
                        <?php if ($isSelf && $isOnlyAdmin): ?>
                        <small class="field-hint" style="color:#f59e0b;">&#9888; <?= __('admin.users.role_only_admin') ?></small>
                        <?php else: ?>
                        <small class="field-hint">
                            <?= __('admin.users.role_help') ?>
                        </small>
                        <?php endif; ?>
                    </div>

                    <div class="form-group <?= isset($errors['is_active']) ? 'has-error' : '' ?>">
                        <label class="checkbox-label">
                            <?php if ($isSelf): ?>
                            <!-- Self-edit: always keep active (cannot deactivate yourself) -->
                            <input type="hidden" name="is_active" value="1">
                            <?php else: ?>
                            <input type="hidden" name="is_active" value="0">
                            <?php endif; ?>
                            <input type="checkbox" name="is_active" value="1"
                                   <?= ((int) ($old['is_active'] ?? 1)) ? 'checked' : '' ?>
                                   <?= $isSelf ? 'disabled' : '' ?>>
                            <?= __('admin.users.active_account') ?>
                        </label>
                        <?= $err('is_active') ?>
                        <?php if ($isSelf): ?>
                        <small class="field-hint" style="color:#f59e0b;">&#9888; <?= __('admin.users.cannot_deactivate') ?></small>
                        <?php endif; ?>
                    </div>

                    <?php if ($isEdit): ?>
                    <div class="form-meta text-muted">
                        <?php if (!empty($user['created_at'])): ?>
                        <small><?= __('admin.users.created_at', [':date' => e(format_date($user['created_at'], 'd.m.Y H:i'))]) ?></small><br>
                        <?php endif; ?>
                        <?php if (!empty($user['updated_at'])): ?>
                        <small><?= __('admin.users.updated_at', [':date' => e(format_date($user['updated_at'], 'd.m.Y H:i'))]) ?></small>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                </div>

                <div class="sidebar-actions">
                    <button type="submit" class="btn btn-primary btn-full">
                        <?= $isEdit ? __('admin.common.save') : __('admin.users.create_btn') ?>
                    </button>
                    <a href="<?= admin_url('users') ?>" class="btn btn-secondary btn-full"><?= __('admin.common.cancel') ?></a>
                </div>

            </div>
        </div>

    </form>
</div>

<style>
.form-grid-2 {
    display: grid;
    grid-template-columns: 1fr 320px;
    gap: 2rem;
    align-items: start;
}
@media (max-width: 768px) { .form-grid-2 { grid-template-columns: 1fr; } }

.sidebar-box {
    background: #f8f9fa;
    border: 1px solid var(--border-color, #e0e0e0);
    border-radius: 6px;
    padding: 1.25rem;
    margin-bottom: 1rem;
}
.sidebar-box__title {
    font-size: .95rem;
    font-weight: 600;
    margin: 0 0 1rem;
    padding-bottom: .5rem;
    border-bottom: 1px solid var(--border-color, #e0e0e0);
}
.sidebar-actions { display: flex; flex-direction: column; gap: .5rem; }
.btn-full { width: 100%; text-align: center; }

.checkbox-label {
    display: flex;
    align-items: center;
    gap: .5rem;
    cursor: pointer;
    font-weight: normal;
}
.checkbox-label input[type="checkbox"] { width: 16px; height: 16px; }
.form-meta { padding-top: .75rem; border-top: 1px solid var(--border-color, #e0e0e0); margin-top: .75rem; }

.field-error { display: block; color: #dc2626; font-size: .82rem; margin-top: .25rem; }
.has-error input, .has-error select { border-color: #dc2626 !important; }
.field-hint { display: block; color: var(--text-muted, #6c757d); font-size: .8rem; margin-top: .25rem; }
.required { color: #dc2626; }
</style>

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