<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<div class="d-flex align-items-center justify-content-between mb-3">
    <small class="text-muted"><i class="bi bi-person-gear me-1"></i>Kelola akun admin, superadmin, dan operator</small>
    <div class="d-flex gap-2">
        <button class="btn btn-outline-secondary btn-sm" data-bs-toggle="modal" data-bs-target="#modalChangePassword">
            <i class="bi bi-key me-1"></i>Ganti Password
        </button>
        <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#modalTambah">
            <i class="bi bi-plus-circle me-1"></i>Tambah Admin
        </button>
    </div>
</div>

    <!-- Tabel User -->
    <div class="card border-0 shadow-sm">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0" id="tableUser">
                    <thead class="table-light">
                        <tr>
                            <th width="50" class="ps-3">No</th>
                            <th>Nama</th>
                            <th>Username</th>
                            <th>Email</th>
                            <th width="120">Role</th>
                            <th width="110">Status</th>
                            <th width="200" class="text-center">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($users)): ?>
                        <tr>
                            <td colspan="7" class="text-center py-4 text-muted">Belum ada data user.</td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($users as $i => $u): ?>
                        <tr id="row-<?= $u['id'] ?>">
                            <td class="ps-3"><?= $i + 1 ?></td>
                            <td class="fw-semibold"><?= esc($u['name']) ?></td>
                            <td><code><?= esc($u['username']) ?></code></td>
                            <td><?= esc($u['email'] ?? '-') ?></td>
                            <td>
                                <?php
                                $roleClass = match($u['role']) {
                                    'superadmin' => 'bg-primary',
                                    'admin'      => 'bg-success',
                                    'tata_usaha' => 'bg-info text-dark',
                                    'kamad'      => 'bg-warning text-dark',
                                    default      => 'bg-secondary',
                                };
                                ?>
                                <span class="badge <?= $roleClass ?>"><?= ucfirst($u['role']) ?></span>
                            </td>
                            <td>
                                <span class="badge badge-status-<?= $u['id'] ?> <?= $u['is_active'] ? 'bg-success' : 'bg-danger' ?>">
                                    <?= $u['is_active'] ? 'Aktif' : 'Nonaktif' ?>
                                </span>
                            </td>
                            <td class="text-center">
                                <!-- Edit -->
                                <button class="btn btn-sm btn-outline-primary py-0 px-2 me-1"
                                    title="Edit"
                                    onclick="openEdit(<?= $u['id'] ?>, '<?= esc($u['name'], 'js') ?>', '<?= esc($u['email'] ?? '', 'js') ?>', '<?= $u['role'] ?>', <?= $u['is_active'] ?>)">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <!-- Reset Password -->
                                <button class="btn btn-sm btn-outline-warning py-0 px-2 me-1"
                                    title="Reset Password"
                                    onclick="openReset(<?= $u['id'] ?>, '<?= esc($u['name'], 'js') ?>')">
                                    <i class="bi bi-shield-lock"></i>
                                </button>
                                <?php if ((int)$u['id'] !== (int)session('user_id')): ?>
                                <!-- Toggle Aktif -->
                                <button class="btn btn-sm btn-outline-secondary py-0 px-2 me-1 btn-toggle-<?= $u['id'] ?>"
                                    title="Toggle Aktif/Nonaktif"
                                    onclick="toggleActive(<?= $u['id'] ?>, '<?= esc($u['name'], 'js') ?>')">
                                    <i class="bi <?= $u['is_active'] ? 'bi-toggle-on' : 'bi-toggle-off' ?>"></i>
                                </button>
                                <!-- Hapus -->
                                <button class="btn btn-sm btn-outline-danger py-0 px-2"
                                    title="Hapus"
                                    onclick="deleteUser(<?= $u['id'] ?>, '<?= esc($u['name'], 'js') ?>')">
                                    <i class="bi bi-trash"></i>
                                </button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

<!-- ══════════════════════════════════════════════════════════════ -->
<!-- MODAL: TAMBAH USER -->
<!-- ══════════════════════════════════════════════════════════════ -->
<div class="modal fade" id="modalTambah" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-person-plus me-2"></i>Tambah User</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="formTambah">
                <?= csrf_field() ?>
                <div class="modal-body">
                    <div id="alertTambah"></div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Nama Lengkap <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="name" required placeholder="Nama lengkap">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Username <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="username" required placeholder="Username unik">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Email</label>
                        <input type="email" class="form-control" name="email" placeholder="Email (opsional)">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Role <span class="text-danger">*</span></label>
                        <select class="form-select" name="role" required>
                            <option value="">-- Pilih Role --</option>
                            <option value="superadmin">Superadmin</option>
                            <option value="admin">Admin</option>
                            <option value="operator">Operator</option>
                            <option value="tata_usaha">Tata Usaha</option>
                            <option value="kamad">Kepala Sekolah (Kamad)</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Password <span class="text-danger">*</span></label>
                        <input type="password" class="form-control" name="password" required placeholder="Minimal 6 karakter">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Konfirmasi Password <span class="text-danger">*</span></label>
                        <input type="password" class="form-control" name="password_confirm" required placeholder="Ulangi password">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary" id="btnTambah">
                        <span class="spinner-border spinner-border-sm d-none me-1" id="spinnerTambah"></span>
                        Simpan
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ══════════════════════════════════════════════════════════════ -->
<!-- MODAL: EDIT USER -->
<!-- ══════════════════════════════════════════════════════════════ -->
<div class="modal fade" id="modalEdit" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-pencil-square me-2"></i>Edit User</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="formEdit">
                <?= csrf_field() ?>
                <input type="hidden" name="edit_id" id="editId">
                <div class="modal-body">
                    <div id="alertEdit"></div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Nama Lengkap <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="name" id="editName" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Email</label>
                        <input type="email" class="form-control" name="email" id="editEmail" placeholder="Email (opsional)">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Role <span class="text-danger">*</span></label>
                        <select class="form-select" name="role" id="editRole" required>
                            <option value="superadmin">Superadmin</option>
                            <option value="admin">Admin</option>
                            <option value="operator">Operator</option>
                            <option value="tata_usaha">Tata Usaha</option>
                            <option value="kamad">Kepala Sekolah (Kamad)</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Status</label>
                        <select class="form-select" name="is_active" id="editIsActive">
                            <option value="1">Aktif</option>
                            <option value="0">Nonaktif</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary" id="btnEdit">
                        <span class="spinner-border spinner-border-sm d-none me-1" id="spinnerEdit"></span>
                        Simpan
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ══════════════════════════════════════════════════════════════ -->
<!-- MODAL: RESET PASSWORD (untuk user lain) -->
<!-- ══════════════════════════════════════════════════════════════ -->
<div class="modal fade" id="modalReset" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-shield-lock me-2"></i>Reset Password</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="formReset">
                <?= csrf_field() ?>
                <input type="hidden" name="reset_id" id="resetId">
                <div class="modal-body">
                    <div id="alertReset"></div>
                    <p class="text-muted mb-3">Reset password untuk: <strong id="resetName"></strong></p>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Password Baru <span class="text-danger">*</span></label>
                        <input type="password" class="form-control" name="new_password" required placeholder="Minimal 6 karakter">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Konfirmasi Password Baru <span class="text-danger">*</span></label>
                        <input type="password" class="form-control" name="new_password_confirm" required placeholder="Ulangi password baru">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-warning" id="btnReset">
                        <span class="spinner-border spinner-border-sm d-none me-1" id="spinnerReset"></span>
                        Reset Password
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- ══════════════════════════════════════════════════════════════ -->
<!-- MODAL: GANTI PASSWORD SENDIRI -->
<!-- ══════════════════════════════════════════════════════════════ -->
<div class="modal fade" id="modalChangePassword" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-key me-2"></i>Ganti Password Saya</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="formChangePassword">
                <?= csrf_field() ?>
                <div class="modal-body">
                    <div id="alertChangePassword"></div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Password Lama <span class="text-danger">*</span></label>
                        <input type="password" class="form-control" name="old_password" required placeholder="Password saat ini">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Password Baru <span class="text-danger">*</span></label>
                        <input type="password" class="form-control" name="new_password" required placeholder="Minimal 6 karakter">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Konfirmasi Password Baru <span class="text-danger">*</span></label>
                        <input type="password" class="form-control" name="new_password_confirm" required placeholder="Ulangi password baru">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary" id="btnChangePassword">
                        <span class="spinner-border spinner-border-sm d-none me-1" id="spinnerChangePassword"></span>
                        Simpan
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
// ── CSRF helper ───────────────────────────────────────────────────────────
function getCsrfToken() {
    const meta = document.querySelector('meta[name="csrf-token"]');
    return meta ? meta.content : '';
}

function getCsrfName() {
    const meta = document.querySelector('meta[name="csrf-name"]');
    return meta ? meta.content : '<?= csrf_token() ?>';
}

function buildHeaders() {
    const headers = { 'X-Requested-With': 'XMLHttpRequest' };
    headers[getCsrfName()] = getCsrfToken();
    return headers;
}

// ── Alert helper ──────────────────────────────────────────────────────────
function showAlert(containerId, type, message) {
    const el = document.getElementById(containerId);
    el.innerHTML = `<div class="alert alert-${type} py-2 mb-3"><i class="bi bi-${type === 'success' ? 'check-circle' : 'exclamation-circle'} me-2"></i>${message}</div>`;
}

function clearAlert(containerId) {
    document.getElementById(containerId).innerHTML = '';
}

// ── Open modals ───────────────────────────────────────────────────────────
function openEdit(id, name, email, role, isActive) {
    document.getElementById('editId').value       = id;
    document.getElementById('editName').value     = name;
    document.getElementById('editEmail').value    = email;
    document.getElementById('editRole').value     = role;
    document.getElementById('editIsActive').value = isActive;
    clearAlert('alertEdit');
    new bootstrap.Modal(document.getElementById('modalEdit')).show();
}

function openReset(id, name) {
    document.getElementById('resetId').value   = id;
    document.getElementById('resetName').textContent = name;
    document.getElementById('formReset').reset();
    clearAlert('alertReset');
    new bootstrap.Modal(document.getElementById('modalReset')).show();
}

// ── AJAX submit helper ────────────────────────────────────────────────────
async function ajaxSubmit(url, formData, alertId, btnId, spinnerId, onSuccess) {
    const btn     = document.getElementById(btnId);
    const spinner = document.getElementById(spinnerId);
    btn.disabled  = true;
    spinner.classList.remove('d-none');
    clearAlert(alertId);

    try {
        const res  = await fetch(url, {
            method: 'POST',
            headers: buildHeaders(),
            body: formData,
        });
        const data = await res.json();

        if (data.success) {
            showAlert(alertId, 'success', data.message || 'Proses berhasil.');
            if (typeof onSuccess === 'function') onSuccess(data);
        } else {
            showAlert(alertId, 'danger', data.message || data.error || 'Terjadi kesalahan sistem.');
        }
    } catch (e) {
        showAlert(alertId, 'danger', 'Terjadi kesalahan jaringan. Silakan coba lagi.');
    } finally {
        btn.disabled = false;
        spinner.classList.add('d-none');
    }
}

// ── Form: Tambah User ─────────────────────────────────────────────────────
document.getElementById('formTambah').addEventListener('submit', async function(e) {
    e.preventDefault();
    await ajaxSubmit(
        '/user-management/store',
        new FormData(this),
        'alertTambah', 'btnTambah', 'spinnerTambah',
        () => setTimeout(() => location.reload(), 1200)
    );
});

// ── Form: Edit User ───────────────────────────────────────────────────────
document.getElementById('formEdit').addEventListener('submit', async function(e) {
    e.preventDefault();
    const id = document.getElementById('editId').value;
    await ajaxSubmit(
        `/user-management/update/${id}`,
        new FormData(this),
        'alertEdit', 'btnEdit', 'spinnerEdit',
        () => setTimeout(() => location.reload(), 1200)
    );
});

// ── Form: Reset Password ──────────────────────────────────────────────────
document.getElementById('formReset').addEventListener('submit', async function(e) {
    e.preventDefault();
    const id = document.getElementById('resetId').value;
    await ajaxSubmit(
        `/user-management/reset-password/${id}`,
        new FormData(this),
        'alertReset', 'btnReset', 'spinnerReset',
        () => {
            setTimeout(() => {
                bootstrap.Modal.getInstance(document.getElementById('modalReset')).hide();
            }, 1200);
        }
    );
});

// ── Form: Ganti Password Sendiri ──────────────────────────────────────────
document.getElementById('formChangePassword').addEventListener('submit', async function(e) {
    e.preventDefault();
    await ajaxSubmit(
        '/user-management/change-password',
        new FormData(this),
        'alertChangePassword', 'btnChangePassword', 'spinnerChangePassword',
        () => {
            this.reset();
            setTimeout(() => {
                bootstrap.Modal.getInstance(document.getElementById('modalChangePassword')).hide();
            }, 1200);
        }
    );
});

// ── Toggle Aktif ──────────────────────────────────────────────────────────
function toggleActive(id, name) {
    Swal.fire({
        title: 'Toggle Status Akun',
        text: `Ubah status aktif/nonaktif untuk "${name}"?`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#0d6efd',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Ya, ubah!',
        cancelButtonText: 'Batal',
    }).then(async (result) => {
        if (!result.isConfirmed) return;

        try {
            const res  = await fetch(`/user-management/toggle-active/${id}`, {
                headers: buildHeaders(),
            });
            const data = await res.json();

            if (data.success) {
                // Update badge status di tabel
                const badge = document.querySelector(`.badge-status-${id}`);
                if (badge) {
                    badge.className = `badge badge-status-${id} ${data.is_active ? 'bg-success' : 'bg-danger'}`;
                    badge.textContent = data.is_active ? 'Aktif' : 'Nonaktif';
                }
                // Update icon tombol toggle
                const toggleBtn = document.querySelector(`.btn-toggle-${id} i`);
                if (toggleBtn) {
                    toggleBtn.className = `bi ${data.is_active ? 'bi-toggle-on' : 'bi-toggle-off'}`;
                }
                Swal.fire({ icon: 'success', title: 'Berhasil', text: data.message, timer: 1500, showConfirmButton: false });
            } else {
                Swal.fire({ icon: 'error', title: 'Gagal', text: data.message });
            }
        } catch (e) {
            Swal.fire({ icon: 'error', title: 'Error', text: 'Terjadi kesalahan jaringan.' });
        }
    });
}

// ── Hapus User ────────────────────────────────────────────────────────────
function deleteUser(id, name) {
    Swal.fire({
        title: 'Hapus User',
        text: `Yakin hapus user "${name}"? Tindakan ini tidak dapat dibatalkan.`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#dc3545',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Ya, hapus!',
        cancelButtonText: 'Batal',
    }).then(async (result) => {
        if (!result.isConfirmed) return;

        try {
            const res  = await fetch(`/user-management/delete/${id}`, {
                headers: buildHeaders(),
            });
            const data = await res.json();

            if (data.success) {
                const row = document.getElementById(`row-${id}`);
                if (row) row.remove();
                Swal.fire({ icon: 'success', title: 'Dihapus!', text: data.message, timer: 1500, showConfirmButton: false });
            } else {
                Swal.fire({ icon: 'error', title: 'Gagal', text: data.message });
            }
        } catch (e) {
            Swal.fire({ icon: 'error', title: 'Error', text: 'Terjadi kesalahan jaringan.' });
        }
    });
}

// ── Reset alert saat modal ditutup ────────────────────────────────────────
['modalTambah','modalEdit','modalReset','modalChangePassword'].forEach(id => {
    document.getElementById(id).addEventListener('hidden.bs.modal', function() {
        const alertMap = {
            modalTambah: 'alertTambah',
            modalEdit: 'alertEdit',
            modalReset: 'alertReset',
            modalChangePassword: 'alertChangePassword',
        };
        clearAlert(alertMap[id]);
    });
});
</script>
<?= $this->endSection() ?>
