<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manajemen User - Work Order System</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.sheetjs.com/xlsx-0.20.2/package/dist/xlsx.full.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <script src="config.js"></script>
    <style>
        body { background: #f3f4f6; font-family: 'Inter', system-ui, sans-serif; }
        .transition-smooth { transition: all 0.2s ease; }
        .card-hover:hover { transform: translateY(-2px); box-shadow: 0 10px 25px -5px rgba(0,0,0,0.1); }
    </style>
</head>
<body class="p-6">
    <div class="max-w-7xl mx-auto">
        <!-- Header -->
        <div class="flex flex-wrap justify-between items-center mb-6 gap-4">
            <div>
                <h1 class="text-3xl font-bold text-gray-800"><i class="fas fa-users-cog text-purple-600 mr-2"></i>Manajemen User</h1>
                <p class="text-gray-500 mt-1">Kelola akun pengguna sistem keperawatan</p>
            </div>
            <div class="flex gap-3">
                <button onclick="exportToExcel()" class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg shadow-md transition-smooth flex items-center gap-2">
                    <i class="fas fa-file-excel"></i> Export Excel
                </button>
                <button onclick="openUserModal()" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg shadow-md transition-smooth flex items-center gap-2">
                    <i class="fas fa-user-plus"></i> Tambah User
                </button>
                <a href="dashboard.html" class="bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded-lg shadow-md transition-smooth flex items-center gap-2">
                    <i class="fas fa-arrow-left"></i> Kembali
                </a>
            </div>
        </div>

        <!-- Filter dan Statistik -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
            <div class="bg-white rounded-xl shadow p-4 card-hover">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-500 text-sm">Total User</p>
                        <p class="text-2xl font-bold" id="totalUsers">0</p>
                    </div>
                    <i class="fas fa-users text-3xl text-blue-400"></i>
                </div>
            </div>
            <div class="bg-white rounded-xl shadow p-4 card-hover">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-500 text-sm">Admin</p>
                        <p class="text-2xl font-bold" id="totalAdmin">0</p>
                    </div>
                    <i class="fas fa-user-shield text-3xl text-red-400"></i>
                </div>
            </div>
            <div class="bg-white rounded-xl shadow p-4 card-hover">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-500 text-sm">Editor</p>
                        <p class="text-2xl font-bold" id="totalEditor">0</p>
                    </div>
                    <i class="fas fa-user-edit text-3xl text-green-400"></i>
                </div>
            </div>
            <div class="bg-white rounded-xl shadow p-4 card-hover">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-gray-500 text-sm">Viewer</p>
                        <p class="text-2xl font-bold" id="totalViewer">0</p>
                    </div>
                    <i class="fas fa-user text-3xl text-gray-400"></i>
                </div>
            </div>
        </div>

        <!-- Tabel User -->
        <div class="bg-white rounded-2xl shadow-lg overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200 flex flex-wrap justify-between items-center gap-3">
                <h2 class="text-xl font-semibold flex items-center"><i class="fas fa-list-ul text-purple-600 mr-2"></i> Daftar User</h2>
                <div class="flex gap-2">
                    <input type="text" id="searchInput" placeholder="Cari user..." class="border rounded-lg px-4 py-2 w-64">
                    <select id="roleFilter" class="border rounded-lg px-4 py-2">
                        <option value="">Semua Role</option>
                        <option value="admin">Admin</option>
                        <option value="editor">Editor</option>
                        <option value="viewer">Viewer</option>
                    </select>
                </div>
            </div>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200" id="userTable">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">No</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Username</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Nama Lengkap</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">NIK</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Unit</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Jabatan</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Role</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Terakhir Login</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Aksi</th>
                        </tr>
                    </thead>
                    <tbody id="userListBody" class="bg-white divide-y divide-gray-200">
                        <tr><td colspan="10" class="text-center py-8 text-gray-500">Memuat data...</td</tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Modal Tambah/Edit User -->
    <div id="userModal" class="fixed inset-0 bg-gray-800 bg-opacity-60 hidden overflow-y-auto h-full w-full z-50">
        <div class="relative top-10 mx-auto p-5 border w-full max-w-2xl shadow-2xl rounded-2xl bg-white">
            <div class="flex justify-between items-center border-b pb-3">
                <h3 id="modalTitle" class="text-xl font-semibold text-gray-800"><i class="fas fa-user-plus text-blue-600 mr-2"></i>Tambah User</h3>
                <button onclick="closeUserModal()" class="text-gray-400 hover:text-gray-600"><i class="fas fa-times text-2xl"></i></button>
            </div>
            <form id="userForm" class="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
                <input type="hidden" id="userId">
                <div class="md:col-span-2">
                    <label class="block text-sm font-medium text-gray-700">Pilih Karyawan *</label>
                    <select id="employee_id" required class="w-full border rounded-lg px-3 py-2">
                        <option value="">Pilih Karyawan</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Username *</label>
                    <input type="text" id="username" required class="w-full border rounded-lg px-3 py-2">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Role *</label>
                    <select id="role" required class="w-full border rounded-lg px-3 py-2">
                        <option value="viewer">Viewer (Hanya Lihat)</option>
                        <option value="editor">Editor (Edit Data)</option>
                        <option value="admin">Admin (Full Akses)</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Password</label>
                    <input type="password" id="password" class="w-full border rounded-lg px-3 py-2" placeholder="Kosongkan jika tidak diubah">
                    <p class="text-xs text-gray-500 mt-1">Minimal 6 karakter. Kosongkan jika tidak mengubah password.</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Konfirmasi Password</label>
                    <input type="password" id="confirm_password" class="w-full border rounded-lg px-3 py-2">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Status</label>
                    <select id="is_active" class="w-full border rounded-lg px-3 py-2">
                        <option value="1">Aktif</option>
                        <option value="0">Nonaktif</option>
                    </select>
                </div>
                <div class="md:col-span-2 flex justify-end gap-3 mt-2">
                    <button type="button" onclick="closeUserModal()" class="px-4 py-2 bg-gray-300 rounded-lg">Batal</button>
                    <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">Simpan</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Modal Reset Password -->
    <div id="resetModal" class="fixed inset-0 bg-gray-800 bg-opacity-60 hidden overflow-y-auto h-full w-full z-50">
        <div class="relative top-40 mx-auto p-5 border w-full max-w-md shadow-2xl rounded-2xl bg-white">
            <div class="flex justify-between items-center border-b pb-3">
                <h3 class="text-xl font-semibold text-gray-800"><i class="fas fa-key text-yellow-600 mr-2"></i>Reset Password</h3>
                <button onclick="closeResetModal()" class="text-gray-400 hover:text-gray-600"><i class="fas fa-times text-2xl"></i></button>
            </div>
            <div class="mt-4">
                <p class="text-gray-600 mb-4">Reset password untuk user: <strong id="resetUserName"></strong></p>
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700">Password Baru</label>
                    <input type="password" id="reset_password" class="w-full border rounded-lg px-3 py-2 mt-1">
                </div>
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700">Konfirmasi Password Baru</label>
                    <input type="password" id="reset_confirm_password" class="w-full border rounded-lg px-3 py-2 mt-1">
                </div>
                <div class="flex justify-end gap-3">
                    <button onclick="closeResetModal()" class="px-4 py-2 bg-gray-300 rounded-lg">Batal</button>
                    <button onclick="submitResetPassword()" class="px-4 py-2 bg-yellow-600 text-white rounded-lg hover:bg-yellow-700">Reset Password</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Cek token di localStorage
        const token = localStorage.getItem('wo_token');
        if (!token) {
            // Tidak ada token, redirect ke login
            window.location.href = 'index.html';
        }

        let currentResetUserId = null;

        async function fetchAPI(endpoint, options = {}) {
            const url = `${API_BASE_URL}/${endpoint}`;
            
            try {
                const res = await fetch(url, {
                    method: options.method || 'GET',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    },
                    body: options.body ? JSON.stringify(options.body) : undefined
                });
                
                // Jika 401 Unauthorized, token tidak valid atau expired
                if (res.status === 401) {
                    localStorage.removeItem('wo_token');
                    window.location.href = 'index.html';
                    return null;
                }
                
                // Jika 403 Forbidden, user tidak memiliki akses
                if (res.status === 403) {
                    alert('Anda tidak memiliki akses ke halaman ini. Hanya Admin yang diizinkan.');
                    window.location.href = 'dashboard.html';
                    return null;
                }
                
                const data = await res.json();
                
                if (!res.ok) {
                    throw new Error(data.error || 'Request failed');
                }
                
                return data;
            } catch (err) {
                console.error('Fetch error:', err);
                throw err;
            }
        }

        async function loadUsers() {
            try {
                const data = await fetchAPI('users.php?action=list');
                if (!data) return;
                
                const search = document.getElementById('searchInput').value.toLowerCase();
                const roleFilter = document.getElementById('roleFilter').value;
                
                let filtered = data;
                if (search) {
                    filtered = filtered.filter(u => 
                        (u.full_name && u.full_name.toLowerCase().includes(search)) || 
                        (u.username && u.username.toLowerCase().includes(search)) ||
                        (u.nik && u.nik.toLowerCase().includes(search))
                    );
                }
                if (roleFilter) {
                    filtered = filtered.filter(u => u.role === roleFilter);
                }
                
                // Update statistik
                document.getElementById('totalUsers').innerText = data.length;
                document.getElementById('totalAdmin').innerText = data.filter(u => u.role === 'admin').length;
                document.getElementById('totalEditor').innerText = data.filter(u => u.role === 'editor').length;
                document.getElementById('totalViewer').innerText = data.filter(u => u.role === 'viewer').length;
                
                const tbody = document.getElementById('userListBody');
                if (!filtered.length) {
                    tbody.innerHTML = '<tr><td colspan="10" class="text-center py-8 text-gray-500">Tidak ada data user</td</tr>';
                    return;
                }
                
                tbody.innerHTML = filtered.map((u, i) => `
                    <tr class="hover:bg-gray-50 transition">
                        <td class="px-6 py-4 text-sm">${i+1}</td>
                        <td class="px-6 py-4 text-sm font-medium text-gray-900">${escapeHtml(u.username)}</td>
                        <td class="px-6 py-4 text-sm">${escapeHtml(u.full_name) || '-'}</td>
                        <td class="px-6 py-4 text-sm">${escapeHtml(u.nik) || '-'}</td>
                        <td class="px-6 py-4 text-sm">${escapeHtml(u.unit_name) || '-'}</td>
                        <td class="px-6 py-4 text-sm">${escapeHtml(u.position_name) || '-'}</td>
                        <td class="px-6 py-4">${getRoleBadge(u.role)}</td>
                        <td class="px-6 py-4">${getStatusBadge(u.is_active)}</td>
                        <td class="px-6 py-4 text-sm">${u.last_login_at ? new Date(u.last_login_at).toLocaleDateString('id-ID') : '-'}</td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <button onclick="editUser(${u.id})" class="text-blue-600 hover:text-blue-800 mr-2"><i class="fas fa-edit"></i></button>
                            <button onclick="showResetModal(${u.id}, '${escapeHtml(u.username)}')" class="text-yellow-600 hover:text-yellow-800 mr-2"><i class="fas fa-key"></i></button>
                            <button onclick="deleteUser(${u.id})" class="text-red-600 hover:text-red-800"><i class="fas fa-trash-alt"></i></button>
                        </td>
                    </tr>
                `).join('');
            } catch (err) {
                console.error(err);
                document.getElementById('userListBody').innerHTML = '<tr><td colspan="10" class="text-center py-8 text-red-500">Gagal memuat data: ' + err.message + '</td></tr>';
            }
        }

        async function loadEmployees() {
            try {
                const data = await fetchAPI('employees.php?action=list_active');
                if (!data) return;
                
                const select = document.getElementById('employee_id');
                select.innerHTML = '<option value="">Pilih Karyawan</option>' + 
                    data.map(e => `<option value="${e.id}">${escapeHtml(e.nik)} - ${escapeHtml(e.full_name)} (${escapeHtml(e.unit_name || '-')})</option>`).join('');
            } catch(err) {
                console.error(err);
                document.getElementById('employee_id').innerHTML = '<option value="">Gagal memuat data karyawan</option>';
            }
        }

        function getRoleBadge(role) {
            const map = {
                'admin': '<span class="px-2 py-1 rounded-full text-xs bg-red-100 text-red-800"><i class="fas fa-user-shield mr-1"></i>Admin</span>',
                'editor': '<span class="px-2 py-1 rounded-full text-xs bg-green-100 text-green-800"><i class="fas fa-user-edit mr-1"></i>Editor</span>',
                'viewer': '<span class="px-2 py-1 rounded-full text-xs bg-gray-100 text-gray-800"><i class="fas fa-user mr-1"></i>Viewer</span>'
            };
            return map[role] || role;
        }

        function getStatusBadge(active) {
            return active == 1 ? 
                '<span class="px-2 py-1 rounded-full text-xs bg-green-100 text-green-800">Aktif</span>' :
                '<span class="px-2 py-1 rounded-full text-xs bg-red-100 text-red-800">Nonaktif</span>';
        }

        function openUserModal() {
            document.getElementById('modalTitle').innerHTML = '<i class="fas fa-user-plus text-blue-600 mr-2"></i>Tambah User';
            document.getElementById('userForm').reset();
            document.getElementById('userId').value = '';
            document.getElementById('password').required = true;
            document.getElementById('confirm_password').required = true;
            document.getElementById('userModal').classList.remove('hidden');
        }

        async function editUser(id) {
            try {
                const data = await fetchAPI(`users.php?action=detail&id=${id}`);
                if (!data) return;
                
                document.getElementById('modalTitle').innerHTML = '<i class="fas fa-user-edit text-blue-600 mr-2"></i>Edit User';
                document.getElementById('userId').value = data.id;
                document.getElementById('employee_id').value = data.employee_id;
                document.getElementById('username').value = data.username;
                document.getElementById('role').value = data.role;
                document.getElementById('is_active').value = data.is_active;
                document.getElementById('password').required = false;
                document.getElementById('confirm_password').required = false;
                document.getElementById('userModal').classList.remove('hidden');
            } catch(err) {
                alert('Gagal mengambil data: ' + err.message);
            }
        }

        document.getElementById('userForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const userId = document.getElementById('userId').value;
            const password = document.getElementById('password').value;
            const confirmPassword = document.getElementById('confirm_password').value;
            
            if (password && password !== confirmPassword) {
                alert('Password dan konfirmasi password tidak cocok');
                return;
            }
            if (password && password.length < 6) {
                alert('Password minimal 6 karakter');
                return;
            }
            
            const payload = {
                employee_id: document.getElementById('employee_id').value,
                username: document.getElementById('username').value,
                role: document.getElementById('role').value,
                is_active: parseInt(document.getElementById('is_active').value)
            };
            if (password) payload.password = password;
            
            try {
                let result;
                if (userId) {
                    result = await fetchAPI(`users.php?action=update&id=${userId}`, { method: 'PUT', body: payload });
                } else {
                    result = await fetchAPI('users.php?action=create', { method: 'POST', body: payload });
                }
                if (result && result.success) {
                    alert(userId ? 'User berhasil diupdate' : 'User berhasil ditambahkan');
                    closeUserModal();
                    loadUsers();
                } else if (result && result.error) {
                    alert('Gagal: ' + result.error);
                }
            } catch(err) {
                alert('Error: ' + err.message);
            }
        });

        function showResetModal(userId, username) {
            currentResetUserId = userId;
            document.getElementById('resetUserName').innerText = username;
            document.getElementById('reset_password').value = '';
            document.getElementById('reset_confirm_password').value = '';
            document.getElementById('resetModal').classList.remove('hidden');
        }

        async function submitResetPassword() {
            const password = document.getElementById('reset_password').value;
            const confirm = document.getElementById('reset_confirm_password').value;
            
            if (!password) {
                alert('Password baru harus diisi');
                return;
            }
            if (password.length < 6) {
                alert('Password minimal 6 karakter');
                return;
            }
            if (password !== confirm) {
                alert('Password dan konfirmasi tidak cocok');
                return;
            }
            
            try {
                const result = await fetchAPI(`users.php?action=reset_password&id=${currentResetUserId}`, { 
                    method: 'PUT', 
                    body: { password } 
                });
                if (result && result.success) {
                    alert('Password berhasil direset');
                    closeResetModal();
                } else if (result && result.error) {
                    alert('Gagal reset password: ' + result.error);
                }
            } catch(err) {
                alert('Error: ' + err.message);
            }
        }

        async function deleteUser(id) {
            if (!confirm('Yakin hapus user ini?')) return;
            try {
                const result = await fetchAPI(`users.php?action=delete&id=${id}`, { method: 'DELETE' });
                if (result && result.success) {
                    alert('User berhasil dihapus');
                    loadUsers();
                } else if (result && result.error) {
                    alert('Gagal hapus: ' + result.error);
                }
            } catch(err) {
                alert('Error: ' + err.message);
            }
        }

        function closeUserModal() {
            document.getElementById('userModal').classList.add('hidden');
        }

        function closeResetModal() {
            document.getElementById('resetModal').classList.add('hidden');
            currentResetUserId = null;
        }

        function exportToExcel() {
            const table = document.getElementById('userTable');
            const workbook = XLSX.utils.book_new();
            const worksheet = XLSX.utils.table_to_sheet(table, { raw: true });
            XLSX.utils.book_append_sheet(workbook, worksheet, 'Users');
            XLSX.writeFile(workbook, `Users_${new Date().toISOString().slice(0,19)}.xlsx`);
        }

        function escapeHtml(str) {
            if (!str) return '';
            return str.replace(/[&<>]/g, function(m) {
                if (m === '&') return '&amp;';
                if (m === '<') return '&lt;';
                if (m === '>') return '&gt;';
                return m;
            });
        }

        // Logout function - clear token and redirect to login
        function logout() {
            localStorage.removeItem('wo_token');
            window.location.href = 'index.html';
        }

        // Event listeners
        document.getElementById('searchInput').addEventListener('keyup', () => loadUsers());
        document.getElementById('roleFilter').addEventListener('change', () => loadUsers());
        
        // Inisialisasi
        loadEmployees();
        loadUsers();
    </script>
</body>
</html>