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

<div class="px-4 sm:px-0" x-data="layananApp()">
    <div class="flex justify-between items-center mb-8">
        <h1 class="text-3xl font-bold text-gray-900">Kelola Layanan</h1>
        <div class="space-x-2">
            <button @click="openKategoriModal()" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-lg">
                + Kategori Baru
            </button>
            <button @click="openLayananModal()" class="bg-primary hover:bg-secondary text-white px-4 py-2 rounded-lg">
                + Layanan Baru
            </button>
        </div>
    </div>

    <!-- Tabs untuk Kategori -->
    <div class="mb-6">
        <div class="border-b border-gray-200">
            <nav class="-mb-px flex space-x-8">
                <button @click="activeTab = 'all'" 
                        :class="activeTab === 'all' ? 'border-primary text-primary' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
                        class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm">
                    Semua Layanan
                </button>
                <template x-for="kategori in categories" :key="kategori.id">
                    <button @click="activeTab = kategori.id" 
                            :class="activeTab === kategori.id ? 'border-primary text-primary' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
                            class="whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm"
                            x-text="kategori.nama_kategori">
                    </button>
                </template>
            </nav>
        </div>
    </div>

    <!-- List Layanan -->
    <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">Kategori</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Nama Layanan</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Harga</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">Aksi</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <template x-for="layanan in filteredLayanan" :key="layanan.id">
                        <tr class="hover:bg-gray-50">
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600" x-text="layanan.kategori_nama"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900" x-text="layanan.nama_layanan"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900" x-text="formatRupiah(layanan.harga)"></td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span :class="layanan.status === 'active' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'"
                                      class="px-2 py-1 text-xs font-semibold rounded-full"
                                      x-text="layanan.status === 'active' ? 'Aktif' : 'Nonaktif'">
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm space-x-2">
                                <button @click="editLayanan(layanan)" class="text-blue-600 hover:text-blue-800">Edit</button>
                                <button @click="deleteLayanan(layanan.id)" class="text-red-600 hover:text-red-800">Hapus</button>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Modal Kategori -->
    <div x-show="showKategoriModal" 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="showKategoriModal = 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="saveKategori()">
                    <div class="bg-white px-6 pt-6 pb-4">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">Kategori Layanan Baru</h3>
                        
                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-medium mb-2">Nama Kategori</label>
                            <input type="text" x-model="kategoriForm.nama_kategori" 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>
                    
                    <div class="bg-gray-50 px-6 py-3 flex justify-end space-x-2">
                        <button type="button" @click="showKategoriModal = 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 Layanan -->
    <div x-show="showLayananModal" 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="showLayananModal = 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="saveLayanan()">
                    <div class="bg-white px-6 pt-6 pb-4">
                        <h3 class="text-lg font-medium text-gray-900 mb-4" x-text="layananForm.id ? 'Edit Layanan' : 'Layanan Baru'"></h3>
                        
                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-medium mb-2">Kategori</label>
                            <select x-model="layananForm.id_kategori" 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 Kategori</option>
                                <template x-for="kategori in categories" :key="kategori.id">
                                    <option :value="kategori.id" x-text="kategori.nama_kategori"></option>
                                </template>
                            </select>
                        </div>

                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-medium mb-2">Nama Layanan</label>
                            <input type="text" x-model="layananForm.nama_layanan" 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">Harga</label>
                            <input type="number" x-model="layananForm.harga" required min="0" step="1"
                                   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">Status</label>
                            <select x-model="layananForm.status"
                                    class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary">
                                <option value="active">Aktif</option>
                                <option value="inactive">Nonaktif</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="bg-gray-50 px-6 py-3 flex justify-end space-x-2">
                        <button type="button" @click="showLayananModal = 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>
</div>

<script>
function layananApp() {
    return {
        categories: [],
        layanan: [],
        activeTab: 'all',
        showKategoriModal: false,
        showLayananModal: false,
        kategoriForm: {
            nama_kategori: ''
        },
        layananForm: {
            id: null,
            id_kategori: '',
            nama_layanan: '',
            harga: '',
            status: 'active'
        },

        init() {
            this.loadCategories();
            this.loadLayanan();
        },

        get filteredLayanan() {
            if (this.activeTab === 'all') {
                return this.layanan;
            }
            return this.layanan.filter(l => l.id_kategori == this.activeTab);
        },

        async loadCategories() {
            try {
                const response = await fetch('api/layanan.php?action=get_categories');
                const data = await response.json();
                if (data.success) {
                    this.categories = data.data;
                }
            } catch (error) {
                console.error('Error loading categories:', error);
            }
        },

        async loadLayanan() {
            try {
                const response = await fetch('api/layanan.php?action=get_layanan');
                const data = await response.json();
                if (data.success) {
                    this.layanan = data.data;
                }
            } catch (error) {
                console.error('Error loading layanan:', error);
            }
        },

        openKategoriModal() {
            this.kategoriForm = { nama_kategori: '' };
            this.showKategoriModal = true;
        },

        openLayananModal() {
            this.layananForm = { id: null, id_kategori: '', nama_layanan: '', harga: '', status: 'active' };
            this.showLayananModal = true;
        },

        async saveKategori() {
            try {
                const formData = new FormData();
                formData.append('action', 'add_category');
                formData.append('nama_kategori', this.kategoriForm.nama_kategori);

                const response = await fetch('api/layanan.php', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();
                
                if (data.success) {
                    showToast('Kategori berhasil ditambahkan', 'success');
                    this.showKategoriModal = false;
                    this.loadCategories();
                } else {
                    showToast(data.message, 'error');
                }
            } catch (error) {
                showToast('Terjadi kesalahan', 'error');
            }
        },

        editLayanan(layanan) {
            this.layananForm = { ...layanan };
            this.showLayananModal = true;
        },

        async saveLayanan() {
            try {
                const formData = new FormData();
                formData.append('action', this.layananForm.id ? 'update_layanan' : 'add_layanan');
                if (this.layananForm.id) {
                    formData.append('id', this.layananForm.id);
                }
                formData.append('id_kategori', this.layananForm.id_kategori);
                formData.append('nama_layanan', this.layananForm.nama_layanan);
                formData.append('harga', this.layananForm.harga);
                formData.append('status', this.layananForm.status);

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

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

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

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

        formatRupiah(angka) {
            return 'Rp ' + parseInt(angka).toLocaleString('id-ID');
        }
    }
}
</script>

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

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