<?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 = 'Total Saldo';
include 'includes/header.php';
?>

<div class="container">
    <div class="card" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 0.1px; text-align: center;">
        <div style="margin-bottom: 15px;">
            <div style="font-size: 0.85em; opacity: 0.9; margin-bottom: 5px;">💰 Total Saldo Keseluruhan</div>
            <div style="font-size: 1.5em; font-weight: bold; margin-bottom: 1px; word-break: break-word;" id="totalSaldoDisplay">Rp 0</div>
            
        </div>
    </div>
   

    <!-- Tombol Lihat Selengkapnya -->
    <div style="text-align: center; margin: 15px 0;">
        <button onclick="toggleDetailContainer()" style="padding: 10px 25px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: 600; font-size: 0.95em;">
            ▼ Lihat Selengkapnya
        </button>
    </div>

    <!-- Detail Container...

    <!-- Detail Container (LANGSUNG TERBUKA - TIDAK HIDDEN) -->
  <div id="saldoDetailContainer" style="margin-top: 10px; display: none;">

        <!-- Pemasukan -->
      <div class="card" style="background: linear-gradient(135deg, #667eea 100%, #764ba2 100%); color: white; padding: 0.1px; text-align: Left;">
        <div style="margin-bottom: 15px;">
        <div class="card" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; padding: 10px; margin-bottom: 5px;">
            <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;">
                <div style="flex: 1; min-width: 100px;">
                    <div style="font-size: 0.75em; opacity: 0.9; margin-bottom: 5px;">📈 Total Pemasukan Keseluruhan</div>
                    <div style="font-size: 1em; font-weight: bold; word-break: break-word;" id="totalIncomeDisplay">Rp 0</div>
                </div>
                <div style="font-size: 3em; opacity: 0.3;"></div>
            </div>
        </div>

        <!-- Pengeluaran -->
        <div class="card" style="background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); color: white; padding: 10px; margin-bottom: 5px;">
            <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;">
                <div style="flex: 1; min-width: 200px;">
                    <div style="font-size: 0.75em; opacity: 0.9; margin-bottom: 5px;">📉 Total Pengeluaran Keseluruhan</div>
                    <div style="font-size: 1em; font-weight: bold; word-break: break-word;" id="totalExpenseDisplay">Rp 0</div>
                </div>
                <div style="font-size: 3em; opacity: 0.3;"></div>
            </div>
        </div>

        <!-- Jumlah Transaksi -->
        <div class="card" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); color: white; padding: 10px; margin-bottom: 5px;">
            <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;">
                <div style="flex: 1; min-width: 200px;">
                    <div style="font-size: 0.75em; opacity: 0.9; margin-bottom: 5px;">📋 Transaksi Tercatat Keseluruhan</div>
                    <div style="font-size: 1em; font-weight: bold; word-break: break-word;" id="totalTransactionCount">0</div>
                </div>
                <div style="font-size: 3em; opacity: 0.3;"></div>
            </div>
        </div>
</div>
 </div>
  </div>
   </div>
        <!-- Breakdown per Tahun dengan Dropdown Pilihan -->
        <div class="card">
            <h2>📅 Lihat Per Tahun</h2>
            <div style="margin-bottom: 15px;">
                <select id="yearBreakdownYear" style="width: 100%; padding: 12px; border: 2px solid var(--border); border-radius: 8px; font-size: 1em;">
                    <option value="">Pilih Tahun</option>
                </select>
            </div>
            <div id="yearBreakdownContainer" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px;"></div>
        </div>

        <!-- Breakdown per Bulan (Tahun Terpilih) -->
        <div class="card">
            <h2>📅 Lihat Per Bulan</h2>
            <div style="margin-bottom: 15px;">
                <select id="monthBreakdownYear" style="width: 100%; padding: 12px; border: 2px solid var(--border); border-radius: 8px; font-size: 1em;">
                    <option value="">Pilih Tahun</option>
                </select>
            </div>
            <div id="monthBreakdownContainer" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px;"></div>
        </div>
    </div>
</div>

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

<script>
    // FORMAT CURRENCY - TANPA SINGKATAN (Rp 1.000.000, bukan Rp 1 jt)
    function formatCurrency(amount) {
        return 'Rp ' + Math.floor(amount).toLocaleString('id-ID');
    }

    let transactions = [];
    const months = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];

    // UPDATE TOTAL SALDO
    function updateTotalSaldo() {
        const totalIncome = transactions
            .filter(t => t.type === 'income')
            .reduce((sum, t) => sum + t.amount, 0);
        
        const totalExpense = transactions
            .filter(t => t.type === 'expense')
            .reduce((sum, t) => sum + t.amount, 0);
        
        const totalSaldo = totalIncome - totalExpense;

        document.getElementById('totalSaldoDisplay').textContent = formatCurrency(totalSaldo);
        document.getElementById('totalIncomeDisplay').textContent = formatCurrency(totalIncome);
        document.getElementById('totalExpenseDisplay').textContent = formatCurrency(totalExpense);
        document.getElementById('totalTransactionCount').textContent = transactions.length + ' transaksi';

        // Update breakdown
        populateYearDropdowns();
    }

    // POPULATE YEAR DROPDOWNS (untuk kedua section)
    function populateYearDropdowns() {
        const years = [...new Set(transactions.map(t => new Date(t.date).getFullYear()))].sort().reverse();
        
        const yearBreakdownDropdown = document.getElementById('yearBreakdownYear');
        const monthBreakdownDropdown = document.getElementById('monthBreakdownYear');
        
        // Populate breakdown per tahun dropdown
        yearBreakdownDropdown.innerHTML = '<option value="">Pilih Tahun</option>' +
            years.map(y => `<option value="${y}">${y}</option>`).join('');

        // Populate breakdown per bulan dropdown
        monthBreakdownDropdown.innerHTML = '<option value="">Pilih Tahun</option>' +
            years.map(y => `<option value="${y}">${y}</option>`).join('');

        // Auto-select tahun terbaru untuk breakdown per bulan
        if (years.length > 0) {
            monthBreakdownDropdown.value = years[0];
            updateMonthBreakdown();
        }

        // Auto-select tahun terbaru untuk breakdown per tahun
        if (years.length > 0) {
            yearBreakdownDropdown.value = years[0];
            updateYearBreakdown();
        }
    }

    // UPDATE YEAR BREAKDOWN (dengan filter tahun terpilih)
    function updateYearBreakdown() {
        const selectedYear = document.getElementById('yearBreakdownYear').value;
        
        if (!selectedYear) {
            document.getElementById('yearBreakdownContainer').innerHTML = 
                '<p style="text-align: center; color: var(--text-secondary); grid-column: 1 / -1;">Pilih tahun untuk melihat detail</p>';
            return;
        }

        const monthData = {};

        transactions
            .filter(t => new Date(t.date).getFullYear() === parseInt(selectedYear))
            .forEach(trans => {
                const month = new Date(trans.date).getMonth();
                if (!monthData[month]) {
                    monthData[month] = { income: 0, expense: 0, count: 0 };
                }
                if (trans.type === 'income') {
                    monthData[month].income += trans.amount;
                } else {
                    monthData[month].expense += trans.amount;
                }
                monthData[month].count++;
            });

        const container = document.getElementById('yearBreakdownContainer');
        let html = '';

        for (let i = 0; i < 12; i++) {
            const data = monthData[i];
            if (!data) continue;

            const balance = data.income - data.expense;
            const color = balance >= 0 ? '#10b981' : '#ef4444';

            html += `
                <div style="background: var(--bg); padding: 20px; border-radius: 12px; border-left: 5px solid ${color};">
                    <h3 style="margin-top: 0; color: var(--primary); font-size: 1.1em;">${months[i]} ${selectedYear}</h3>
                    <div style="margin-bottom: 12px;">
                        <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                            <span style="color: var(--text-secondary); font-size: 0.9em;">Pemasukan:</span>
                            <strong style="color: #10b981; font-size: 0.95em; word-break: break-word;">${formatCurrency(data.income)}</strong>
                        </div>
                        <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                            <span style="color: var(--text-secondary); font-size: 0.9em;">Pengeluaran:</span>
                            <strong style="color: #ef4444; font-size: 0.95em; word-break: break-word;">-${formatCurrency(data.expense)}</strong>
                        </div>
                        <div style="display: flex; justify-content: space-between; padding-top: 8px; border-top: 1px solid var(--border);">
                            <span style="color: var(--text-secondary); font-size: 0.9em;">Saldo:</span>
                            <strong style="color: ${color}; font-size: 0.95em; word-break: break-word;">${formatCurrency(balance)}</strong>
                        </div>
                    </div>
                </div>
            `;
        }

        container.innerHTML = html || '<p style="text-align: center; color: var(--text-secondary); grid-column: 1 / -1;">Tidak ada data untuk tahun ini</p>';
    }

    // UPDATE MONTH BREAKDOWN
    function updateMonthBreakdown() {
        const year = document.getElementById('monthBreakdownYear').value;
        
        if (!year) {
            document.getElementById('monthBreakdownContainer').innerHTML = 
                '<p style="text-align: center; color: var(--text-secondary); grid-column: 1 / -1;">Pilih tahun untuk melihat breakdown per bulan</p>';
            return;
        }

        const monthData = {};

        transactions
            .filter(t => new Date(t.date).getFullYear() === parseInt(year))
            .forEach(trans => {
                const month = new Date(trans.date).getMonth();
                if (!monthData[month]) {
                    monthData[month] = { income: 0, expense: 0, count: 0 };
                }
                if (trans.type === 'income') {
                    monthData[month].income += trans.amount;
                } else {
                    monthData[month].expense += trans.amount;
                }
                monthData[month].count++;
            });

        const container = document.getElementById('monthBreakdownContainer');
        let html = '';

        for (let i = 0; i < 12; i++) {
            const data = monthData[i];
            if (!data) continue;

            const balance = data.income - data.expense;
            const color = balance >= 0 ? '#10b981' : '#ef4444';

            html += `
                <div style="background: var(--bg); padding: 20px; border-radius: 12px; border-left: 5px solid ${color};">
                    <h3 style="margin-top: 0; color: var(--primary); font-size: 1.1em;">${months[i]} ${year}</h3>
                    <div style="margin-bottom: 12px;">
                        <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                            <span style="color: var(--text-secondary); font-size: 0.9em;">Pemasukan:</span>
                            <strong style="color: #10b981; font-size: 0.95em; word-break: break-word;">${formatCurrency(data.income)}</strong>
                        </div>
                        <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                            <span style="color: var(--text-secondary); font-size: 0.9em;">Pengeluaran:</span>
                            <strong style="color: #ef4444; font-size: 0.95em; word-break: break-word;">-${formatCurrency(data.expense)}</strong>
                        </div>
                        <div style="display: flex; justify-content: space-between; padding-top: 8px; border-top: 1px solid var(--border);">
                            <span style="color: var(--text-secondary); font-size: 0.9em;">Saldo:</span>
                            <strong style="color: ${color}; font-size: 0.95em; word-break: break-word;">${formatCurrency(balance)}</strong>
                        </div>
                    </div>
                </div>
            `;
        }

        container.innerHTML = html || '<p style="text-align: center; color: var(--text-secondary); grid-column: 1 / -1;">Tidak ada data untuk tahun ini</p>';
    }

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

    // EVENT LISTENERS
    document.getElementById('yearBreakdownYear').addEventListener('change', updateYearBreakdown);
    document.getElementById('monthBreakdownYear').addEventListener('change', updateMonthBreakdown);

    // LOAD DATA ON PAGE LOAD
    loadData();
    // FUNCTION TOGGLE DETAIL CONTAINER
function toggleDetailContainer() {
    const container = document.getElementById('saldoDetailContainer');
    const button = event.target;
    
    if (container.style.display === 'none') {
        // Buka
        container.style.display = 'block';
        button.textContent = '▲ Sembunyikan';
    } else {
        // Sembunyikan
        container.style.display = 'none';
        button.textContent = '▼ Lihat Selengkapnya';
    }
}

</script>