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

<div class="px-4 sm:px-0" x-data="riwayatStrukApp()">
    <div class="flex justify-between items-center mb-8">
        <h1 class="text-3xl font-bold text-gray-900">Riwayat Struk</h1>
        <a href="struk.php" class="bg-primary hover:bg-secondary text-white px-4 py-2 rounded-lg">
            + Buat Struk 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</label>
                <input type="date" x-model="filter.dari" @change="loadTransaksi()"
                       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="loadTransaksi()"
                       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 ID/Kasir..."
                       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="grid grid-cols-1 md:grid-cols-2 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 Transaksi</p>
                <p class="text-3xl font-bold mt-2" x-text="transaksi.length"></p>
                <p class="text-sm opacity-75 mt-1">Transaksi 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 Pendapatan</p>
                <p class="text-3xl font-bold mt-2" x-text="formatRupiah(totalPendapatan)"></p>
                <p class="text-sm opacity-75 mt-1">Periode terpilih</p>
            </div>
        </div>
    </div>

    <!-- List Transaksi -->
    <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">No. Struk</th>
                        <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">Total</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Kasir</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="5" class="px-6 py-8 text-center text-gray-500">
                                Loading...
                            </td>
                        </tr>
                    </template>
                    
                    <template x-if="!loading && transaksi.length === 0">
                        <tr>
                            <td colspan="5" class="px-6 py-8 text-center text-gray-500">
                                Belum ada transaksi
                            </td>
                        </tr>
                    </template>
                    
                    <template x-for="item in transaksi" :key="item.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(item.id).padStart(6, '0')}`"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600" x-text="formatDateTime(item.created_at)"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-semibold text-green-600" x-text="formatRupiah(item.total)"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600" x-text="item.kasir"></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm">
                                <a :href="`print-struk.php?id=${item.id}`" target="_blank" class="text-blue-600 hover:text-blue-800">
                                    Lihat Struk
                                </a>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
function riwayatStrukApp() {
    return {
        transaksi: [],
        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 = today.toISOString().split('T')[0];
            this.loadTransaksi();
        },

        get totalPendapatan() {
            return this.transaksi.reduce((sum, item) => sum + parseFloat(item.total), 0);
        },

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

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

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

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

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