<?php
// ========== ANTI CACHE - SOLUSI DATA HILANG ==========
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
// =====================================================

$page_title = 'Riwayat Transaksi';
include 'includes/header.php';
?>

<div class="container">
    <div class="card">
        <h2>📝 Riwayat Transaksi</h2>

        <div style="display:flex;gap:10px;margin-bottom:20px;flex-wrap:wrap;">
            <select id="filterMonth" style="flex:1;min-width:120px;padding:10px;border:2px solid var(--border);border-radius:8px;">
                <option value="">Semua Bulan</option>
            </select>
            <select id="filterYear" style="flex:1;min-width:120px;padding:10px;border:2px solid var(--border);border-radius:8px;">
                <option value="">Semua Tahun</option>
            </select>
            <select id="filterType" style="flex:1;min-width:120px;padding:10px;border:2px solid var(--border);border-radius:8px;">
                <option value="">Semua Jenis</option>
                <option value="income">Pemasukan</option>
                <option value="expense">Pengeluaran</option>
            </select>
                        <select id="filterCategory" style="flex:1;min-width:120px;padding:10px;border:2px solid var(--border);border-radius:8px;">
                <option value="">Semua Kategori</option>
            </select>

        </div>
        <div id="totalInfo" style="display:none;background:#e8f4f8;padding:15px;border-radius:8px;margin-bottom:15px;font-weight:bold;color:#186d7e;"></div>

        <div id="transactionsList"></div>
        <button id="loadMoreBtn" onclick="loadMore()" style="width:100%;padding:12px;margin-top:15px;background:var(--primary);color:white;border:none;border-radius:8px;cursor:pointer;font-weight:600;display:none;">Lihat Lainnya</button>
    </div>
</div>

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

<div id="editModal" style="display:none;position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.5);z-index:999;overflow-y:auto;">
    <div style="background:var(--surface);border-radius:12px;margin:20px auto;max-width:500px;padding:30px;">
        <h3 style="margin-top:0;">Edit Transaksi</h3>
        <div style="margin-bottom:15px;">
            <label style="display:block;margin-bottom:5px;">Tanggal</label>
            <input type="date" id="editDate" style="width:100%;padding:10px;border:1px solid var(--border);border-radius:6px;">
        </div>
        <div style="margin-bottom:15px;">
            <label style="display:block;margin-bottom:5px;">Kategori</label>
            <input type="text" id="editCategory" style="width:100%;padding:10px;border:1px solid var(--border);border-radius:6px;">
        </div>
        <div style="margin-bottom:15px;">
            <label style="display:block;margin-bottom:5px;">Deskripsi</label>
            <textarea id="editDescription" style="width:100%;padding:10px;border:1px solid var(--border);border-radius:6px;"></textarea>
        </div>
        <div style="margin-bottom:15px;">
            <label style="display:block;margin-bottom:5px;">Jumlah</label>
            <input type="number" id="editAmount" style="width:100%;padding:10px;border:1px solid var(--border);border-radius:6px;">
        </div>
        <div style="display:flex;gap:10px;">
            <button onclick="saveEdit()" class="btn btn-primary" style="flex:1;">Simpan</button>
            <button onclick="closeEditModal()" class="btn btn-secondary" style="flex:1;">Batal</button>
        </div>
    </div>
</div>

<script>
    const months = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
    const ITEMS_PER_PAGE = 25;
    
    let transactions = [];
    let editingId = null;
    let displayedCount = ITEMS_PER_PAGE;  // PERBAIKAN: Default 25 item dari awal
    let filteredTransactions = [];

    function formatCurrency(amount) {
        return 'Rp ' + Math.floor(amount).toLocaleString('id-ID');
    }

    function formatDate(dateStr) {
        const date = new Date(dateStr);
        return date.toLocaleDateString('id-ID', { year: 'numeric', month: 'long', day: 'numeric' });
    }
        function populateCategories() {
        const categories = [...new Set(transactions.map(t => t.category))].filter(Boolean).sort();
        
        const filterCategory = document.getElementById('filterCategory');
        filterCategory.innerHTML = '<option value="">Semua Kategori</option>' +
            categories.map(cat => `<option value="${cat}">${cat}</option>`).join('');
        
        const savedCategory = localStorage.getItem('filterCategory');
        if (savedCategory !== null) {
            filterCategory.value = savedCategory;
        }
    }


    function saveFilterStates() {
        localStorage.setItem('filterMonth', document.getElementById('filterMonth').value);
        localStorage.setItem('filterYear', document.getElementById('filterYear').value);
        localStorage.setItem('filterType', document.getElementById('filterType').value);
        localStorage.setItem('filterCategory', document.getElementById('filterCategory').value);
        localStorage.setItem('displayedCount', displayedCount);
    }


    function restoreFilterStates() {
        const savedMonth = localStorage.getItem('filterMonth');
        const savedYear = localStorage.getItem('filterYear');
        const savedType = localStorage.getItem('filterType');
        const savedCategory = localStorage.getItem('filterCategory');
        const savedDisplayedCount = localStorage.getItem('displayedCount');

        if (savedMonth !== null) document.getElementById('filterMonth').value = savedMonth;
        if (savedYear !== null) document.getElementById('filterYear').value = savedYear;
        if (savedType !== null) document.getElementById('filterType').value = savedType;
        if (savedCategory !== null) document.getElementById('filterCategory').value = savedCategory;
        
        if (savedDisplayedCount !== null) {
            displayedCount = parseInt(savedDisplayedCount);
        } else {
            displayedCount = ITEMS_PER_PAGE;
        }
    }


    async function loadData() {
        try {
            const response = await fetch('api.php?action=load');
            const data = await response.json();
            transactions = data.transactions || [];
            
            displayTransactions();
            
            return true;
        } catch (error) {
            console.error('Error loading data:', error);
            return false;
        }
    }

    async function saveTransactions() {
        try {
            const response = await fetch('api.php?action=save_transactions', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ transactions }),
                cache: 'no-store'
            });

            if (!response.ok) {
                console.error('Save failed:', response.status);
                return false;
            }

            const result = await response.json();

            if (result.success) {
                const loaded = await loadData();
                return loaded;
            }

            return false;
        } catch (error) {
            console.error('Error saving:', error);
            return false;
        }
    }

    function populateFilters() {
        const years = [...new Set(transactions.map(t => new Date(t.date).getFullYear()))].sort((a, b) => b - a);

        document.getElementById('filterMonth').innerHTML = '<option value="">Semua Bulan</option>' +
            months.map((m, i) => `<option value="${i}">${m}</option>`).join('');

        document.getElementById('filterYear').innerHTML = '<option value="">Semua Tahun</option>' +
            (years.length ? years.map(y => `<option value="${y}">${y}</option>`).join('') : 
            `<option value="${new Date().getFullYear()}">${new Date().getFullYear()}</option>`);

        restoreFilterStates();
    }

    function displayTransactions() {
        const filterMonth = document.getElementById('filterMonth').value;
        const filterYear = document.getElementById('filterYear').value;
        const filterType = document.getElementById('filterType').value;
        const filterCategory = document.getElementById('filterCategory').value;

        let filtered = transactions.filter(trans => {
            const transDate = new Date(trans.date);
            
            if (filterMonth !== '' && transDate.getMonth() !== parseInt(filterMonth)) return false;
            if (filterYear !== '' && transDate.getFullYear() !== parseInt(filterYear)) return false;
            if (filterType !== '' && trans.type !== filterType) return false;
            if (filterCategory !== '' && trans.category !== filterCategory) return false;
            
            return true;
        });


        filtered.sort((a, b) => new Date(b.date) - new Date(a.date));

        filteredTransactions = filtered;

        // PERBAIKAN: Jika displayedCount > filtered.length, set ke filtered.length
        if (displayedCount > filtered.length) {
            displayedCount = filtered.length;
        }

        const container = document.getElementById('transactionsList');

        if (filtered.length === 0) {
            container.innerHTML = '<p style="text-align:center;color:var(--text-secondary);padding:40px;">Tidak ada transaksi</p>';
            document.getElementById('loadMoreBtn').style.display = 'none';
            saveFilterStates();
            return;
        }
                // ========== TAMBAH TOTAL INFO ==========
        let totalAmount = 0;
        filtered.forEach(trans => {
            if (trans.type === 'income') {
                totalAmount += trans.amount;
            } else {
                totalAmount -= trans.amount;
            }
        });

        const totalInfo = document.getElementById('totalInfo');
        if (filterMonth !== '' || filterYear !== '' || filterType !== '' || filterCategory !== '') {
            const labels = [];
            if (filterMonth !== '') labels.push(months[parseInt(filterMonth)]);
            if (filterYear !== '') labels.push(filterYear);
            if (filterType !== '') labels.push(filterType === 'income' ? 'Pemasukan' : 'Pengeluaran');
            if (filterCategory !== '') labels.push(filterCategory);
            
            const label = labels.length > 0 ? labels.join(' - ') : 'Total';
            totalInfo.innerHTML = `${label}: <strong>${totalAmount >= 0 ? '+' : ''}${formatCurrency(totalAmount)}</strong>`;
            totalInfo.style.display = 'block';
        } else {
            totalInfo.style.display = 'none';
        }
        // ==========================================


        // PERBAIKAN: Tampilkan sesuai displayedCount (default 25 dari awal)
        const itemsToShow = filtered.slice(0, displayedCount);

        container.innerHTML = itemsToShow.map(trans => `
            <div style="background:var(--bg);padding:15px;border-radius:8px;margin-bottom:10px;">
                <div style="display:flex;justify-content:space-between;align-items:start;margin-bottom:10px;">
                    <div style="flex:1;">
                        <div style="font-weight:600;margin-bottom:5px;">
                            ${trans.type === 'income' ? '💰' : '💸'} ${trans.category}
                        </div>
                        <div style="font-size:0.85em;color:var(--text-secondary);margin-bottom:5px;">
                            ${trans.description || '-'}
                        </div>
                        <div style="font-size:0.8em;color:var(--text-secondary);">
                            ${formatDate(trans.date)}
                        </div>
                    </div>
                    <div style="text-align:right;">
                        <div style="font-size:1.2em;font-weight:bold;color:${trans.type === 'income' ? '#10b981' : '#ef4444'};margin-bottom:10px;">
                            ${trans.type === 'income' ? '+' : '-'}${formatCurrency(trans.amount)}
                        </div>
                        <button onclick="openEditModal('${trans.id}')" class="btn btn-sm" style="padding:5px 10px;font-size:0.85em;margin-right:5px;background:var(--primary);color:white;border:none;border-radius:4px;cursor:pointer;">✏️</button>
                        <button onclick="deleteTransaction('${trans.id}')" class="btn btn-sm" style="padding:5px 10px;font-size:0.85em;background:#ef4444;color:white;border:none;border-radius:4px;cursor:pointer;">🗑️</button>
                    </div>
                </div>
            </div>
        `).join('');

        // PERBAIKAN: Tampilkan tombol jika ada lebih dari displayedCount
        const loadMoreBtn = document.getElementById('loadMoreBtn');
        if (filtered.length > displayedCount) {
            loadMoreBtn.style.display = 'block';
        } else {
            loadMoreBtn.style.display = 'none';
        }

        saveFilterStates();
    }

    function loadMore() {
        const nextCount = Math.min(displayedCount + ITEMS_PER_PAGE, filteredTransactions.length);
        const itemsToAdd = filteredTransactions.slice(displayedCount, nextCount);
        
        displayedCount = nextCount;

        const container = document.getElementById('transactionsList');
        const newHtml = itemsToAdd.map(trans => `
            <div style="background:var(--bg);padding:15px;border-radius:8px;margin-bottom:10px;">
                <div style="display:flex;justify-content:space-between;align-items:start;margin-bottom:10px;">
                    <div style="flex:1;">
                        <div style="font-weight:600;margin-bottom:5px;">
                            ${trans.type === 'income' ? '💰' : '💸'} ${trans.category}
                        </div>
                        <div style="font-size:0.85em;color:var(--text-secondary);margin-bottom:5px;">
                            ${trans.description || '-'}
                        </div>
                        <div style="font-size:0.8em;color:var(--text-secondary);">
                            ${formatDate(trans.date)}
                        </div>
                    </div>
                    <div style="text-align:right;">
                        <div style="font-size:1.2em;font-weight:bold;color:${trans.type === 'income' ? '#10b981' : '#ef4444'};margin-bottom:10px;">
                            ${trans.type === 'income' ? '+' : '-'}${formatCurrency(trans.amount)}
                        </div>
                        <button onclick="openEditModal('${trans.id}')" class="btn btn-sm" style="padding:5px 10px;font-size:0.85em;margin-right:5px;background:var(--primary);color:white;border:none;border-radius:4px;cursor:pointer;">✏️</button>
                        <button onclick="deleteTransaction('${trans.id}')" class="btn btn-sm" style="padding:5px 10px;font-size:0.85em;background:#ef4444;color:white;border:none;border-radius:4px;cursor:pointer;">🗑️</button>
                    </div>
                </div>
            </div>
        `).join('');

        container.innerHTML += newHtml;
        saveFilterStates();

        const loadMoreBtn = document.getElementById('loadMoreBtn');
        if (displayedCount >= filteredTransactions.length) {
            loadMoreBtn.style.display = 'none';
        }
    }

    function openEditModal(id) {
        const trans = transactions.find(t => t.id === id);
        if (!trans) return;

        editingId = id;
        document.getElementById('editDate').value = trans.date;
        document.getElementById('editCategory').value = trans.category;
        document.getElementById('editDescription').value = trans.description || '';
        document.getElementById('editAmount').value = trans.amount;
        document.getElementById('editModal').style.display = 'block';
    }

    function closeEditModal() {
        document.getElementById('editModal').style.display = 'none';
        editingId = null;
    }

    async function saveEdit() {
        if (!editingId) return;

        const trans = transactions.find(t => t.id === editingId);
        if (!trans) return;

        trans.date = document.getElementById('editDate').value;
        trans.category = document.getElementById('editCategory').value;
        trans.description = document.getElementById('editDescription').value;
        trans.amount = parseFloat(document.getElementById('editAmount').value);

        closeEditModal();
        await saveTransactions();
    }

    async function deleteTransaction(id) {
        if (!confirm('Hapus transaksi ini?')) return;

        transactions = transactions.filter(t => t.id !== id);
        await saveTransactions();
    }

    document.getElementById('filterMonth').addEventListener('change', function() {
        displayedCount = ITEMS_PER_PAGE;  // Reset ke 25 saat filter berubah
        displayTransactions();
    });

    document.getElementById('filterYear').addEventListener('change', function() {
        displayedCount = ITEMS_PER_PAGE;  // Reset ke 25 saat filter berubah
        displayTransactions();
    });

    document.getElementById('filterType').addEventListener('change', function() {
        displayedCount = ITEMS_PER_PAGE;  // Reset ke 25 saat filter berubah
        displayTransactions();
    });
    document.getElementById('filterCategory').addEventListener('change', function() {
        displayedCount = ITEMS_PER_PAGE;  // Reset ke 25 saat filter berubah
        displayTransactions();
    });

    async function initializePage() {
        const loaded = await loadData();
        if (loaded) {
            populateFilters();
            populateCategories();
            displayTransactions();
        }
    }


    document.getElementById('editModal').addEventListener('click', function(e) {
        if (e.target === this) closeEditModal();
    });

    initializePage();

    setInterval(loadData, 3000);
</script>