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

<style>
body { margin: 0; padding: 0; background: #0a0a0a; }
* { box-sizing: border-box; }
#candleChart { 
    min-width: 100%;
    height: auto;
    cursor: pointer;
    display: block;
}
.tooltip {
    position: fixed;
    background: #1a1a1a;
    border: 1px solid #333;
    padding: 12px;
    border-radius: 6px;
    font-size: 12px;
    color: #fff;
    pointer-events: none;
    z-index: 1000;
    display: none;
    box-shadow: 0 4px 12px rgba(0,0,0,0.5);
    max-width: 200px;
}
.tooltip.visible {
    display: block;
}
.tooltip-title {
    font-weight: bold;
    margin-bottom: 8px;
    border-bottom: 1px solid #333;
    padding-bottom: 8px;
}
.tooltip-row {
    margin: 4px 0;
    display: flex;
    justify-content: space-between;
    gap: 12px;
}
.tooltip-label {
    color: #888;
}
.tooltip-value {
    font-weight: bold;
}
.income { color: #10b981; }
.expense { color: #ef4444; }
.filter-container {
    display: flex;
    gap: 12px;
    align-items: center;
}
.filter-container select {
    padding: 8px 12px;
    background: #2a2a2a;
    border: 1px solid #444;
    border-radius: 6px;
    color: #fff;
    font-size: 14px;
    cursor: pointer;
}
.filter-container select:hover {
    border-color: #60a5fa;
}
.filter-container select:focus {
    outline: none;
    border-color: #60a5fa;
    box-shadow: 0 0 0 3px rgba(96, 165, 250, 0.1);
}
.filter-container label {
    color: #888;
    font-size: 14px;
}
.orientation-btn {
    padding: 8px 14px;
    background: #444;
    color: #aaa;
    border: 1px solid #555;
    border-radius: 6px;
    cursor: pointer;
    font-weight: 600;
    transition: all 0.2s;
}
.orientation-btn.active {
    background: #2196F3;
    color: white;
    border-color: #2196F3;
}
.orientation-btn:hover {
    border-color: #60a5fa;
}
.chartWrapper {
    flex: 1;
    overflow-x: auto;
    overflow-y: auto;
    position: relative;
    background: #0a0a0a;
}
</style>

<div style="display: flex; height: calc(100vh - 100px); gap: 0; flex-direction: column;">
    <!-- CHART AREA (FULL WIDTH) -->
    <div style="flex: 1; background: #0a0a0a; display: flex; flex-direction: column; overflow: hidden;">
        
        <!-- HEADER -->
        <div style="background: #1a1a1a; padding: 15px 20px; border-bottom: 1px solid #333; display: flex; gap: 15px; align-items: center; justify-content: space-between; flex-wrap: wrap;">
            <h2 style="margin: 0; color: #fff; font-size: 1.1em;">📈 Grafik Pemasukan & Pengeluaran</h2>
            
            <!-- FILTER BULAN & TAHUN -->
            <div class="filter-container">
                <label for="monthFilter">Bulan:</label>
                <select id="monthFilter" onchange="chart.onFilterChange()">
                    <option value="">Semua</option>
                    <option value="01">Januari</option>
                    <option value="02">Februari</option>
                    <option value="03">Maret</option>
                    <option value="04">April</option>
                    <option value="05">Mei</option>
                    <option value="06">Juni</option>
                    <option value="07">Juli</option>
                    <option value="08">Agustus</option>
                    <option value="09">September</option>
                    <option value="10">Oktober</option>
                    <option value="11">November</option>
                    <option value="12">Desember</option>
                </select>
                
                <label for="yearFilter">Tahun:</label>
                <select id="yearFilter" onchange="chart.onFilterChange()"></select>
            </div>
            
            <!-- BUTTONS -->
            <div style="display: flex; gap: 4px;">
                <button class="orientation-btn active" id="verticalBtn" onclick="chart.setOrientation('vertical')" title="Tampilan Vertikal">📱 Vertikal</button>
                <button class="orientation-btn" id="horizontalBtn" onclick="chart.setOrientation('horizontal')" title="Tampilan Horizontal">🌐 Horizontal</button>
                <button onclick="chart.zoomIn()" style="padding: 5px 11px; background: #2196F3; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">🔍-</button>
                <button onclick="chart.zoomOut()" style="padding: 8px 13px; background: #2196F3; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">🔍+</button>
                <button onclick="chart.reset()" style="padding: 5px 11px; background: #444; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">Reset</button>
            </div>
        </div>

        <!-- CANVAS WRAPPER (SCROLLABLE) -->
        <div class="chartWrapper" id="chartWrapper">
            <svg id="candleChart"></svg>
            <div id="tooltip" class="tooltip"></div>
        </div>

        <!-- LEGEND -->
        <div style="background: #1a1a1a; padding: 12px 20px; border-top: 1px solid #333; font-size: 0.85em; display: flex; gap: 20px; flex-wrap: wrap; overflow-x: auto;">
            <span><span style="color: #10b981; font-weight: bold;">■ HIJAU</span> = Candlestick Pemasukan (Income) - Saldo Naik</span>
            <span><span style="color: #ef4444; font-weight: bold;">■ MERAH</span> = Candlestick Pengeluaran (Expense) - Saldo Turun</span>
            <span><span style="color: #60a5fa;">─ BIRU</span> = Garis Trend EMA 12</span>
            <span><span style="color: #f97316;">─ ORANGE</span> = Garis Trend EMA 26</span>
        </div>
    </div>
</div>

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

<script>
const chart = {
    data: [],
    zoomLevel: 1,
    candleData: [],
    selectedMonth: '',
    selectedYear: '',
    orientation: 'vertical',
    lastScrollPosition: 0,
    userInteractedWithScroll: false,
    
    // ========== PENGATURAN UKURAN CHART ==========
    // Ubah nilai di bawah ini untuk menyesuaikan ukuran chart
    // VERTIKAL
    chartVerticalHeight: 350,        // Tinggi chart saat VERTIKAL (default: 350px)
    chartVerticalMinWidth: 900,      // Lebar minimum chart VERTIKAL (default: 900px)
    candlespaceVertical: 20,         // Jarak per candlestick VERTIKAL (default: 20px)
    
    // HORIZONTAL
    chartHorizontalHeight: 300,      // Tinggi chart saat HORIZONTAL (default: 300px)
    chartHorizontalMinWidth: 1200,   // Lebar minimum chart HORIZONTAL (default: 1200px)
    candlespaceHorizontal: 20,       // Jarak per candlestick HORIZONTAL (default: 20px)
    
    // PADDING (jarak dari tepi)
    paddingTop: 30,                  // Jarak atas (default: 30px)
    paddingBottom: 80,               // Jarak bawah (default: 80px)
    paddingLeft: 30,                 // Jarak kiri (default: 30px)
    paddingRight: 110,               // Jarak kanan (default: 110px) - DITAMBAH UNTUK JARAK DARI RUPIAH
    
    // CANDLESTICK
    candleWidth: 8,                  // Lebar candlestick default (default: 8px)
    // ==========================================
    
    formatCurrency(num) {
        return 'Rp ' + Math.floor(num).toLocaleString('id-ID');
    },

    initYearFilter() {
        const yearSelect = document.getElementById('yearFilter');
        const currentYear = new Date().getFullYear();
        
        const optionAll = document.createElement('option');
        optionAll.value = '';
        optionAll.textContent = 'Semua';
        yearSelect.appendChild(optionAll);
        
        for (let year = currentYear; year >= currentYear - 5; year--) {
            const option = document.createElement('option');
            option.value = String(year);
            option.textContent = String(year);
            yearSelect.appendChild(option);
        }
    },

    setOrientation(orientation) {
        this.orientation = orientation;
        
        const verticalBtn = document.getElementById('verticalBtn');
        const horizontalBtn = document.getElementById('horizontalBtn');
        
        if (orientation === 'vertical') {
            verticalBtn.classList.add('active');
            horizontalBtn.classList.remove('active');
        } else {
            horizontalBtn.classList.add('active');
            verticalBtn.classList.remove('active');
        }
        
        this.draw();
    },

    onFilterChange() {
        this.selectedMonth = document.getElementById('monthFilter').value;
        this.selectedYear = document.getElementById('yearFilter').value;
        
        console.log('✓ Filter: Bulan=' + (this.selectedMonth || 'Semua') + ', Tahun=' + (this.selectedYear || 'Semua'));
        this.zoomLevel = 1;
        this.userInteractedWithScroll = false;
        this.draw();
    },

    async loadData() {
        try {
            const res = await fetch('api.php?action=load');
            const json = await res.json();
            this.data = json.transactions || [];
            console.log('✓ API Data:', this.data.length, 'transactions');
        } catch (e) {
            console.log('✗ API error, using test data');
            this.data = [
                { date: '2025-01-01', type: 'income', amount: 2000000 },
                { date: '2025-01-01', type: 'expense', amount: 500000 },
                { date: '2025-01-02', type: 'income', amount: 3000000 },
                { date: '2025-01-02', type: 'expense', amount: 800000 },
                { date: '2025-01-03', type: 'income', amount: 2500000 },
                { date: '2025-01-03', type: 'expense', amount: 600000 },
                { date: '2025-01-04', type: 'income', amount: 1800000 },
                { date: '2025-01-04', type: 'expense', amount: 1200000 },
                { date: '2025-01-05', type: 'income', amount: 2200000 },
                { date: '2025-01-05', type: 'expense', amount: 900000 },
                { date: '2025-01-06', type: 'income', amount: 1500000 },
                { date: '2025-01-06', type: 'expense', amount: 1500000 },
                { date: '2025-01-07', type: 'income', amount: 2700000 },
                { date: '2025-01-07', type: 'expense', amount: 1100000 },
                { date: '2025-01-08', type: 'income', amount: 3200000 },
                { date: '2025-01-08', type: 'expense', amount: 950000 },
                { date: '2025-01-09', type: 'income', amount: 1900000 },
                { date: '2025-01-09', type: 'expense', amount: 1300000 },
                { date: '2025-01-10', type: 'income', amount: 2800000 },
                { date: '2025-01-10', type: 'expense', amount: 700000 }
            ];
        }
        
        this.draw();
    },

    getCandleData() {
        let allData = [...this.data].sort((a, b) => new Date(a.date) - new Date(b.date));
        
        let totalBalance = 0;
        const dataWithBalance = allData.map(trans => {
            if (trans.type === 'income') {
                totalBalance += trans.amount || 0;
            } else if (trans.type === 'expense') {
                totalBalance -= trans.amount || 0;
            }
            return { ...trans, totalBalance };
        });
        
        let filteredData = dataWithBalance;
        if (this.selectedMonth || this.selectedYear) {
            filteredData = dataWithBalance.filter(trans => {
                const transDate = new Date(trans.date);
                const month = String(transDate.getMonth() + 1).padStart(2, '0');
                const year = String(transDate.getFullYear());
                
                let match = true;
                if (this.selectedMonth && month !== this.selectedMonth) match = false;
                if (this.selectedYear && year !== this.selectedYear) match = false;
                
                return match;
            });
        }
        
        const sortedData = filteredData.sort((a, b) => new Date(a.date) - new Date(b.date));
        
        let balance = 0;
        const transactions = sortedData.map(trans => {
            if (trans.type === 'income') {
                balance += trans.amount || 0;
            } else if (trans.type === 'expense') {
                balance -= trans.amount || 0;
            }
            
            return {
                date: trans.date,
                type: trans.type,
                amount: trans.amount || 0,
                balance: balance
            };
        });

        console.log('Filtered transactions:', transactions.length);
        return { transactions };
    },

    calculateEMA(values, period) {
        const ema = [];
        const multiplier = 2 / (period + 1);
        let sum = 0;

        for (let i = 0; i < values.length; i++) {
            sum += values[i];
            if (i < period - 1) {
                ema.push(null);
            } else if (i === period - 1) {
                ema.push(sum / period);
            } else {
                const val = (values[i] - ema[i - 1]) * multiplier + ema[i - 1];
                ema.push(val);
            }
        }
        return ema;
    },

    draw() {
        const { transactions } = this.getCandleData();
        this.candleData = transactions;
        
        if (transactions.length === 0) {
            console.log('No data!');
            const svg = document.getElementById('candleChart');
            if (svg) svg.innerHTML = '';
            return;
        }

        const svg = document.getElementById('candleChart');
        if (!svg) return;

        svg.innerHTML = '';

        const balances = transactions.map(t => t.balance);
        const ema12 = this.calculateEMA(balances, 12);
        const ema26 = this.calculateEMA(balances, 26);

        // Hitung ukuran berdasarkan setting
        let chartWidth, chartHeight, candleSpace;
        if (this.orientation === 'horizontal') {
            chartHeight = this.chartHorizontalHeight;
            chartWidth = Math.max(this.chartHorizontalMinWidth, transactions.length * this.candlespaceHorizontal);
            candleSpace = this.candlespaceHorizontal;
        } else {
            chartHeight = this.chartVerticalHeight;
            chartWidth = Math.max(this.chartVerticalMinWidth, transactions.length * this.candlespaceVertical);
            candleSpace = this.candlespaceVertical;
        }
        
        const padding = { 
            top: this.paddingTop, 
            bottom: this.paddingBottom, 
            left: this.paddingLeft, 
            right: this.paddingRight 
        };

        svg.setAttribute('width', chartWidth);
        svg.setAttribute('height', chartHeight);

        const minBalance = Math.min(...balances, 0);
        const maxBalance = Math.max(...balances, 1000);
        const rangeBalance = maxBalance - minBalance;

        const chartArea = chartWidth - padding.left - padding.right;
        const effectiveChartArea = chartArea / this.zoomLevel;
        
        // CANDLESTICK WIDTH TERBALIK: Zoom In = Kecil, Zoom Out = Besar
        const zoomedCandleWidth = this.candleWidth / this.zoomLevel;
        
        const scaleX = (index) => padding.left + (index * effectiveChartArea / (transactions.length - 1 || 1));
        const scaleY = (value) => {
            const chartAreaHeight = chartHeight - padding.top - padding.bottom;
            const y = padding.top + chartAreaHeight * (maxBalance - value) / rangeBalance;
            return y;
        };

        // Grid
        for (let i = 0; i <= 5; i++) {
            const y = padding.top + (chartHeight - padding.top - padding.bottom) * i / 5;
            const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
            line.setAttribute('x1', padding.left);
            line.setAttribute('x2', chartWidth - padding.right);
            line.setAttribute('y1', y);
            line.setAttribute('y2', y);
            line.setAttribute('stroke', '#222');
            line.setAttribute('stroke-width', '1');
            svg.appendChild(line);
        }

        // Baseline
        const baselineY = scaleY(0);
        const baseline = document.createElementNS('http://www.w3.org/2000/svg', 'line');
        baseline.setAttribute('x1', padding.left);
        baseline.setAttribute('x2', chartWidth - padding.right);
        baseline.setAttribute('y1', baselineY);
        baseline.setAttribute('y2', baselineY);
        baseline.setAttribute('stroke', '#666');
        baseline.setAttribute('stroke-width', '2');
        baseline.setAttribute('stroke-dasharray', '5,5');
        svg.appendChild(baseline);

        // Candlesticks (dengan zoom width TERBALIK)
        transactions.forEach((trans, index) => {
            const x = scaleX(index);
            const yBalance = scaleY(trans.balance);
            const yPrevBalance = index > 0 ? scaleY(transactions[index - 1].balance) : baselineY;
            
            const isIncome = trans.type === 'income';
            const color = isIncome ? '#10b981' : '#ef4444';

            const body = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
            body.setAttribute('x', x - zoomedCandleWidth / 2);
            body.setAttribute('y', Math.min(yBalance, yPrevBalance));
            body.setAttribute('width', zoomedCandleWidth);
            body.setAttribute('height', Math.max(Math.abs(yBalance - yPrevBalance), 2));
            body.setAttribute('fill', color);
            body.setAttribute('stroke', color);
            body.setAttribute('stroke-width', '1');
            body.setAttribute('opacity', '0.85');
            body.style.cursor = 'pointer';
            body.addEventListener('click', (e) => this.showTooltip(e, index, transactions));
            svg.appendChild(body);
        });

        // EMA 12
        const path12 = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');
        const points12 = [];
        ema12.forEach((value, index) => {
            if (value !== null) {
                points12.push(`${scaleX(index)},${scaleY(value)}`);
            }
        });
        if (points12.length > 1) {
            path12.setAttribute('points', points12.join(' '));
            path12.setAttribute('fill', 'none');
            path12.setAttribute('stroke', '#60a5fa');
            path12.setAttribute('stroke-width', '2');
            path12.setAttribute('stroke-linejoin', 'round');
            path12.setAttribute('opacity', '0.9');
            svg.appendChild(path12);
        }

        // EMA 26
        const path26 = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');
        const points26 = [];
        ema26.forEach((value, index) => {
            if (value !== null) {
                points26.push(`${scaleX(index)},${scaleY(value)}`);
            }
        });
        if (points26.length > 1) {
            path26.setAttribute('points', points26.join(' '));
            path26.setAttribute('fill', 'none');
            path26.setAttribute('stroke', '#f97316');
            path26.setAttribute('stroke-width', '2');
            path26.setAttribute('stroke-linejoin', 'round');
            path26.setAttribute('opacity', '0.7');
            svg.appendChild(path26);
        }

        // Y-axis labels (SEKARANG DI KANAN DENGAN JARAK LEBIH JAUH)
        for (let i = 0; i <= 5; i++) {
            const y = padding.top + (chartHeight - padding.top - padding.bottom) * i / 5;
            const value = maxBalance - (rangeBalance * i / 5);
            const label = document.createElementNS('http://www.w3.org/2000/svg', 'text');
            label.setAttribute('x', chartWidth - padding.right + 15);
            label.setAttribute('y', y + 4);
            label.setAttribute('text-anchor', 'start');
            label.setAttribute('font-size', '10');
            label.setAttribute('fill', '#666');
            label.textContent = this.formatCurrency(value);
            svg.appendChild(label);
        }

        // X-axis labels
        const dateIndexMap = {};
        transactions.forEach((trans, idx) => {
            if (!dateIndexMap[trans.date]) {
                dateIndexMap[trans.date] = [];
            }
            dateIndexMap[trans.date].push(idx);
        });

        Object.entries(dateIndexMap).forEach(([date, indices], dateIdx) => {
            const middleIdx = indices[Math.floor(indices.length / 2)];
            if (dateIdx % Math.max(1, Math.floor(Object.keys(dateIndexMap).length / 8)) === 0 || dateIdx === Object.keys(dateIndexMap).length - 1) {
                const x = scaleX(middleIdx);
                const label = document.createElementNS('http://www.w3.org/2000/svg', 'text');
                label.setAttribute('x', x);
                label.setAttribute('y', chartHeight - padding.bottom + 20);
                label.setAttribute('text-anchor', 'middle');
                label.setAttribute('font-size', '10');
                label.setAttribute('fill', '#666');
                label.textContent = new Date(date).toLocaleDateString('id-ID', { month: 'short', day: 'numeric' });
                svg.appendChild(label);
            }
        });

        console.log('✓ Chart:', transactions.length, 'candlesticks,', chartWidth + 'x' + chartHeight, '| Zoom:', this.zoomLevel.toFixed(2), '| Candle Width:', zoomedCandleWidth.toFixed(1));
        
        // AUTO-SCROLL KE KANAN (candlestick ke kanan default) - HANYA JIKA USER BELUM GESER
        setTimeout(() => {
            const wrapper = document.getElementById('chartWrapper');
            if (wrapper && !this.userInteractedWithScroll) {
                wrapper.scrollLeft = wrapper.scrollWidth;
                this.lastScrollPosition = wrapper.scrollLeft;
            }
        }, 50);
    },

    showTooltip(e, index, transactions) {
        const trans = transactions[index];
        const tooltip = document.getElementById('tooltip');
        const prevBalance = index > 0 ? transactions[index - 1].balance : 0;
        const change = trans.balance - prevBalance;
        const changePercent = prevBalance ? ((change / Math.abs(prevBalance)) * 100).toFixed(2) : 0;

        tooltip.innerHTML = `
            <div class="tooltip-title">${trans.type === 'income' ? '💚 PEMASUKAN' : '❤️ PENGELUARAN'}</div>
            <div class="tooltip-row">
                <span class="tooltip-label">Tanggal:</span>
                <span class="tooltip-value">${new Date(trans.date).toLocaleDateString('id-ID')}</span>
            </div>
            <div class="tooltip-row">
                <span class="tooltip-label">Jumlah:</span>
                <span class="tooltip-value ${trans.type === 'income' ? 'income' : 'expense'}">${this.formatCurrency(trans.amount)}</span>
            </div>
            <div class="tooltip-row">
                <span class="tooltip-label">Saldo:</span>
                <span class="tooltip-value">${this.formatCurrency(trans.balance)}</span>
            </div>
            <div class="tooltip-row">
                <span class="tooltip-label">Perubahan:</span>
                <span class="tooltip-value ${change >= 0 ? 'income' : 'expense'}">${this.formatCurrency(Math.abs(change))} (${change >= 0 ? '+' : ''}${changePercent}%)</span>
            </div>
        `;
        
        tooltip.classList.add('visible');
        // Tooltip SEBELAH KIRI candlestick
        const tooltipWidth = 220;
        tooltip.style.right = (window.innerWidth - e.pageX + 10) + 'px';
        tooltip.style.left = 'auto';
        tooltip.style.top = (e.pageY - 60) + 'px';
    }
};

document.addEventListener('mouseleave', function() {
    const tooltip = document.getElementById('tooltip');
    tooltip.classList.remove('visible');
});

document.addEventListener('DOMContentLoaded', function() {
    console.log('🚀 Init...');
    chart.initYearFilter();
    chart.loadData();
    
    // DETEKSI JIKA USER GESER SCROLL
    const wrapper = document.getElementById('chartWrapper');
    if (wrapper) {
        wrapper.addEventListener('scroll', function() {
            chart.userInteractedWithScroll = true;
            chart.lastScrollPosition = wrapper.scrollLeft;
        });
    }
});

chart.zoomIn = function() {
    this.zoomLevel = Math.min(3, this.zoomLevel + 0.2);
    console.log('🔍+ Zoom In:', this.zoomLevel.toFixed(2), '→ Candlestick MENGECIL');
    this.draw();
};

chart.zoomOut = function() {
    this.zoomLevel = Math.max(1, this.zoomLevel - 0.2);
    console.log('🔍- Zoom Out:', this.zoomLevel.toFixed(2), '→ Candlestick MEMBESAR');
    this.draw();
};

chart.reset = function() {
    this.zoomLevel = 1;
    console.log('Reset Zoom: 1.00 → Candlestick Normal (8px)');
    this.draw();
};

setInterval(() => chart.loadData(), 3000);
</script>