<?php
$pageTitle = 'User Management';
require_once 'includes/header.php';
require_once 'config/database.php';
requireAdmin();
?>

<div class="px-4 sm:px-0" x-data="userManagementApp()">
    <div class="flex justify-between items-center mb-8">
        <h1 class="text-3xl font-bold text-gray-900">User Management</h1>
        <button @click="openModal()" class="bg-primary hover:bg-secondary text-white px-4 py-2 rounded-lg">
            + Tambah User
        </button>
    </div>

    <!-- List Users -->
    <div class="bg-white rounded-lg shadow-md overflow-hidden">
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">ID</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</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">Dibuat</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Aksi</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <template x-if="loading">
                        <tr>
                            <td colspan="6" class="px-6 py-8 text-center text-gray-500">
                                Loading...
                            </td>
                        </tr>
                    </template>
                    
                    <template x-if="!loading && users.length === 0">
                        <tr>
                            <td colspan="6" class="px-6 py-8 text-center text-gray-500">
                                Belum ada user
                            </td>
                        </tr>
                    </template>
                    
                    <template x-for="user in users" :key="user.id">
                        <tr class="hover:bg-gray-50">
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900" x-text="user.id"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900" x-text="user.username"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600" x-text="user.nama"></td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span :class="user.role === 'admin' ? 'bg-purple-100 text-purple-800' : 'bg-blue-100 text-blue-800'"
                                      class="px-2 py-1 text-xs font-semibold rounded-full"
                                      x-text="user.role === 'admin' ? 'Admin' : 'Loket'">
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600" x-text="formatDate(user.created_at)"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm space-x-2">
                                <button @click="editUser(user)" class="text-blue-600 hover:text-blue-800">Edit</button>
                                <button @click="changePassword(user)" class="text-green-600 hover:text-green-800">Ganti Password</button>
                                <button @click="deleteUser(user.id)" class="text-red-600 hover:text-red-800">Hapus</button>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Modal Add/Edit User -->
    <div x-show="showModal" x-cloak class="fixed inset-0 z-50 overflow-y-auto" style="display: none;">
        <div class="flex items-center justify-center min-h-screen px-4">
            <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" @click="showModal = false"></div>
            
            <div class="bg-white rounded-lg overflow-hidden shadow-xl transform transition-all max-w-lg w-full z-50">
                <form @submit.prevent="saveUser()">
                    <div class="bg-white px-6 pt-6 pb-4">
                        <h3 class="text-lg font-medium text-gray-900 mb-4" x-text="form.id ? 'Edit User' : 'Tambah User'"></h3>
                        
                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-medium mb-2">Username *</label>
                            <input type="text" x-model="form.username" required
                                   :readonly="form.id !== null"
                                   :class="form.id !== null ? 'bg-gray-100' : ''"
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary">
                            <p class="text-xs text-gray-500 mt-1">Username tidak dapat diubah setelah dibuat</p>
                        </div>

                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-medium mb-2">Nama Lengkap *</label>
                            <input type="text" x-model="form.nama" required
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary">
                        </div>

                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-medium mb-2">Role *</label>
                            <select x-model="form.role" required
                                    class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary">
                                <option value="">Pilih Role</option>
                                <option value="admin">Admin</option>
                                <option value="loket">Loket</option>
                            </select>
                        </div>

                        <div x-show="!form.id" class="mb-4">
                            <label class="block text-gray-700 text-sm font-medium mb-2">Password *</label>
                            <input type="password" x-model="form.password" :required="!form.id"
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
                                   placeholder="Minimal 6 karakter">
                        </div>
                    </div>
                    
                    <div class="bg-gray-50 px-6 py-3 flex justify-end space-x-2">
                        <button type="button" @click="showModal = false"
                                class="px-4 py-2 bg-gray-200 hover:bg-gray-300 text-gray-800 rounded-lg">
                            Batal
                        </button>
                        <button type="submit"
                                class="px-4 py-2 bg-primary hover:bg-secondary text-white rounded-lg">
                            Simpan
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal Change Password -->
    <div x-show="showPasswordModal" x-cloak class="fixed inset-0 z-50 overflow-y-auto" style="display: none;">
        <div class="flex items-center justify-center min-h-screen px-4">
            <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" @click="showPasswordModal = false"></div>
            
            <div class="bg-white rounded-lg overflow-hidden shadow-xl transform transition-all max-w-lg w-full z-50">
                <form @submit.prevent="savePassword()">
                    <div class="bg-white px-6 pt-6 pb-4">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Ganti Password</h3>
                        
                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-medium mb-2">User</label>
                            <input type="text" :value="passwordForm.username" readonly
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg bg-gray-100">
                        </div>

                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-medium mb-2">Password Baru *</label>
                            <input type="password" x-model="passwordForm.password" required
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
                                   placeholder="Minimal 6 karakter">
                        </div>

                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-medium mb-2">Konfirmasi Password *</label>
                            <input type="password" x-model="passwordForm.confirm_password" required
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
                                   placeholder="Ketik ulang password">
                        </div>
                    </div>
                    
                    <div class="bg-gray-50 px-6 py-3 flex justify-end space-x-2">
                        <button type="button" @click="showPasswordModal = false"
                                class="px-4 py-2 bg-gray-200 hover:bg-gray-300 text-gray-800 rounded-lg">
                            Batal
                        </button>
                        <button type="submit"
                                class="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg">
                            Ganti Password
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
function userManagementApp() {
    return {
        users: [],
        loading: false,
        showModal: false,
        showPasswordModal: false,
        form: {
            id: null,
            username: '',
            nama: '',
            role: '',
            password: ''
        },
        passwordForm: {
            id: null,
            username: '',
            password: '',
            confirm_password: ''
        },

        init() {
            this.loadUsers();
        },

        async loadUsers() {
            this.loading = true;
            try {
                const response = await fetch('api/user-management.php?action=get_users');
                const data = await response.json();
                
                if (data.success) {
                    this.users = data.data;
                }
            } catch (error) {
                console.error('Error loading users:', error);
            } finally {
                this.loading = false;
            }
        },

        openModal() {
            this.form = {
                id: null,
                username: '',
                nama: '',
                role: '',
                password: ''
            };
            this.showModal = true;
        },

        editUser(user) {
            this.form = {
                id: user.id,
                username: user.username,
                nama: user.nama,
                role: user.role,
                password: ''
            };
            this.showModal = true;
        },

        changePassword(user) {
            this.passwordForm = {
                id: user.id,
                username: user.username,
                password: '',
                confirm_password: ''
            };
            this.showPasswordModal = true;
        },

        async saveUser() {
            try {
                // Validasi password untuk user baru
                if (!this.form.id && this.form.password.length < 6) {
                    showToast('Password minimal 6 karakter', 'error');
                    return;
                }

                const formData = new FormData();
                formData.append('action', this.form.id ? 'update_user' : 'add_user');
                if (this.form.id) {
                    formData.append('id', this.form.id);
                }
                formData.append('username', this.form.username);
                formData.append('nama', this.form.nama);
                formData.append('role', this.form.role);
                if (!this.form.id) {
                    formData.append('password', this.form.password);
                }

                const response = await fetch('api/user-management.php', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();
                
                if (data.success) {
                    showToast(data.message, 'success');
                    this.showModal = false;
                    this.loadUsers();
                } else {
                    showToast(data.message, 'error');
                }
            } catch (error) {
                showToast('Terjadi kesalahan', 'error');
            }
        },

        async savePassword() {
            try {
                // Validasi
                if (this.passwordForm.password.length < 6) {
                    showToast('Password minimal 6 karakter', 'error');
                    return;
                }

                if (this.passwordForm.password !== this.passwordForm.confirm_password) {
                    showToast('Konfirmasi password tidak cocok', 'error');
                    return;
                }

                const formData = new FormData();
                formData.append('action', 'change_password');
                formData.append('id', this.passwordForm.id);
                formData.append('password', this.passwordForm.password);

                const response = await fetch('api/user-management.php', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();
                
                if (data.success) {
                    showToast(data.message, 'success');
                    this.showPasswordModal = false;
                } else {
                    showToast(data.message, 'error');
                }
            } catch (error) {
                showToast('Terjadi kesalahan', 'error');
            }
        },

        async deleteUser(id) {
            if (!confirm('Yakin ingin menghapus user ini?')) return;

            try {
                const formData = new FormData();
                formData.append('action', 'delete_user');
                formData.append('id', id);

                const response = await fetch('api/user-management.php', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();
                
                if (data.success) {
                    showToast('User berhasil dihapus', 'success');
                    this.loadUsers();
                } else {
                    showToast(data.message, 'error');
                }
            } catch (error) {
                showToast('Terjadi kesalahan', 'error');
            }
        },

        formatDate(datetime) {
            const d = new Date(datetime);
            return d.toLocaleDateString('id-ID', { 
                day: '2-digit', 
                month: 'short', 
                year: 'numeric'
            });
        }
    }
}
</script>

<style>
[x-cloak] { display: none !important; }
</style>

<?php require_once 'includes/footer.php'; ?>
