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

<div class="container">
    <div class="card">
        <h2>🤖 AI Financial Advisor</h2>
        <p style="color:var(--text-secondary);margin-bottom:20px;">
            AI kami akan menganalisis keuangan Anda dan memberikan saran, motivasi, dan rekomendasi yang personal!
        </p>

        <div style="background:var(--bg);padding:20px;border-radius:12px;margin-bottom:20px;">
            <div style="display:flex;gap:10px;align-items:center;margin-bottom:15px;">
                <div style="width:50px;height:50px;background:linear-gradient(135deg,#667eea,#764ba2);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:1.5em;">🤖</div>
                <div>
                    <div style="font-weight:600;color:var(--primary);">FinanceAI Assistant</div>
                    <div style="font-size:0.85em;color:var(--text-secondary);">Asisten Keuangan Pribadi Anda</div>
                </div>
            </div>
            <button onclick="analyzeFinance()" class="btn btn-primary btn-full" id="analyzeBtn">
                <span>🔍</span>
                Analisis Keuangan Saya
            </button>
        </div>

        <!-- AI Response -->
        <div id="aiResponse" style="display:none;">
            <div style="background:linear-gradient(135deg,#667eea,#764ba2);color:white;padding:25px;border-radius:12px;margin-bottom:20px;">
                <h3 style="margin-bottom:15px;display:flex;align-items:center;gap:10px;">
                    <span>📊</span>
                    Analisis Keuangan Anda
                </h3>
                <div id="financialStatus"></div>
            </div>

            <div class="card" style="background:var(--bg);border:2px solid var(--success);">
                <h3 style="color:var(--success);margin-bottom:15px;display:flex;align-items:center;gap:10px;">
                    <span>💡</span>
                    Saran & Rekomendasi
                </h3>
                <div id="aiAdvice"></div>
            </div>

            <div class="card" style="background:var(--bg);border:2px solid var(--warning);margin-top:20px;">
                <h3 style="color:var(--warning);margin-bottom:15px;display:flex;align-items:center;gap:10px;">
                    <span>🎯</span>
                    Target & Motivasi
                </h3>
                <div id="aiMotivation"></div>
            </div>

            <div class="card" style="background:var(--bg);border:2px solid var(--primary);margin-top:20px;">
                <h3 style="color:var(--primary);margin-bottom:15px;display:flex;align-items:center;gap:10px;">
                    <span>📈</span>
                    Tips Meningkatkan Pemasukan
                </h3>
                <div id="aiIncomeTips"></div>
            </div>
        </div>
    </div>

    <!-- Financial Insights -->
    <div class="card">
        <h2>📈 Insight Keuangan</h2>
        <div id="insights">
            <p style="text-align:center;color:var(--text-secondary);padding:20px;">
                Klik tombol "Analisis Keuangan Saya" untuk melihat insight
            </p>
        </div>
    </div>
</div>

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

<script>
    let transactions = [];

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

    async function analyzeFinance() {
        showLoading();
        const btn = document.getElementById('analyzeBtn');
        btn.disabled = true;
        btn.innerHTML = '<span>⏳</span> Menganalisis...';

        // Simulate AI processing
        await new Promise(resolve => setTimeout(resolve, 2000));

        if (transactions.length === 0) {
            alert('Belum ada data transaksi untuk dianalisis. Mulai catat transaksi Anda!');
            btn.disabled = false;
            btn.innerHTML = '<span>🔍</span> Analisis Keuangan Saya';
            hideLoading();
            return;
        }

        const analysis = performAnalysis();
        displayAnalysis(analysis);

        btn.disabled = false;
        btn.innerHTML = '<span>🔍</span> Analisis Keuangan Saya';
        hideLoading();
    }

    function performAnalysis() {
        const now = new Date();
        const currentMonth = now.getMonth();
        const currentYear = now.getFullYear();
        const lastMonth = new Date(currentYear, currentMonth - 1);

        // Current month data
        const currentMonthTrans = transactions.filter(t => {
            const d = new Date(t.date);
            return d.getMonth() === currentMonth && d.getFullYear() === currentYear;
        });

        // Last month data
        const lastMonthTrans = transactions.filter(t => {
            const d = new Date(t.date);
            return d.getMonth() === lastMonth.getMonth() && d.getFullYear() === lastMonth.getFullYear();
        });

        const currentIncome = currentMonthTrans.filter(t => t.type === 'income').reduce((sum, t) => sum + t.amount, 0);
        const currentExpense = currentMonthTrans.filter(t => t.type === 'expense').reduce((sum, t) => sum + t.amount, 0);
        const lastIncome = lastMonthTrans.filter(t => t.type === 'income').reduce((sum, t) => sum + t.amount, 0);
        const lastExpense = lastMonthTrans.filter(t => t.type === 'expense').reduce((sum, t) => sum + t.amount, 0);

        const currentBalance = currentIncome - currentExpense;
        const savingRate = currentIncome > 0 ? ((currentIncome - currentExpense) / currentIncome * 100) : 0;

        // Expense categories
        const expenseCategories = {};
        currentMonthTrans.filter(t => t.type === 'expense').forEach(t => {
            expenseCategories[t.category] = (expenseCategories[t.category] || 0) + t.amount;
        });

        const topExpense = Object.entries(expenseCategories).sort((a, b) => b[1] - a[1])[0];

        return {
            currentIncome,
            currentExpense,
            currentBalance,
            lastIncome,
            lastExpense,
            savingRate,
            topExpense: topExpense || ['Belum ada', 0],
            incomeGrowth: lastIncome > 0 ? ((currentIncome - lastIncome) / lastIncome * 100) : 0,
            expenseGrowth: lastExpense > 0 ? ((currentExpense - lastExpense) / lastExpense * 100) : 0
        };
    }

    function displayAnalysis(analysis) {
        document.getElementById('aiResponse').style.display = 'block';

        // Financial Status
        const statusColor = analysis.currentBalance >= 0 ? 'var(--success)' : 'var(--danger)';
        const statusEmoji = analysis.currentBalance >= 0 ? '😊' : '😰';

        document.getElementById('financialStatus').innerHTML = `
            <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:15px;margin-bottom:20px;">
                <div>
                    <div style="opacity:0.9;font-size:0.9em;margin-bottom:5px;">Pemasukan Bulan Ini</div>
                    <div style="font-size:1.5em;font-weight:bold;">${formatCurrency(analysis.currentIncome)}</div>
                    <div style="font-size:0.8em;margin-top:5px;opacity:0.9;">
                        ${analysis.incomeGrowth >= 0 ? '📈' : '📉'} ${Math.abs(analysis.incomeGrowth).toFixed(1)}% vs bulan lalu
                    </div>
                </div>
                <div>
                    <div style="opacity:0.9;font-size:0.9em;margin-bottom:5px;">Pengeluaran Bulan Ini</div>
                    <div style="font-size:1.5em;font-weight:bold;">${formatCurrency(analysis.currentExpense)}</div>
                    <div style="font-size:0.8em;margin-top:5px;opacity:0.9;">
                        ${analysis.expenseGrowth >= 0 ? '📈' : '📉'} ${Math.abs(analysis.expenseGrowth).toFixed(1)}% vs bulan lalu
                    </div>
                </div>
                <div>
                    <div style="opacity:0.9;font-size:0.9em;margin-bottom:5px;">Saldo Bulan Ini</div>
                    <div style="font-size:1.5em;font-weight:bold;color:${statusColor};">${statusEmoji} ${formatCurrency(analysis.currentBalance)}</div>
                    <div style="font-size:0.8em;margin-top:5px;opacity:0.9;">
                        Saving rate: ${analysis.savingRate.toFixed(1)}%
                    </div>
                </div>
            </div>
        `;

        // AI Advice
        let advice = '';
        if (analysis.currentBalance < 0) {
            advice = `
                <div style="padding:15px;background:white;border-radius:8px;margin-bottom:10px;">
                    <strong>⚠️ Pengeluaran Melebihi Pemasukan!</strong>
                    <p style="margin-top:10px;line-height:1.6;">
                        Bulan ini pengeluaran Anda sebesar ${formatCurrency(analysis.currentExpense)} 
                        melebihi pemasukan sebesar ${formatCurrency(analysis.currentIncome)}. 
                        Deficit: ${formatCurrency(Math.abs(analysis.currentBalance))}.
                    </p>
                    <p style="margin-top:10px;line-height:1.6;">
                        <strong>Saran:</strong><br>
                        • Kurangi pengeluaran di kategori "${analysis.topExpense[0]}" (pengeluaran terbesar: ${formatCurrency(analysis.topExpense[1])})<br>
                        • Buat anggaran bulanan maksimal 70% dari pemasukan<br>
                        • Cari sumber pemasukan tambahan jika memungkinkan
                    </p>
                </div>
            `;
        } else if (analysis.savingRate < 20) {
            advice = `
                <div style="padding:15px;background:white;border-radius:8px;margin-bottom:10px;">
                    <strong>📊 Saving Rate Masih Rendah (${analysis.savingRate.toFixed(1)}%)</strong>
                    <p style="margin-top:10px;line-height:1.6;">
                        Meskipun Anda surplus ${formatCurrency(analysis.currentBalance)}, 
                        saving rate Anda masih di bawah 20%. Idealnya minimal 20-30%.
                    </p>
                    <p style="margin-top:10px;line-height:1.6;">
                        <strong>Saran:</strong><br>
                        • Target saving minimal 20% dari pemasukan (${formatCurrency(analysis.currentIncome * 0.2)})<br>
                        • Evaluasi pengeluaran kategori "${analysis.topExpense[0]}" yang mencapai ${formatCurrency(analysis.topExpense[1])}<br>
                        • Pisahkan uang saving di awal bulan (pay yourself first)
                    </p>
                </div>
            `;
        } else {
            advice = `
                <div style="padding:15px;background:white;border-radius:8px;margin-bottom:10px;">
                    <strong>🎉 Keuangan Anda Sehat!</strong>
                    <p style="margin-top:10px;line-height:1.6;">
                        Surplus ${formatCurrency(analysis.currentBalance)} dengan saving rate ${analysis.savingRate.toFixed(1)}%. 
                        Ini sangat bagus! Anda berhasil menabung ${Math.abs(analysis.savingRate).toFixed(0)}% dari pemasukan.
                    </p>
                    <p style="margin-top:10px;line-height:1.6;">
                        <strong>Saran:</strong><br>
                        • Pertahankan pola pengeluaran yang sehat ini<br>
                        • Investasikan sebagian savings untuk masa depan<br>
                        • Tetapkan target saving 30-40% jika memungkinkan
                    </p>
                </div>
            `;
        }
        document.getElementById('aiAdvice').innerHTML = advice;

        // Motivation
        const motivation = generateMotivation(analysis);
        document.getElementById('aiMotivation').innerHTML = motivation;

        // Income Tips
        const incomeTips = `
            <div style="padding:15px;background:white;border-radius:8px;margin-bottom:10px;">
                <ol style="padding-left:20px;line-height:1.8;">
                    <li><strong>Skill Enhancement:</strong> Tingkatkan skill untuk promosi atau side hustle</li>
                    <li><strong>Passive Income:</strong> Mulai investasi atau bisnis sampingan</li>
                    <li><strong>Freelance:</strong> Tawarkan jasa sesuai keahlian Anda</li>
                    <li><strong>Digital Products:</strong> Buat konten atau produk digital untuk dijual</li>
                    <li><strong>Optimasi Aset:</strong> Sewakan aset yang tidak terpakai</li>
                </ol>
            </div>
        `;
        document.getElementById('aiIncomeTips').innerHTML = incomeTips;

        // Insights
        const insights = `
            <div style="display:grid;gap:15px;">
                <div style="padding:15px;background:var(--bg);border-left:4px solid var(--primary);border-radius:8px;">
                    <strong>💰 Top Pengeluaran:</strong>
                    <p style="margin-top:8px;color:var(--text-secondary);">
                        ${analysis.topExpense[0]}: ${formatCurrency(analysis.topExpense[1])} 
                        (${((analysis.topExpense[1] / analysis.currentExpense) * 100).toFixed(1)}% dari total pengeluaran)
                    </p>
                </div>
                <div style="padding:15px;background:var(--bg);border-left:4px solid var(--success);border-radius:8px;">
                    <strong>📊 Pertumbuhan Pemasukan:</strong>
                    <p style="margin-top:8px;color:var(--text-secondary);">
                        ${analysis.incomeGrowth >= 0 ? 'Naik' : 'Turun'} ${Math.abs(analysis.incomeGrowth).toFixed(1)}% 
                        dibanding bulan lalu (${formatCurrency(analysis.lastIncome)})
                    </p>
                </div>
                <div style="padding:15px;background:var(--bg);border-left:4px solid var(--danger);border-radius:8px;">
                    <strong>📉 Pertumbuhan Pengeluaran:</strong>
                    <p style="margin-top:8px;color:var(--text-secondary);">
                        ${analysis.expenseGrowth >= 0 ? 'Naik' : 'Turun'} ${Math.abs(analysis.expenseGrowth).toFixed(1)}% 
                        dibanding bulan lalu (${formatCurrency(analysis.lastExpense)})
                    </p>
                </div>
            </div>
        `;
        document.getElementById('insights').innerHTML = insights;

        // Scroll to response
        document.getElementById('aiResponse').scrollIntoView({ behavior: 'smooth' });
    }

    function generateMotivation(analysis) {
        if (analysis.currentBalance >= analysis.currentIncome * 0.3) {
            return `
                <div style="padding:20px;background:white;border-radius:8px;text-align:center;">
                    <div style="font-size:3em;margin-bottom:10px;">🏆</div>
                    <h3 style="color:var(--success);margin-bottom:10px;">Luar Biasa, Singgih & Eka!</h3>
                    <p style="line-height:1.8;color:var(--text-secondary);">
                        Kalian berhasil menabung lebih dari 30% dari pemasukan! 
                        Ini pencapaian yang sangat membanggakan. Terus pertahankan disiplin finansial ini, 
                        dan masa depan kalian akan cerah! 💪
                    </p>
                    <div style="margin-top:15px;padding:15px;background:var(--bg);border-radius:8px;">
                        <strong>Target Berikutnya:</strong> Coba tingkatkan saving rate ke 40%! 
                    </div>
                </div>
            `;
        } else if (analysis.currentBalance >= 0) {
            return `
                <div style="padding:20px;background:white;border-radius:8px;text-align:center;">
                    <div style="font-size:3em;margin-bottom:10px;">👍</div>
                    <h3 style="color:var(--primary);margin-bottom:10px;">Bagus, Terus Semangat!</h3>
                    <p style="line-height:1.8;color:var(--text-secondary);">
                        Kalian sudah di jalur yang benar dengan surplus ${formatCurrency(analysis.currentBalance)}. 
                        Sedikit lagi untuk mencapai target saving 30%. Tetap konsisten dan disiplin!
                    </p>
                    <div style="margin-top:15px;padding:15px;background:var(--bg);border-radius:8px;">
                        <strong>Tips:</strong> Kurangi ${formatCurrency((analysis.currentIncome * 0.3) - analysis.currentBalance)} 
                        lagi dari pengeluaran untuk mencapai target!
                    </div>
                </div>
            `;
        } else {
            return `
                <div style="padding:20px;background:white;border-radius:8px;text-align:center;">
                    <div style="font-size:3em;margin-bottom:10px;">💪</div>
                    <h3 style="color:var(--warning);margin-bottom:10px;">Jangan Menyerah!</h3>
                    <p style="line-height:1.8;color:var(--text-secondary);">
                        Bulan ini memang sulit, tapi ini adalah kesempatan untuk bangkit lebih kuat! 
                        Setiap langkah kecil menuju perbaikan adalah kemajuan. 
                        Evaluasi pengeluaran, buat rencana yang realistis, dan yakin kalian bisa! 🌟
                    </p>
                    <div style="margin-top:15px;padding:15px;background:var(--bg);border-radius:8px;">
                        <strong>Action Plan:</strong> Fokus kurangi pengeluaran kategori "${analysis.topExpense[0]}" 
                        sebesar 20-30% bulan depan!
                    </div>
                </div>
            `;
        }
    }

    loadData();
</script>
