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

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

    <!-- Filter -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
                <label class="block text-gray-700 text-sm font-medium mb-2">Dari Tanggal</label>
                <input type="date" x-model="filter.dari" @change="loadPengeluaran()"
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary">
            </div>
            <div>
                <label class="block text-gray-700 text-sm font-medium mb-2">Sampai Tanggal</label>
                <input type="date" x-model="filter.sampai" @change="loadPengeluaran()"
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary">
            </div>
            <div>
                <label class="block text-gray-700 text-sm font-medium mb-2">Cari</label>
                <input type="text" x-model="filter.search" @input="debounceSearch()" placeholder="Cari kategori/deskripsi..."
                       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>

    <!-- Summary -->
    <div class="bg-gradient-to-r from-red-500 to-red-600 rounded-lg shadow-md p-6 mb-6">
        <div class="text-white">
            <p class="text-sm opacity-90">Total Pengeluaran</p>
            <p class="text-3xl font-bold mt-2" x-text="formatRupiah(totalPengeluaran)"></p>
            <p class="text-sm opacity-75 mt-1" x-text="`${pengeluaran.length} transaksi`"></p>
        </div>
    </div>

    <!-- List Pengeluaran -->
    <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">Tanggal</th>
                        <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">Deskripsi</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Nominal</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Petugas</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 && pengeluaran.length === 0">
                        <tr>
                            <td colspan="6" class="px-6 py-8 text-center text-gray-500">
                                Belum ada data pengeluaran
                            </td>
                        </tr>
                    </template>
                    
                    <template x-for="item in pengeluaran" :key="item.id">
                        <tr class="hover:bg-gray-50">
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600" x-text="formatTanggal(item.tanggal)"></td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="px-2 py-1 text-xs font-semibold bg-blue-100 text-blue-800 rounded-full" x-text="item.kategori"></span>
                            </td>
                            <td class="px-6 py-4 text-sm text-gray-600" x-text="item.deskripsi"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-semibold text-red-600" x-text="formatRupiah(item.nominal)"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600" x-text="item.petugas"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm space-x-2">
                                <button @click="editPengeluaran(item)" class="text-blue-600 hover:text-blue-800">Edit</button>
                                <button @click="deletePengeluaran(item.id)" class="text-red-600 hover:text-red-800">Hapus</button>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Modal -->
    <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="savePengeluaran()">
                    <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 Pengeluaran' : 'Tambah Pengeluaran'"></h3>
                        
                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-medium mb-2">Tanggal *</label>
                            <input type="date" x-model="form.tanggal" 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">Kategori *</label>
                            <input type="text" x-model="form.kategori" required list="kategori-list"
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
                                   placeholder="Contoh: Operasional, Pemeliharaan">
                            <datalist id="kategori-list">
                                <option value="Operasional">
                                <option value="Pemeliharaan">
                                <option value="Gaji">
                                <option value="Utilitas">
                                <option value="Lain-lain">
                            </datalist>
                        </div>

                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-medium mb-2">Deskripsi</label>
                            <textarea x-model="form.deskripsi" rows="3"
                                      class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
                                      placeholder="Detail pengeluaran"></textarea>
                        </div>

                        <div class="mb-4">
                            <label class="block text-gray-700 text-sm font-medium mb-2">Nominal *</label>
                            <input type="number" x-model="form.nominal" 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"
                                   placeholder="0">
                        </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>
</div>

<script>
function pengeluaranApp() {
    return {
        pengeluaran: [],
        showModal: false,
        loading: false,
        filter: {
            dari: '',
            sampai: '',
            search: ''
        },
        form: {
            id: null,
            tanggal: '',
            kategori: '',
            deskripsi: '',
            nominal: ''
        },
        searchTimeout: null,

        init() {
            const today = new Date();
            const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
            this.filter.dari = firstDay.toISOString().split('T')[0];
            this.filter.sampai = today.toISOString().split('T')[0];
            this.loadPengeluaran();
        },

        get totalPengeluaran() {
            return this.pengeluaran.reduce((sum, item) => sum + parseFloat(item.nominal), 0);
        },

        async loadPengeluaran() {
            this.loading = true;
            try {
                const params = new URLSearchParams({
                    action: 'get_pengeluaran',
                    dari: this.filter.dari,
                    sampai: this.filter.sampai,
                    search: this.filter.search
                });
                
                const response = await fetch(`api/pengeluaran.php?${params}`);
                const data = await response.json();
                
                if (data.success) {
                    this.pengeluaran = data.data;
                }
            } catch (error) {
                console.error('Error loading pengeluaran:', error);
            } finally {
                this.loading = false;
            }
        },

        debounceSearch() {
            clearTimeout(this.searchTimeout);
            this.searchTimeout = setTimeout(() => this.loadPengeluaran(), 500);
        },

        openModal() {
            this.form = {
                id: null,
                tanggal: new Date().toISOString().split('T')[0],
                kategori: '',
                deskripsi: '',
                nominal: ''
            };
            this.showModal = true;
        },

        editPengeluaran(item) {
            this.form = { ...item };
            this.showModal = true;
        },

        async savePengeluaran() {
            try {
                const formData = new FormData();
                formData.append('action', this.form.id ? 'update_pengeluaran' : 'add_pengeluaran');
                if (this.form.id) {
                    formData.append('id', this.form.id);
                }
                formData.append('tanggal', this.form.tanggal);
                formData.append('kategori', this.form.kategori);
                formData.append('deskripsi', this.form.deskripsi);
                formData.append('nominal', this.form.nominal);

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

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

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

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

        formatRupiah(angka) {
            return 'Rp ' + parseInt(angka).toLocaleString('id-ID');
        },

        formatTanggal(date) {
            const d = new Date(date);
            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'; ?>
