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

<div class="container">
    <div class="stat-grid">
        <div class="stat-card">
            <div class="icon">📈</div>
            <h3>Pemasukan Hari Ini</h3>
            <div class="amount" id="todayIncome">Rp 0</div>
        </div>
        <div class="stat-card">
            <div class="icon">📉</div>
            <h3>Pengeluaran Hari Ini</h3>
            <div class="amount" id="todayExpense">Rp 0</div>
        </div>
        <div class="stat-card">
            <div class="icon">💵</div>
            <h3>Saldo Hari Ini</h3>
            <div class="amount" id="todayBalance">Rp 0</div>
        </div>
        <div class="stat-card">
            <div class="icon">🗓️</div>
            <h3>Saldo Bulan Ini</h3>
            <div class="amount" id="monthBalance">Rp 0</div>
        </div>
    </div>

    <div class="card">
        <h2>➕ Tambah Transaksi</h2>
        <form id="transactionForm">
            <div class="form-group">
                <label for="type">Jenis Transaksi</label>
                <select id="type" required>
                    <option value="income">💰 Pemasukan</option>
                    <option value="expense">💸 Pengeluaran</option>
                </select>
            </div>

            <div class="form-group">
                <label for="amount">Jumlah (Rp)</label>
                <input type="text" id="amount" placeholder="0" required min="0">
            </div>

            <div class="form-group">
                <label for="category">Kategori</label>
                <input type="text" id="category" placeholder="Contoh: Makanan, Gaji, dll" required>
            </div>

            <div class="form-group">
                <label for="description">Keterangan (Opsional)</label>
                <textarea id="description" placeholder="Detail transaksi..." rows="3"></textarea>
            </div>

            <button type="submit" class="btn btn-primary btn-full">
                <span>💾</span>
                Simpan Transaksi
            </button>
        </form>
    </div>

    <div class="card">
        <h2>📌 Transaksi Terbaru</h2>
        <div id="recentTransactions"></div>
        <a href="riwayat.php" class="btn btn-primary btn-full" style="margin-top: 15px;">
            Lihat Semua Riwayat →
        </a>
    </div>
</div>

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

<script>
    // TAMBAH FUNGSI INI DI AWAL
function formatCurrency(amount) {
    if (amount < 1_000_000) {
        return 'Rp ' + amount.toLocaleString('id-ID');
    } else if (amount < 1_000_000_000) {
        let juta = amount / 1_000_000;
        // Gunakan Math.floor untuk TIDAK round-up (hanya cut)
        let jutaFloor = Math.floor(juta * 10) / 10;
        // Jika hasilnya integer (4.0), tampil tanpa desimal
        if (jutaFloor === Math.floor(jutaFloor)) {
            return 'Rp ' + Math.floor(jutaFloor) + ' jt';
        } else {
            return 'Rp ' + jutaFloor.toString().replace('.', ',') + ' jt';
        }
    } else {
        let miliar = amount / 1_000_000_000;
        // Sama untuk miliar
        let miliarFloor = Math.floor(miliar * 10) / 10;
        if (miliarFloor === Math.floor(miliarFloor)) {
            return 'Rp ' + Math.floor(miliarFloor) + ' M';
        } else {
            return 'Rp ' + miliarFloor.toString().replace('.', ',') + ' M';
        }
    }
}

        // ===== AUTO FORMAT INPUT JUMLAH =====
    document.getElementById('amount').addEventListener('input', function(e) {
        // Ambil hanya angka
        let value = e.target.value.replace(/[^0-9]/g, '');
        
        // Balik dari belakang dan tambah titik setiap 3 digit
        let result = '';
        for (let i = value.length - 1, count = 0; i >= 0; i--, count++) {
            if (count > 0 && count % 3 === 0) {
                result = '.' + result;
            }
            result = value[i] + result;
        }
        
        e.target.value = result;
    });
    // ===== AKHIR AUTO FORMAT =====


    let transactions = [];


    // PERBAIKAN: Load data dengan bypass cache
    async function loadData() {
        try {
            const timestamp = new Date().getTime();
            const response = await fetch('api.php?action=load&t=' + timestamp, {
                cache: 'no-store',
                headers: {
                    'Cache-Control': 'no-cache'
                }
            });

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

            const data = await response.json();
            transactions = data.transactions || [];
            updateDashboard();
            displayRecentTransactions();
            return true;
        } catch (error) {
            console.error('Error loading data:', error);
            return false;
        }
    }

    // PERBAIKAN: Save dengan return response dan load ulang
    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();

            // PENTING: Setelah save, load data segar dari server
            if (result.success) {
                console.log('Save successful, loading fresh data...');
                const loaded = await loadData();
                return loaded;
            }

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

    function updateDashboard() {
        const today = new Date().toDateString();
        const currentMonth = new Date().getMonth();
        const currentYear = new Date().getFullYear();

        let todayIncome = 0, todayExpense = 0;
        let monthIncome = 0, monthExpense = 0;

        transactions.forEach(trans => {
            const transDate = new Date(trans.date);
            if (transDate.toDateString() === today) {
                if (trans.type === 'income') todayIncome += trans.amount;
                else todayExpense += trans.amount;
            }

            if (transDate.getMonth() === currentMonth && transDate.getFullYear() === currentYear) {
                if (trans.type === 'income') monthIncome += trans.amount;
                else monthExpense += trans.amount;
            }
        });

        document.getElementById('todayIncome').textContent = formatCurrency(todayIncome);
        document.getElementById('todayExpense').textContent = formatCurrency(todayExpense);
        document.getElementById('todayBalance').textContent = formatCurrency(todayIncome - todayExpense);
        document.getElementById('monthBalance').textContent = formatCurrency(monthIncome - monthExpense);
    }

    function displayRecentTransactions() {
        const recent = transactions.slice(-5).reverse();
        const container = document.getElementById('recentTransactions');

        if (recent.length === 0) {
            container.innerHTML = '<p style="text-align:center;color:var(--text-secondary);padding:20px;">Belum ada transaksi</p>';
            return;
        }

        container.innerHTML = recent.map(trans => `
            <div style="background:var(--bg);padding:15px;border-radius:8px;margin-bottom:10px;display:flex;justify-content:space-between;align-items:center;">
                <div>
                    <div style="font-weight:600;margin-bottom:5px;">
                        ${trans.type === 'income' ? '💰' : '💸'} ${trans.category}
                    </div>
                    <div style="font-size:0.85em;color:var(--text-secondary);">
                        ${trans.description || '-'}
                    </div>
                </div>
                <div style="font-weight:bold;color:${trans.type === 'income' ? 'var(--success)' : 'var(--danger)'};margin-left:10px;">
                    ${trans.type === 'income' ? '+' : '-'}${formatCurrency(trans.amount)}
                </div>
            </div>
        `).join('');
    }

    document.getElementById('transactionForm').addEventListener('submit', async function(e) {
        e.preventDefault();

        const transaction = {
            id: Date.now().toString(),
            type: document.getElementById('type').value,
                   amount: parseFloat(document.getElementById('amount').value.replace(/\./g, '')),

            category: document.getElementById('category').value,
            description: document.getElementById('description').value,
            date: new Date().toISOString()
        };

        transactions.push(transaction);

        // PERBAIKAN: Tunggu save selesai, baru reset form
        const saved = await saveTransactions();

        if (saved) {
            this.reset();
            alert('✅ Transaksi berhasil disimpan dan ditampilkan!');
        } else {
            alert('❌ Gagal menyimpan transaksi!');
            transactions.pop(); // Batalkan jika gagal
        }
    });

    // Load data saat halaman dimuat
    loadData();

    // Auto-refresh setiap 3 detik
    setInterval(loadData, 3000);
</script>
