<?php
defined('_JEXEC') or die;

use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Uri\Uri;

/** @var \Joomla\Registry\Registry $params */
/** @var array $items */

// Get parameters
$chartType = $params->get('chart_type', 'bar');
$uniqueId = uniqid('grafik_keuangan_');
$activeYear = $params->get('default_year', date('Y'));

// Prepare Data for Chart
// Prepare Data for Chart
$monthNames = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'];
$labels = [];

// Initialize arrays for all components dynamically
$components = ['51', '52', '53', 'posbakum', 'prodeo'];
$datasets = [];
foreach ($components as $comp) {
    $datasets["pagu_{$comp}"] = [];
    $datasets["realisasi_{$comp}"] = [];
}

// Track cumulative realization per component
$cumulativeReal = array_fill_keys($components, 0);

if (!empty($items)) {
    foreach ($items as $item) {
        $m = (int) $item->bulan;
        if (isset($monthNames[$m])) {
            $labels[] = $monthNames[$m];

            foreach ($components as $comp) {
                $paguKey = "pagu_{$comp}";
                $realKey = "realisasi_{$comp}";

                // Get raw values
                $annualPagu = (float) $item->$paguKey;
                $monthlyReal = (float) $item->$realKey;

                // Update cumulative
                $cumulativeReal[$comp] += $monthlyReal;

                // Stack Logic:
                // Bottom Bar ("Terpakai") = Cumulative Realization
                // Top Bar ("Sisa") = Annual Pagu - Cumulative Realization
                // If Cumulative > Pagu, Sisa is 0 (or negative if allowed, but better clamped to 0 for display)

                $used = $cumulativeReal[$comp];
                $remaining = max(0, $annualPagu - $used);

                $datasets[$realKey][] = $used;
                $datasets[$paguKey][] = $remaining;
            }
        }
    }
}
?>

<div class="mod-grafik-keuangan card shadow-sm mb-3">
    <?php if ($params->get('show_year_selector', 1)): ?>
        <div class="card-header bg-white d-flex justify-content-between align-items-center py-3 module-header">
             <!-- Use 'module-title' to inherit JA Tour/T4 typography -->
            <h4 class="m-0 font-weight-bold module-title d-flex align-items-center" style="margin-bottom: 0 !important;">
                <span class="d-flex align-items-center">
                    <i class="fas fa-chart-pie mr-2" style="font-size: 1.2em; color: var(--color-primary, #007bff);"></i>
                    <span style="letter-spacing: 0.5px;">Detail Realisasi Anggaran</span>
                </span>
                <span class="badge badge-primary ml-2" style="font-size: 0.5em; vertical-align: middle;">Kumulatif</span>
            </h4>
            <select id="year_<?php echo $uniqueId; ?>" class="form-control"
                style="width: auto; font-weight: bold; border-radius: 20px; padding-left: 15px; padding-right: 15px;">
                <?php
                $currentYear = date('Y');
                for ($y = $currentYear; $y >= $currentYear - 4; $y--) {
                    $selected = ($activeYear == $y) ? 'selected' : '';
                    echo "<option value='{$y}' {$selected}>{$y}</option>";
                }
                ?>
            </select>
        </div>
    <?php endif; ?>

    <div class="card-body">
        <div style="position: relative; height: 400px; width: 100%;">
            <canvas id="chart_<?php echo $uniqueId; ?>"></canvas>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const ctx = document.getElementById('chart_<?php echo $uniqueId; ?>').getContext('2d');
            const yearSelect = document.getElementById('year_<?php echo $uniqueId; ?>');

            // Define colors: Realisasi (Used) = Solid / Darker. Pagu (Remaining) = Light / Transparent.
            const colors = {
                '51': { pagu: 'rgba(54, 162, 235, 0.3)', real: 'rgba(54, 162, 235, 1)' }, // Blue
                '52': { pagu: 'rgba(75, 192, 192, 0.3)', real: 'rgba(75, 192, 192, 1)' }, // Teal
                '53': { pagu: 'rgba(255, 206, 86, 0.3)', real: 'rgba(255, 206, 86, 1)' }, // Yellow
                'posbakum': { pagu: 'rgba(153, 102, 255, 0.3)', real: 'rgba(153, 102, 255, 1)' }, // Purple
                'prodeo': { pagu: 'rgba(255, 99, 132, 0.3)', real: 'rgba(255, 99, 132, 1)' } // Red
            };

            const chartConfig = {
                type: '<?php echo $chartType; ?>',
                data: {
                    labels: <?php echo json_encode($labels); ?>,
                    datasets: [
                        // Stack Order: Real (Bottom) then Pagu (Top)
                        // 51
                        { label: 'Terpakai 51', data: <?php echo json_encode($datasets['realisasi_51']); ?>, backgroundColor: colors['51'].real, borderColor: colors['51'].real, borderWidth: 1, stack: '51', hidden: false },
                        { label: 'Sisa 51', data: <?php echo json_encode($datasets['pagu_51']); ?>, backgroundColor: colors['51'].pagu, borderColor: colors['51'].real, borderWidth: 1, stack: '51', hidden: false },
                        // 52
                        { label: 'Terpakai 52', data: <?php echo json_encode($datasets['realisasi_52']); ?>, backgroundColor: colors['52'].real, borderColor: colors['52'].real, borderWidth: 1, stack: '52', hidden: false },
                        { label: 'Sisa 52', data: <?php echo json_encode($datasets['pagu_52']); ?>, backgroundColor: colors['52'].pagu, borderColor: colors['52'].real, borderWidth: 1, stack: '52', hidden: false },
                        // 53
                        { label: 'Terpakai 53', data: <?php echo json_encode($datasets['realisasi_53']); ?>, backgroundColor: colors['53'].real, borderColor: colors['53'].real, borderWidth: 1, stack: '53', hidden: false },
                        { label: 'Sisa 53', data: <?php echo json_encode($datasets['pagu_53']); ?>, backgroundColor: colors['53'].pagu, borderColor: colors['53'].real, borderWidth: 1, stack: '53', hidden: false },
                        // posbakum
                        { label: 'Terpakai Posbakum', data: <?php echo json_encode($datasets['realisasi_posbakum']); ?>, backgroundColor: colors['posbakum'].real, borderColor: colors['posbakum'].real, borderWidth: 1, stack: 'posbakum', hidden: false },
                        { label: 'Sisa Posbakum', data: <?php echo json_encode($datasets['pagu_posbakum']); ?>, backgroundColor: colors['posbakum'].pagu, borderColor: colors['posbakum'].real, borderWidth: 1, stack: 'posbakum', hidden: false },
                        // prodeo
                        { label: 'Terpakai Prodeo', data: <?php echo json_encode($datasets['realisasi_prodeo']); ?>, backgroundColor: colors['prodeo'].real, borderColor: colors['prodeo'].real, borderWidth: 1, stack: 'prodeo', hidden: false },
                        { label: 'Sisa Prodeo', data: <?php echo json_encode($datasets['pagu_prodeo']); ?>, backgroundColor: colors['prodeo'].pagu, borderColor: colors['prodeo'].real, borderWidth: 1, stack: 'prodeo', hidden: false }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: {
                        mode: 'index',
                        intersect: false,
                    },
                    scales: {
                        x: {
                            stacked: true,
                        },
                        y: {
                            stacked: true,
                            beginAtZero: true,
                            ticks: {
                                callback: function (value) {
                                    return new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', notation: 'compact' }).format(value);
                                }
                            }
                        }
                    },
                    plugins: {
                        tooltip: {
                            callbacks: {
                                label: function (context) {
                                    let label = context.dataset.label || '';
                                    let val = context.parsed.y;

                                    // Make tooltip clearer
                                    if (label) {
                                        label += ': ';
                                    }
                                    if (val !== null) {
                                        label += new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR' }).format(val);
                                    }
                                    return label;
                                }
                            }
                        },
                        legend: {
                            labels: {
                                filter: function (item, chart) {
                                    // Let's show 'Terpakai' in legend. Hide 'Sisa'.
                                    return item.text.includes('Terpakai');
                                },
                                usePointStyle: true,
                                padding: 20,
                                font: {
                                    family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
                                    size: 11
                                }
                            }
                        }
                    }
                }
            };

            let myChart = new Chart(ctx, chartConfig);

            // AJAX Update on Year Change
            if (yearSelect) {
                yearSelect.addEventListener('change', function () {
                    const year = this.value;
                    const baseUrl = '<?php echo Uri::root(); ?>';
                    const url = `${baseUrl}index.php?option=com_grafik_keuangan&task=getData&format=json&year=${year}`;

                    ctx.canvas.style.opacity = 0.5;

                    fetch(url)
                        .then(response => response.json())
                        .then(result => {
                            if (result.success && result.data) {
                                const items = Array.isArray(result.data) ? result.data : (result.data.data || []);

                                // Reset data
                                const comps = ['51', '52', '53', 'posbakum', 'prodeo'];
                                const newSets = {};
                                comps.forEach(c => {
                                    newSets[`pagu_${c}`] = [];
                                    newSets[`realisasi_${c}`] = [];
                                });

                                const newLabels = [];
                                const monthNames = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'];
                                let cumulativeReal = { '51': 0, '52': 0, '53': 0, 'posbakum': 0, 'prodeo': 0 };

                                items.forEach(item => {
                                    const m = parseInt(item.bulan);
                                    if (monthNames[m]) {
                                        newLabels.push(monthNames[m]);
                                        comps.forEach(c => {
                                            let annualPagu = parseFloat(item[`pagu_${c}`] || 0);
                                            let monthlyReal = parseFloat(item[`realisasi_${c}`] || 0);

                                            // Cumulative
                                            cumulativeReal[c] += monthlyReal;

                                            let used = cumulativeReal[c];
                                            let remaining = Math.max(0, annualPagu - used);

                                            newSets[`realisasi_${c}`].push(used);
                                            newSets[`pagu_${c}`].push(remaining);
                                        });
                                    }
                                });

                                // Update Labels
                                myChart.data.labels = newLabels;

                                // Update Datasets: 
                                // Order: [Terpakai 51, Sisa 51, Terpakai 52, Sisa 52...]
                                myChart.data.datasets[0].data = newSets['realisasi_51'];
                                myChart.data.datasets[1].data = newSets['pagu_51'];
                                myChart.data.datasets[2].data = newSets['realisasi_52'];
                                myChart.data.datasets[3].data = newSets['pagu_52'];
                                myChart.data.datasets[4].data = newSets['realisasi_53'];
                                myChart.data.datasets[5].data = newSets['pagu_53'];
                                myChart.data.datasets[6].data = newSets['realisasi_posbakum'];
                                myChart.data.datasets[7].data = newSets['pagu_posbakum'];
                                myChart.data.datasets[8].data = newSets['realisasi_prodeo'];
                                myChart.data.datasets[9].data = newSets['pagu_prodeo'];

                                myChart.update();
                            }
                        })
                        .catch(error => console.error('Error:', error))
                        .finally(() => {
                            ctx.canvas.style.opacity = 1;
                        });
                });
            }
        });
    </script>
</div>