<div class="hero">
    <div>
        <h2 style="margin:0 0 6px;">Manajemen User</h2>
        <p style="margin:0; opacity:0.95;">Buat, ubah, dan hapus akun owner serta kasir.</p>
    </div>
</div>

<div class="panel">
    <div style="display:flex; justify-content:space-between; align-items:center; gap:12px; flex-wrap:wrap;">
        <h3 style="margin:0;">Daftar User</h3>
        <button class="btn-primary" type="button" onclick="openUserModal()" style="max-width:180px;">Tambah Baru</button>
    </div>
</div>

<?php
$iconEdit = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"></path><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4Z"></path></svg>';
$iconDelete = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"></path><path d="M10 11v6"></path><path d="M14 11v6"></path><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"></path></svg>';

$ownerCount = 0;
foreach ($users as $u) {
    if ($u['role'] === 'owner') {
        $ownerCount++;
    }
}
?>
<div class="panel">
    <h3>Daftar User</h3>
    <div class="table-wrap">
        <table>
            <thead>
                <tr><th>Nama</th><th>Username</th><th>Role</th><th>Aksi</th></tr>
            </thead>
            <tbody>
                <?php foreach ($users as $userRow) : ?>
                    <?php
                    $isSelf = (int) $userRow['id'] === (int) ($user['id'] ?? 0);
                    $isLastOwner = $userRow['role'] === 'owner' && $ownerCount <= 1;
                    $isProtected = $isSelf || $isLastOwner;
                    ?>
                    <tr>
                        <td><?= esc($userRow['name']) ?></td>
                        <td><?= esc($userRow['username']) ?></td>
                        <td><?= esc($userRow['role']) ?></td>
                        <td>
                            <div class="action-cell">
                                <a class="icon-btn icon-edit" href="#" title="Edit" data-id="<?= esc($userRow['id']) ?>" data-name="<?= esc($userRow['name']) ?>" data-username="<?= esc($userRow['username']) ?>" data-role="<?= esc($userRow['role']) ?>" onclick="openUserModal(this); return false;"><?= $iconEdit ?></a>
                                <?php if (!$isProtected) : ?>
                                    <a class="icon-btn icon-delete" href="#" title="Hapus" onclick="confirmDelete('/owner/delete-user/<?= esc($userRow['id']) ?>'); return false;"><?= $iconDelete ?></a>
                                <?php else : ?>
                                    <span class="icon-btn" title="<?= $isSelf ? 'Tidak bisa menghapus akun sendiri' : 'Minimal harus ada satu akun Owner' ?>" style="opacity:0.4; cursor:not-allowed;"><?= $iconDelete ?></span>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="modal" id="userModal" tabindex="-1" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.45); z-index:9999; align-items:center; justify-content:center;">
    <div style="background:white; width:min(560px, 92vw); border-radius:16px; padding:20px;">
        <h3 id="userModalTitle" style="margin-top:0;">Tambah User</h3>
        <form id="userForm" method="post" action="/owner/save-user">
            <input type="hidden" name="id" id="userId">
            <div class="form-grid">
                <input type="text" name="username" id="userUsername" placeholder="Username" required>
                <input type="text" name="name" id="userName" placeholder="Nama Lengkap" required>
                <select name="role" id="userRole">
                    <option value="owner">Owner</option>
                    <option value="cashier">Cashier</option>
                </select>
                <div>
                    <div style="position:relative;">
                        <input type="password" name="password" id="userPassword" placeholder="Password" style="width:100%; padding-right:44px;">
                        <button type="button" onclick="togglePasswordVisibility()" title="Lihat/Sembunyikan Password" style="position:absolute; right:4px; top:4px; width:36px; height:36px; min-height:36px; padding:0; border:none; background:transparent; color:var(--muted); display:flex; align-items:center; justify-content:center; cursor:pointer;">
                            <svg id="userPasswordEyeIcon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="width:18px; height:18px;"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
                        </button>
                    </div>
                    <p id="userPasswordHint" class="muted" style="font-size:12px; margin:4px 0 0;"></p>
                </div>
            </div>
            <div class="form-grid">
                <button class="btn-primary" type="submit">Simpan</button>
                <button class="btn-secondary" type="button" onclick="closeUserModal();">Batal</button>
            </div>
        </form>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<style>
.swal2-container { z-index: 10050 !important; }
</style>
<script>
function openUserModal(el) {
    const modal = document.getElementById('userModal');
    const form = document.getElementById('userForm');
    document.getElementById('userModalTitle').textContent = el ? 'Edit User' : 'Tambah User';
    document.getElementById('userId').value = el ? el.dataset.id : '';
    document.getElementById('userUsername').value = el ? el.dataset.username : '';
    document.getElementById('userName').value = el ? el.dataset.name : '';
    document.getElementById('userRole').value = el ? el.dataset.role : 'owner';
    document.getElementById('userPassword').value = '';
    document.getElementById('userPassword').type = 'password';
    document.getElementById('userPasswordEyeIcon').innerHTML = '<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle>';
    if (el) {
        document.getElementById('userPassword').placeholder = 'Password Baru';
        document.getElementById('userPasswordHint').textContent = 'Password lama tidak bisa ditampilkan (tersimpan terenkripsi). Kosongkan field ini jika tidak ingin mengganti password.';
    } else {
        document.getElementById('userPassword').placeholder = 'Password';
        document.getElementById('userPasswordHint').textContent = '';
    }
    form.action = el ? '/owner/update-user' : '/owner/save-user';
    modal.style.display = 'flex';
}
function closeUserModal() { document.getElementById('userModal').style.display = 'none'; }
function togglePasswordVisibility() {
    const input = document.getElementById('userPassword');
    const icon = document.getElementById('userPasswordEyeIcon');
    if (input.type === 'password') {
        input.type = 'text';
        icon.innerHTML = '<path d="M17.94 17.94A10.94 10.94 0 0 1 12 20c-7 0-11-8-11-8a18.9 18.9 0 0 1 5.06-5.94"></path><path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.9 18.9 0 0 1-2.16 3.19"></path><path d="M14.12 14.12a3 3 0 1 1-4.24-4.24"></path><line x1="1" y1="1" x2="23" y2="23"></line>';
    } else {
        input.type = 'password';
        icon.innerHTML = '<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle>';
    }
}
function confirmDelete(url) {
    Swal.fire({ title: 'Apakah Anda yakin?', text: 'Data ini akan dihapus permanen.', icon: 'warning', showCancelButton: true, confirmButtonText: 'Ya, hapus', cancelButtonText: 'Batal' }).then((result) => {
        if (result.isConfirmed) {
            fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } }).then(r => r.json()).then((res) => {
                if (!res.success) {
                    Swal.fire('Gagal', res.message || 'Data tidak bisa dihapus', 'error');
                    return;
                }
                Swal.fire('Berhasil', res.message || 'Data Berhasil Dihapus', 'success').then(() => location.reload());
            });
        }
    });
}
document.getElementById('userForm').addEventListener('submit', function (e) {
    e.preventDefault();
    const formData = new FormData(this);
    fetch(this.action, { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } })
        .then(r => r.json())
        .then((res) => {
            if (!res.success) {
                Swal.fire('Gagal', res.message || 'Terjadi kesalahan', 'error');
                return;
            }
            closeUserModal();
            Swal.fire('Berhasil', res.message || 'Data Berhasil Disimpan', 'success').then(() => location.reload());
        });
});
</script>
