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

<div class="d-flex align-items-center justify-content-between mb-3">
    <h5 class="mb-0 fw-bold">Manajemen User</h5>
    <button class="btn btn-primary btn-sm" onclick="openModal()">
        <i class="bi bi-person-plus me-1"></i> Tambah User
    </button>
</div>

<div class="card">
    <div class="table-responsive">
        <table class="table table-hover align-middle mb-0">
            <thead class="table-light">
                <tr>
                    <th style="width:50px">#</th>
                    <th>Nama</th>
                    <th>Username</th>
                    <th>Role</th>
                    <th>Status</th>
                    <th style="width:130px">Aksi</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($users as $i => $u): ?>
            <tr id="user-row-<?= $u['id'] ?>">
                <td class="text-muted"><?= $i + 1 ?></td>
                <td class="fw-semibold"><?= esc($u['nama']) ?></td>
                <td><code><?= esc($u['username']) ?></code></td>
                <td>
                    <?php if ($u['role'] === 'administrator'): ?>
                        <span class="badge" style="background:#dbeafe;color:#1d4ed8;">Administrator</span>
                    <?php else: ?>
                        <span class="badge" style="background:#f0fdf4;color:#15803d;">Viewer</span>
                    <?php endif; ?>
                </td>
                <td>
                    <span class="badge <?= $u['is_active'] ? 'bg-success' : 'bg-secondary' ?>" id="status-badge-<?= $u['id'] ?>">
                        <?= $u['is_active'] ? 'Aktif' : 'Nonaktif' ?>
                    </span>
                </td>
                <td>
                    <button class="btn btn-sm btn-outline-secondary py-0 px-2 me-1"
                        onclick='editUser(<?= json_encode($u) ?>)' title="Edit">
                        <i class="bi bi-pencil"></i>
                    </button>
                    <button class="btn btn-sm btn-outline-warning py-0 px-2 me-1"
                        onclick="toggleUser(<?= $u['id'] ?>, '<?= esc($u['username'], 'js') ?>', <?= $u['is_active'] ?>)"
                        title="<?= $u['is_active'] ? 'Nonaktifkan' : 'Aktifkan' ?>" id="toggle-btn-<?= $u['id'] ?>">
                        <i class="bi bi-<?= $u['is_active'] ? 'pause' : 'play' ?>"></i>
                    </button>
                    <?php if ($u['id'] !== (int) session('user_id')): ?>
                    <button class="btn btn-sm btn-outline-danger py-0 px-2"
                        onclick="deleteUser(<?= $u['id'] ?>, '<?= esc($u['username'], 'js') ?>')" title="Hapus">
                        <i class="bi bi-trash"></i>
                    </button>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            <?php if (empty($users)): ?>
            <tr><td colspan="6" class="text-center text-muted py-4">Belum ada user.</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Modal Add/Edit -->
<div class="modal fade" id="userModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">Tambah User</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="userId" value="0">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-semibold">Nama <span class="text-danger">*</span></label>
                        <input type="text" id="uNama" class="form-control" placeholder="Nama lengkap">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-semibold">Username <span class="text-danger">*</span></label>
                        <input type="text" id="uUsername" class="form-control" placeholder="Username">
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label fw-semibold">Password <span id="pwdHint" class="text-muted fw-normal">(kosongkan jika tidak diubah)</span></label>
                    <input type="password" id="uPassword" class="form-control" placeholder="Password baru">
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-semibold">Role</label>
                        <select id="uRole" class="form-select">
                            <option value="viewer">Viewer</option>
                            <option value="administrator">Administrator</option>
                        </select>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label fw-semibold">Status</label>
                        <select id="uActive" class="form-select">
                            <option value="1">Aktif</option>
                            <option value="0">Nonaktif</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                <button type="button" class="btn btn-primary" onclick="saveUser()">Simpan</button>
            </div>
        </div>
    </div>
</div>

<?= $this->endSection() ?>
<?= $this->section('scripts') ?>
<script>
var userModal = new bootstrap.Modal(document.getElementById('userModal'));

function openModal() {
    document.getElementById('modalTitle').textContent = 'Tambah User';
    document.getElementById('userId').value   = 0;
    document.getElementById('uNama').value     = '';
    document.getElementById('uUsername').value = '';
    document.getElementById('uPassword').value = '';
    document.getElementById('uRole').value     = 'viewer';
    document.getElementById('uActive').value   = '1';
    document.getElementById('pwdHint').textContent = '(wajib diisi)';
    userModal.show();
}

function editUser(u) {
    document.getElementById('modalTitle').textContent  = 'Edit User';
    document.getElementById('userId').value     = u.id;
    document.getElementById('uNama').value      = u.nama;
    document.getElementById('uUsername').value  = u.username;
    document.getElementById('uPassword').value  = '';
    document.getElementById('uRole').value      = u.role;
    document.getElementById('uActive').value    = u.is_active;
    document.getElementById('pwdHint').textContent = '(kosongkan jika tidak diubah)';
    userModal.show();
}

function saveUser() {
    const id       = document.getElementById('userId').value;
    const nama     = document.getElementById('uNama').value.trim();
    const username = document.getElementById('uUsername').value.trim();
    const password = document.getElementById('uPassword').value;
    const role     = document.getElementById('uRole').value;
    const is_active= document.getElementById('uActive').value;

    if (!nama || !username) { Swal.fire('Perhatian', 'Nama dan username wajib diisi.', 'warning'); return; }

    postData('users/save', {id, nama, username, password, role, is_active}, function() {
        Swal.fire({icon:'success', title:'Berhasil', text:'User disimpan.', timer:1500, showConfirmButton:false});
        setTimeout(() => location.reload(), 1500);
        userModal.hide();
    });
}

function toggleUser(id, username, isActive) {
    const action = isActive ? 'nonaktifkan' : 'aktifkan';
    Swal.fire({
        title: `${action.charAt(0).toUpperCase()+action.slice(1)} user?`,
        text: `User "${username}" akan di${action}.`,
        icon: 'question', showCancelButton: true,
        confirmButtonText: 'Ya', cancelButtonText: 'Batal'
    }).then(r => {
        if (r.isConfirmed) {
            postData('users/toggle/' + id, {}, function(res) {
                const badge = document.getElementById('status-badge-' + id);
                const btn   = document.getElementById('toggle-btn-' + id);
                if (res.is_active) {
                    badge.className = 'badge bg-success'; badge.textContent = 'Aktif';
                    btn.innerHTML = '<i class="bi bi-pause"></i>';
                } else {
                    badge.className = 'badge bg-secondary'; badge.textContent = 'Nonaktif';
                    btn.innerHTML = '<i class="bi bi-play"></i>';
                }
            });
        }
    });
}

function deleteUser(id, username) {
    Swal.fire({
        title: 'Hapus User?', text: `User "${username}" akan dihapus permanen.`,
        icon: 'warning', showCancelButton: true,
        confirmButtonColor: '#ef4444', confirmButtonText: 'Ya, Hapus', cancelButtonText: 'Batal'
    }).then(r => {
        if (r.isConfirmed) {
            postData('users/delete/' + id, {}, function() {
                document.getElementById('user-row-' + id).remove();
                Swal.fire({icon:'success', title:'Terhapus', timer:1200, showConfirmButton:false});
            });
        }
    });
}
</script>
<?= $this->endSection() ?>
