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

<div class="px-4 sm:px-0" x-data="riwayatBookingApp()">
    <div class="flex justify-between items-center mb-8">
        <h1 class="text-3xl font-bold text-gray-900">Riwayat Booking</h1>
        <a href="booking.php" class="bg-primary hover:bg-secondary text-white px-4 py-2 rounded-lg">
            + Buat Booking Baru
        </a>
    </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 Kedatangan</label>
                <input type="date" x-model="filter.dari" @change="loadBookings()"
                       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 Kedatangan</label>
                <input type="date" x-model="filter.sampai" @change="loadBookings()"
                       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 organisasi/PIC/telp..."
                       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 Cards -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
        <div class="bg-gradient-to-r from-blue-500 to-blue-600 rounded-lg shadow-md p-6">
            <div class="text-white">
                <p class="text-sm opacity-90">Total Booking</p>
                <p class="text-3xl font-bold mt-2" x-text="bookings.length"></p>
                <p class="text-sm opacity-75 mt-1">Booking terpilih</p>
            </div>
        </div>
        
        <div class="bg-gradient-to-r from-green-500 to-green-600 rounded-lg shadow-md p-6">
            <div class="text-white">
                <p class="text-sm opacity-90">Total Nilai Booking</p>
                <p class="text-3xl font-bold mt-2" x-text="formatRupiah(totalNilai)"></p>
                <p class="text-sm opacity-75 mt-1">Nilai keseluruhan</p>
            </div>
        </div>
        
        <div class="bg-gradient-to-r from-purple-500 to-purple-600 rounded-lg shadow-md p-6">
            <div class="text-white">
                <p class="text-sm opacity-90">Total DP Terkumpul</p>
                <p class="text-3xl font-bold mt-2" x-text="formatRupiah(totalDP)"></p>
                <p class="text-sm opacity-75 mt-1">DP yang sudah dibayar</p>
            </div>
        </div>
        
        <div class="bg-gradient-to-r from-red-500 to-red-600 rounded-lg shadow-md p-6">
            <div class="text-white">
                <p class="text-sm opacity-90">Total Sisa Piutang</p>
                <p class="text-3xl font-bold mt-2" x-text="formatRupiah(totalSisa)"></p>
                <p class="text-sm opacity-75 mt-1">Belum dibayar</p>
            </div>
        </div>
    </div>

    <!-- List Booking -->
    <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">Organisasi</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">PIC</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Telp</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Tgl Kedatangan</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Subtotal</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Diskon</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Total</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">DP</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Sisa</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="11" class="px-6 py-8 text-center text-gray-500">
                                Loading...
                            </td>
                        </tr>
                    </template>
                    
                    <template x-if="!loading && bookings.length === 0">
                        <tr>
                            <td colspan="11" class="px-6 py-8 text-center text-gray-500">
                                Belum ada booking
                            </td>
                        </tr>
                    </template>
                    
                    <template x-for="booking in bookings" :key="booking.id">
                        <tr class="hover:bg-gray-50">
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900" x-text="`#${String(booking.id).padStart(6, '0')}`"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900" x-text="booking.nama_organisasi"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600" x-text="booking.nama_pic"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600" x-text="booking.no_telepon"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600" x-text="formatDate(booking.tanggal_kedatangan)"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900" x-text="formatRupiah(booking.subtotal)"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-red-600" x-text="formatRupiah(booking.diskon)"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-semibold text-gray-900" x-text="formatRupiah(booking.total)"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-green-600" x-text="formatRupiah(booking.dp)"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-semibold text-red-600" x-text="formatRupiah(booking.sisa)"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm space-x-2">
                                <a :href="`booking.php?id=${booking.id}`" class="text-blue-600 hover:text-blue-800" title="Edit">
                                    <svg class="w-5 h-5 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                                    </svg>
                                </a>
                                <button @click="deleteBooking(booking.id)" class="text-red-600 hover:text-red-800" title="Hapus">
                                    <svg class="w-5 h-5 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                    </svg>
                                </button>
                                <a :href="`print-booking.php?id=${booking.id}`" target="_blank" class="text-green-600 hover:text-green-800" title="Cetak">
                                    <svg class="w-5 h-5 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"></path>
                                    </svg>
                                </a>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
function riwayatBookingApp() {
    return {
        bookings: [],
        loading: false,
        filter: {
            dari: '',
            sampai: '',
            search: ''
        },
        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 = new Date(today.getFullYear(), today.getMonth() + 1, 0).toISOString().split('T')[0];
            this.loadBookings();
        },

        get totalNilai() {
            return this.bookings.reduce((sum, b) => sum + parseFloat(b.total), 0);
        },

        get totalDP() {
            return this.bookings.reduce((sum, b) => sum + parseFloat(b.dp), 0);
        },

        get totalSisa() {
            return this.bookings.reduce((sum, b) => sum + parseFloat(b.sisa), 0);
        },

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

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

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

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

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

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

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

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