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

// Check if edit mode
$booking_id = intval($_GET['id'] ?? 0);
$is_edit = $booking_id > 0;
?>

<div class="px-4 sm:px-0" x-data="bookingApp(<?php echo $booking_id; ?>)">
    <div class="flex justify-between items-center mb-8">
        <h1 class="text-3xl font-bold text-gray-900" x-text="isEdit ? 'Edit Booking' : 'Buat Booking Baru'"></h1>
        <a href="riwayat-booking.php" class="text-gray-600 hover:text-gray-800">
            ← Kembali ke Riwayat
        </a>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Form Input -->
        <div class="lg:col-span-2 space-y-6">
            <!-- Info Organisasi -->
            <div class="bg-white rounded-lg shadow-md p-6">
                <h2 class="text-lg font-semibold text-gray-900 mb-4">Info Organisasi</h2>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="md:col-span-2">
                        <label class="block text-gray-700 text-sm font-medium mb-2">Nama Organisasi/Instansi *</label>
                        <input type="text" x-model="form.nama_organisasi" required
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
                               placeholder="Contoh: SD Negeri 1 Malang">
                    </div>
                    
                    <div>
                        <label class="block text-gray-700 text-sm font-medium mb-2">Nama PIC *</label>
                        <input type="text" x-model="form.nama_pic" required
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
                               placeholder="Penanggung jawab">
                    </div>
                    
                    <div>
                        <label class="block text-gray-700 text-sm font-medium mb-2">No Telepon/WA *</label>
                        <input type="text" x-model="form.no_telepon" required
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
                               placeholder="08xxxxxxxxxx">
                    </div>
                    
                    <div class="md:col-span-2">
                        <label class="block text-gray-700 text-sm font-medium mb-2">Tanggal Kedatangan *</label>
                        <input type="date" x-model="form.tanggal_kedatangan" required
                               :min="new Date().toISOString().split('T')[0]"
                               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>

            <!-- Items -->
            <div class="bg-white rounded-lg shadow-md p-6">
                <h2 class="text-lg font-semibold text-gray-900 mb-4">Pilih Layanan</h2>
                
                <!-- Loading State -->
                <template x-if="loadingLayanan">
                    <div class="text-center py-8 text-gray-500 mb-6">
                        <svg class="animate-spin h-8 w-8 mx-auto mb-2 text-primary" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        Memuat layanan...
                    </div>
                </template>
                
                <!-- Button Layanan per Kategori -->
                <div x-show="!loadingLayanan" class="space-y-4 mb-6">
                    <template x-if="layanan.length === 0">
                        <div class="text-center py-8 text-gray-500">
                            Tidak ada layanan aktif. Hubungi administrator.
                        </div>
                    </template>
                    
                    <template x-for="kategori in groupedLayanan" :key="kategori.name">
                        <div>
                            <h3 class="text-sm font-semibold text-gray-700 mb-2 uppercase tracking-wide" x-text="kategori.name"></h3>
                            <div class="grid grid-cols-2 gap-2">
                                <template x-for="l in kategori.items" :key="l.id">
                                    <button @click="addItemById(l.id)" 
                                            class="group relative bg-gradient-to-br from-primary to-secondary hover:from-secondary hover:to-primary text-white rounded-lg p-4 text-left transition-all duration-200 transform hover:scale-105 shadow-md hover:shadow-lg">
                                        <div class="font-semibold text-base mb-1" x-text="l.nama_layanan"></div>
                                        <div class="text-sm opacity-90" x-text="formatRupiah(l.harga)"></div>
                                        <div class="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity">
                                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                                            </svg>
                                        </div>
                                    </button>
                                </template>
                            </div>
                        </div>
                    </template>
                </div>

                <h3 class="text-md font-semibold text-gray-900 mb-3 border-t pt-4">Daftar Item</h3>
                
                <template x-if="items.length === 0">
                    <div class="text-center py-8 text-gray-500">
                        Belum ada item. Pilih layanan di atas.
                    </div>
                </template>

                <div class="space-y-3">
                    <template x-for="(item, index) in items" :key="index">
                        <div class="flex items-center gap-3 p-3 bg-gray-50 rounded-lg">
                            <div class="flex-1">
                                <p class="font-medium text-gray-900" x-text="item.nama_layanan"></p>
                                <p class="text-sm text-gray-600" x-text="`${formatRupiah(item.harga)} x ${item.quantity}`"></p>
                            </div>
                            
                            <div class="flex items-center gap-2">
                                <button @click="updateQuantity(index, -1)" 
                                        class="w-8 h-8 flex items-center justify-center bg-white border border-gray-300 rounded hover:bg-gray-100">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 12H4"></path>
                                    </svg>
                                </button>
                                <input type="number" :value="item.quantity" @input="setQuantity(index, $event.target.value)" min="1"
                                       class="w-16 px-2 py-1 text-center border border-gray-300 rounded">
                                <button @click="updateQuantity(index, 1)" 
                                        class="w-8 h-8 flex items-center justify-center bg-white border border-gray-300 rounded hover:bg-gray-100">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                                    </svg>
                                </button>
                            </div>
                            
                            <div class="w-32 text-right">
                                <p class="font-semibold text-gray-900" x-text="formatRupiah(item.subtotal)"></p>
                            </div>
                            
                            <button @click="removeItem(index)" class="text-red-600 hover:text-red-800">
                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                                </svg>
                            </button>
                        </div>
                    </template>
                </div>
            </div>
        </div>

        <!-- Summary & Pembayaran -->
        <div class="lg:col-span-1">
            <div class="bg-white rounded-lg shadow-md p-6 sticky top-6">
                <h2 class="text-lg font-semibold text-gray-900 mb-4">Pembayaran</h2>
                
                <div class="space-y-4">
                    <div>
                        <div class="flex justify-between text-gray-600 mb-1">
                            <span>Subtotal:</span>
                            <span class="font-semibold" x-text="formatRupiah(subtotal)"></span>
                        </div>
                    </div>
                    
                    <div>
                        <label class="block text-gray-700 text-sm font-medium mb-2">Diskon (Rp)</label>
                        <input type="number" x-model.number="form.diskon" min="0" :max="subtotal" step="1000"
                               @input="calculateTotal()"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
                               placeholder="0">
                        <p x-show="form.diskon > subtotal" class="text-xs text-red-600 mt-1">Diskon tidak boleh lebih dari subtotal</p>
                    </div>
                    
                    <div class="border-t pt-3">
                        <div class="flex justify-between text-lg font-bold text-gray-900 mb-3">
                            <span>Total:</span>
                            <span x-text="formatRupiah(total)"></span>
                        </div>
                    </div>
                    
                    <div>
                        <label class="block text-gray-700 text-sm font-medium mb-2">DP/Uang Muka (Rp)</label>
                        <input type="number" x-model.number="form.dp" min="0" :max="total" step="10000"
                               @input="calculateSisa()"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
                               placeholder="0">
                        <p x-show="form.dp > total" class="text-xs text-red-600 mt-1">DP tidak boleh lebih dari total</p>
                    </div>
                    
                    <div class="border-t pt-3">
                        <div class="flex justify-between text-lg font-bold text-red-600">
                            <span>Sisa Pembayaran:</span>
                            <span x-text="formatRupiah(sisa)"></span>
                        </div>
                    </div>
                </div>

                <div class="space-y-2 mt-6">
                    <button @click="saveBooking()" :disabled="!canSave || saving"
                            :class="!canSave ? 'bg-gray-300 cursor-not-allowed' : 'bg-primary hover:bg-secondary'"
                            class="w-full text-white font-semibold py-3 px-4 rounded-lg transition duration-200">
                        <span x-show="!saving" x-text="isEdit ? 'Update Booking' : 'Simpan & Cetak Booking'"></span>
                        <span x-show="saving">Menyimpan...</span>
                    </button>
                    
                    <button @click="resetForm()" :disabled="items.length === 0 && !form.nama_organisasi"
                            class="w-full bg-gray-200 hover:bg-gray-300 text-gray-800 font-semibold py-3 px-4 rounded-lg transition duration-200">
                        Reset
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function bookingApp(bookingId = 0) {
    return {
        isEdit: bookingId > 0,
        bookingId: bookingId,
        layanan: [],
        items: [],
        saving: false,
        loadingLayanan: true,
        form: {
            nama_organisasi: '',
            nama_pic: '',
            no_telepon: '',
            tanggal_kedatangan: '',
            diskon: 0,
            dp: 0
        },

        init() {
            this.loadLayanan();
            if (this.isEdit) {
                this.loadBooking();
            }
        },

        get groupedLayanan() {
            const groups = {};
            this.layanan.forEach(l => {
                if (!groups[l.kategori_nama]) {
                    groups[l.kategori_nama] = {
                        name: l.kategori_nama,
                        items: []
                    };
                }
                groups[l.kategori_nama].items.push(l);
            });
            return Object.values(groups);
        },

        get subtotal() {
            return this.items.reduce((sum, item) => sum + item.subtotal, 0);
        },

        get total() {
            const t = this.subtotal - (this.form.diskon || 0);
            return t < 0 ? 0 : t;
        },

        get sisa() {
            const s = this.total - (this.form.dp || 0);
            return s < 0 ? 0 : s;
        },

        get canSave() {
            return this.form.nama_organisasi && 
                   this.form.nama_pic && 
                   this.form.no_telepon && 
                   this.form.tanggal_kedatangan && 
                   this.items.length > 0 &&
                   this.form.diskon <= this.subtotal &&
                   this.form.dp <= this.total;
        },

        async loadLayanan() {
            this.loadingLayanan = true;
            try {
                const response = await fetch('api/layanan.php?action=get_layanan_active');
                const data = await response.json();
                if (data.success) {
                    this.layanan = data.data || [];
                } else {
                    this.layanan = [];
                    showToast('Gagal memuat layanan', 'error');
                }
            } catch (error) {
                console.error('Error loading layanan:', error);
                this.layanan = [];
                showToast('Terjadi kesalahan saat memuat layanan', 'error');
            } finally {
                this.loadingLayanan = false;
            }
        },

        async loadBooking() {
            try {
                const response = await fetch(`api/booking.php?action=get_booking&id=${this.bookingId}`);
                const data = await response.json();
                
                if (data.success) {
                    const booking = data.data;
                    this.form.nama_organisasi = booking.nama_organisasi;
                    this.form.nama_pic = booking.nama_pic;
                    this.form.no_telepon = booking.no_telepon;
                    this.form.tanggal_kedatangan = booking.tanggal_kedatangan;
                    this.form.diskon = parseFloat(booking.diskon);
                    this.form.dp = parseFloat(booking.dp);
                    
                    // Load items
                    this.items = booking.details.map(d => ({
                        id_layanan: d.id_layanan,
                        nama_layanan: d.nama_layanan,
                        harga: parseFloat(d.harga),
                        quantity: d.quantity,
                        subtotal: parseFloat(d.subtotal)
                    }));
                } else {
                    showToast(data.message, 'error');
                    window.location.href = 'riwayat-booking.php';
                }
            } catch (error) {
                showToast('Gagal memuat data booking', 'error');
            }
        },

        addItemById(layananId) {
            if (!layananId) return;
            
            // Validasi layanan sudah loaded dan berupa array
            if (!Array.isArray(this.layanan) || this.layanan.length === 0) {
                showToast('Layanan belum dimuat. Harap tunggu...', 'error');
                return;
            }

            const layanan = this.layanan.find(l => l.id == layananId);
            if (!layanan) {
                showToast('Layanan tidak ditemukan', 'error');
                return;
            }

            const existingIndex = this.items.findIndex(i => i.id_layanan == layanan.id);
            if (existingIndex >= 0) {
                this.updateQuantity(existingIndex, 1);
                showToast(`${layanan.nama_layanan} +1`, 'success');
            } else {
                this.items.push({
                    id_layanan: layanan.id,
                    nama_layanan: layanan.nama_layanan,
                    harga: parseFloat(layanan.harga),
                    quantity: 1,
                    subtotal: parseFloat(layanan.harga)
                });
                showToast(`${layanan.nama_layanan} ditambahkan`, 'success');
            }
        },

        updateQuantity(index, change) {
            this.items[index].quantity += change;
            if (this.items[index].quantity < 1) {
                this.items[index].quantity = 1;
            }
            this.items[index].subtotal = this.items[index].harga * this.items[index].quantity;
        },

        setQuantity(index, value) {
            const qty = parseInt(value) || 1;
            this.items[index].quantity = qty < 1 ? 1 : qty;
            this.items[index].subtotal = this.items[index].harga * this.items[index].quantity;
        },

        removeItem(index) {
            this.items.splice(index, 1);
        },

        calculateTotal() {
            // Auto-trigger recalculation
            this.$nextTick();
        },

        calculateSisa() {
            // Auto-trigger recalculation
            this.$nextTick();
        },

        async saveBooking() {
            if (!this.canSave) return;
            if (!confirm(this.isEdit ? 'Update booking ini?' : 'Simpan booking ini?')) return;

            this.saving = true;

            try {
                const formData = new FormData();
                formData.append('action', this.isEdit ? 'update_booking' : 'save_booking');
                if (this.isEdit) {
                    formData.append('id', this.bookingId);
                }
                formData.append('nama_organisasi', this.form.nama_organisasi);
                formData.append('nama_pic', this.form.nama_pic);
                formData.append('no_telepon', this.form.no_telepon);
                formData.append('tanggal_kedatangan', this.form.tanggal_kedatangan);
                formData.append('items', JSON.stringify(this.items));
                formData.append('subtotal', this.subtotal);
                formData.append('diskon', this.form.diskon || 0);
                formData.append('total', this.total);
                formData.append('dp', this.form.dp || 0);
                formData.append('sisa', this.sisa);

                const response = await fetch('api/booking.php', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();

                if (data.success) {
                    showToast(this.isEdit ? 'Booking berhasil diupdate' : 'Booking berhasil disimpan', 'success');
                    window.location.href = `print-booking.php?id=${data.data.id}`;
                } else {
                    showToast(data.message, 'error');
                }
            } catch (error) {
                showToast('Terjadi kesalahan', 'error');
            } finally {
                this.saving = false;
            }
        },

        resetForm() {
            if (!confirm('Reset form? Semua data akan dihapus.')) return;
            
            this.form = {
                nama_organisasi: '',
                nama_pic: '',
                no_telepon: '',
                tanggal_kedatangan: '',
                diskon: 0,
                dp: 0
            };
            this.items = [];
            this.selectedLayananId = '';
        },

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

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