<?php
$pageTitle = 'Laporan Keuangan';
require_once 'includes/header.php';
requireAdmin();
?>

<div class="px-4 sm:px-0" x-data="laporanApp()">
    <div class="flex justify-between items-center mb-8">
        <h1 class="text-3xl font-bold text-gray-900">Laporan Keuangan</h1>
    </div>

    <!-- Filter Controls -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div>
                <label class="block text-gray-700 text-sm font-medium mb-2">Periode</label>
                <select x-model="filter.periode" @change="updateDateFields()"
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary">
                    <option value="harian">Harian</option>
                    <option value="mingguan">Mingguan</option>
                    <option value="bulanan">Bulanan</option>
                </select>
            </div>
            
            <!-- Harian -->
            <div x-show="filter.periode === 'harian'" class="md:col-span-2">
                <label class="block text-gray-700 text-sm font-medium mb-2">Pilih Tanggal</label>
                <input type="date" x-model="filter.tanggal"
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary">
            </div>
            
            <!-- Mingguan -->
            <template x-if="filter.periode === 'mingguan'">
                <div>
                    <label class="block text-gray-700 text-sm font-medium mb-2">Dari Tanggal</label>
                    <input type="date" x-model="filter.minggu_dari"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary">
                </div>
            </template>
            
            <template x-if="filter.periode === 'mingguan'">
                <div>
                    <label class="block text-gray-700 text-sm font-medium mb-2">Sampai Tanggal</label>
                    <input type="date" x-model="filter.minggu_sampai"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary">
                </div>
            </template>
            
            <!-- Bulanan -->
            <div x-show="filter.periode === 'bulanan'" class="md:col-span-2">
                <label class="block text-gray-700 text-sm font-medium mb-2">Pilih Bulan</label>
                <input type="month" x-model="filter.bulan"
                       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="flex items-end gap-2">
                <button @click="loadLaporan()" :disabled="loading"
                        class="flex-1 bg-primary hover:bg-secondary text-white font-semibold py-2 px-4 rounded-lg transition duration-200">
                    <span x-show="!loading">Tampilkan</span>
                    <span x-show="loading">Loading...</span>
                </button>
                <button @click="exportExcel()" :disabled="!hasData"
                        class="bg-green-600 hover:bg-green-700 text-white font-semibold py-2 px-4 rounded-lg transition duration-200">
                    Excel
                </button>
                <button @click="exportPDF()" :disabled="!hasData"
                        class="bg-red-600 hover:bg-red-700 text-white font-semibold py-2 px-4 rounded-lg transition duration-200">
                    PDF
                </button>
            </div>
        </div>
    </div>

    <!-- Summary Cards -->
    <div x-show="hasData" class="mb-6">
        <!-- Baris 1: 3 Cards -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
            <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 Pendapatan</p>
                    <p class="text-3xl font-bold mt-2" x-text="formatRupiah(summary.pendapatan?.total || 0)"></p>
                    <p class="text-sm opacity-75 mt-1" x-text="`${(summary.pendapatan?.struk.jumlah || 0) + (summary.pendapatan?.booking.jumlah || 0)} transaksi`"></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 Pengeluaran</p>
                    <p class="text-3xl font-bold mt-2" x-text="formatRupiah(summary.pengeluaran?.total || 0)"></p>
                    <p class="text-sm opacity-75 mt-1" x-text="`${summary.pengeluaran?.jumlah || 0} transaksi`"></p>
                </div>
            </div>

            <div :class="labaRugiClass" class="rounded-lg shadow-md p-6">
                <div class="text-white">
                    <p class="text-sm opacity-90">Laba/Rugi</p>
                    <p class="text-3xl font-bold mt-2" x-text="formatRupiah(summary.laba_rugi || 0)"></p>
                    <p class="text-sm opacity-75 mt-1" x-text="summary.laba_rugi >= 0 ? 'Laba' : 'Rugi'"></p>
                </div>
            </div>
        </div>
        
        <!-- Baris 2: 3 cards (khusus untuk bulanan dan mingguan) -->
        <div class="grid grid-cols-1 md:grid-cols-3 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">Rata-rata Pendapatan per Transaksi</p>
                    <p class="text-3xl font-bold mt-2" x-text="formatRupiah(summary.rata_rata_transaksi || 0)"></p>
                </div>
            </div>

        <div class="bg-gradient-to-r from-yellow-500 to-yellow-600 rounded-lg shadow-md p-6">
                <div class="text-white">
                    <p class="text-sm opacity-90">Total Pengunjung</p>
                    <p class="text-3xl font-bold mt-2" x-text="summary.jumlah_pengunjung || 0"></p>
                    <p class="text-sm opacity-75 mt-1" x-text="`${summary.jumlah_pengunjung} pengunjung`"></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">Jumlah Transaksi</p>
                    <p class="text-3xl font-bold mt-2" x-text="summary.jumlah_transaksi || 0"></p>
                    <p class="text-sm opacity-75 mt-1">Total transaksi</p>
                </div>
            </div>
        </div>

    <!-- Chart -->
    <div x-show="hasData" class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h2 class="text-xl font-semibold text-gray-900 mb-4">Grafik Pendapatan vs Pengeluaran</h2>
        <div class="relative" style="height: 400px;">
            <canvas id="laporanChart"></canvas>
        </div>
    </div>

    <!-- Breakdown Tables -->
    <div x-show="hasData" class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
        <!-- Pendapatan -->
        <div class="bg-white rounded-lg shadow-md p-6">
            <h2 class="text-xl font-semibold text-gray-900 mb-4">Detail Pendapatan</h2>
            <div class="space-y-3">
                <div class="flex justify-between items-center pb-3 border-b">
                    <div>
                        <p class="text-sm text-gray-600">Pendapatan Struk</p>
                        <p class="text-xs text-gray-500" x-text="`${summary.pendapatan?.struk.jumlah || 0} transaksi`"></p>
                    </div>
                    <p class="font-semibold text-gray-900" x-text="formatRupiah(summary.pendapatan?.struk.total || 0)"></p>
                </div>
                
                <div class="pb-3 border-b">
                    <div class="flex justify-between items-center mb-2">
                        <div>
                            <p class="text-sm text-gray-600 font-medium">Pendapatan Booking</p>
                            <p class="text-xs text-gray-500" x-text="`${summary.pendapatan?.booking.jumlah || 0} booking`"></p>
                        </div>
                        <p class="font-semibold text-gray-900" x-text="formatRupiah(summary.pendapatan?.booking.total || 0)"></p>
                    </div>
                    <div class="ml-4 space-y-1">
                        <div class="flex justify-between items-center">
                            <p class="text-xs text-gray-500">• DP (saat booking)</p>
                            <p class="text-sm text-gray-700" x-text="formatRupiah(summary.pendapatan?.booking_dp.total || 0)"></p>
                        </div>
                        <div class="flex justify-between items-center">
                            <p class="text-xs text-gray-500">• Lunas (saat kedatangan)</p>
                            <p class="text-sm text-gray-700" x-text="formatRupiah(summary.pendapatan?.booking_lunas.total || 0)"></p>
                        </div>
                    </div>
                </div>
                
                <div class="flex justify-between items-center pt-3 border-t-2 border-gray-300">
                    <p class="font-bold text-gray-900">Total Pendapatan</p>
                    <p class="font-bold text-green-600 text-lg" x-text="formatRupiah(summary.pendapatan?.total || 0)"></p>
                </div>
            </div>
        </div>
        
        <!-- Pengeluaran -->
        <div class="bg-white rounded-lg shadow-md p-6">
            <h2 class="text-xl font-semibold text-gray-900 mb-4">Detail Pengeluaran</h2>
            <div class="space-y-3">
                <template x-if="summary.pengeluaran?.per_kategori.length === 0">
                    <p class="text-gray-500 text-sm">Tidak ada pengeluaran</p>
                </template>
                
                <template x-for="item in summary.pengeluaran?.per_kategori || []" :key="item.kategori">
                    <div class="flex justify-between items-center pb-3 border-b">
                        <p class="text-sm text-gray-600" x-text="item.kategori"></p>
                        <p class="font-semibold text-gray-900" x-text="formatRupiah(item.total)"></p>
                    </div>
                </template>
                
                <div class="flex justify-between items-center pt-3 border-t-2 border-gray-300">
                    <p class="font-bold text-gray-900">Total Pengeluaran</p>
                    <p class="font-bold text-red-600 text-lg" x-text="formatRupiah(summary.pengeluaran?.total || 0)"></p>
                </div>
            </div>
        </div>
    </div>

    <!-- Laba/Rugi Final -->
    <div x-show="hasData" class="bg-white rounded-lg shadow-md p-6">
        <div class="flex justify-between items-center">
            <div>
                <h2 class="text-2xl font-bold text-gray-900">Laba/Rugi Bersih</h2>
                <p class="text-sm text-gray-600 mt-1">Total Pendapatan - Total Pengeluaran</p>
            </div>
            <div class="text-right">
                <p :class="summary.laba_rugi >= 0 ? 'text-green-600' : 'text-red-600'" 
                   class="text-4xl font-bold" x-text="formatRupiah(summary.laba_rugi || 0)"></p>
                <p :class="summary.laba_rugi >= 0 ? 'text-green-600' : 'text-red-600'" 
                   class="text-lg font-semibold" x-text="summary.laba_rugi >= 0 ? 'Laba' : 'Rugi'"></p>
            </div>
        </div>
    </div>
</div>

<script>
function laporanApp() {
    return {
        filter: {
            periode: 'harian',
            tanggal: new Date().toISOString().split('T')[0],
            minggu_dari: '',
            minggu_sampai: '',
            bulan: new Date().toISOString().slice(0, 7)
        },
        summary: {},
        chartData: {},
        loading: false,
        hasData: false,
        chart: null,

        init() {
            // Set default untuk mingguan (awal minggu ini sampai hari ini)
            const today = new Date();
            const firstDay = new Date(today.setDate(today.getDate() - today.getDay()));
            this.filter.minggu_dari = firstDay.toISOString().split('T')[0];
            this.filter.minggu_sampai = new Date().toISOString().split('T')[0];
        },

        get labaRugiClass() {
            return this.summary.laba_rugi >= 0 
                ? 'bg-gradient-to-r from-blue-500 to-blue-600' 
                : 'bg-gradient-to-r from-orange-500 to-orange-600';
        },

        updateDateFields() {
            // Reset fields when periode changes
            this.$nextTick();
        },

        async loadLaporan() {
            this.loading = true;
            this.hasData = false;
            
            try {
                // Load summary
                const params = new URLSearchParams({
                    action: 'get_laporan_summary',
                    periode: this.filter.periode,
                    tanggal: this.filter.tanggal,
                    minggu_dari: this.filter.minggu_dari,
                    minggu_sampai: this.filter.minggu_sampai,
                    bulan: this.filter.bulan
                });
                
                const response = await fetch(`api/laporan.php?${params}`);
                const data = await response.json();
                
                if (data.success) {
                    this.summary = data.data;
                    this.hasData = true;
                    
                    // Load chart data
                    await this.loadChart();
                } else {
                    showToast(data.message, 'error');
                }
            } catch (error) {
                showToast('Terjadi kesalahan', 'error');
                console.error(error);
            } finally {
                this.loading = false;
            }
        },

        async loadChart() {
            try {
                const params = new URLSearchParams({
                    action: 'get_chart_data',
                    periode: this.filter.periode,
                    tanggal: this.filter.tanggal,
                    minggu_dari: this.filter.minggu_dari,
                    minggu_sampai: this.filter.minggu_sampai,
                    bulan: this.filter.bulan
                });
                
                const response = await fetch(`api/laporan.php?${params}`);
                const data = await response.json();
                
                if (data.success) {
                    this.chartData = data.data;
                    this.renderChart();
                }
            } catch (error) {
                console.error('Error loading chart:', error);
            }
        },

        renderChart() {
            const ctx = document.getElementById('laporanChart');
            
            // Destroy existing chart
            if (this.chart) {
                this.chart.destroy();
            }
            
            this.chart = new Chart(ctx, {
                type: 'bar',
                data: this.chartData,
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: function(value) {
                                    return 'Rp ' + value.toLocaleString('id-ID');
                                }
                            }
                        }
                    },
                    plugins: {
                        legend: {
                            display: true,
                            position: 'top'
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    let label = context.dataset.label || '';
                                    if (label) {
                                        label += ': ';
                                    }
                                    label += 'Rp ' + context.parsed.y.toLocaleString('id-ID');
                                    return label;
                                }
                            }
                        }
                    }
                }
            });
        },

        exportExcel() {
            if (!this.hasData) return;
            
            const params = new URLSearchParams({
                action: 'export_excel',
                periode: this.filter.periode,
                tanggal: this.filter.tanggal,
                minggu_dari: this.filter.minggu_dari,
                minggu_sampai: this.filter.minggu_sampai,
                bulan: this.filter.bulan
            });
            
            window.open(`api/laporan.php?${params}`, '_blank');
        },

        exportPDF() {
            if (!this.hasData) return;
            
            const params = new URLSearchParams({
                action: 'export_pdf',
                periode: this.filter.periode,
                tanggal: this.filter.tanggal,
                minggu_dari: this.filter.minggu_dari,
                minggu_sampai: this.filter.minggu_sampai,
                bulan: this.filter.bulan
            });
            
            window.open(`api/laporan.php?${params}`, '_blank');
        },

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

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