<?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>'
        : '';
};
?>

<div class="content-header">
    <h2><?= $isEdit ? __('admin.users.edit') : __('admin.users.create') ?></h2>
    <div class="header-actions">
        <a href="/admin/users" class="btn btn-secondary"><- <?= __('admin.users.back') ?></a>
    </div>
</div>

<div class="form-layout">
    <form method="POST"
          action="<?= $isEdit ? '/admin/users/update/' . $userId : '/admin/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>
                    <input type="password" id="password" name="password"
                           value=""
                           <?= $isEdit ? '' : 'required' ?>
                           minlength="8"
                           autocomplete="new-password">
                    <?= $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/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'; ?>
