<?php
namespace My\Module\GrafikKeuangan\Site\Helper;

defined('_JEXEC') or die;

use Joomla\CMS\Factory;

class GrafikKeuanganHelper
{
    public static function getData($params)
    {
        $db = Factory::getContainer()->get('DatabaseDriver');
        $query = $db->getQuery(true);

        // Default to current year if not specified
        $year = $params->get('default_year', date('Y'));
        if (empty($year)) {
            $year = date('Y');
        }

        // 1. Fetch Pagu (Month 0)
        $queryPagu = $db->getQuery(true)
            ->select('*')
            ->from($db->quoteName('#__grafik_keuangan'))
            ->where($db->quoteName('tahun') . ' = ' . (int) $year)
            ->where($db->quoteName('bulan') . ' = 0');
        $db->setQuery($queryPagu);
        $paguData = $db->loadObject();

        // 2. Fetch Realisasi (Months 1-12)
        $queryReal = $db->getQuery(true)
            ->select('*')
            ->from($db->quoteName('#__grafik_keuangan'))
            ->where($db->quoteName('tahun') . ' = ' . (int) $year)
            ->where($db->quoteName('bulan') . ' > 0')
            ->order('bulan ASC');
        $db->setQuery($queryReal);
        $realisasiData = $db->loadObjectList('bulan');

        // 3. Merge Data: Create entry ONLY for months that have Realisasi Data
        $results = [];
        for ($m = 1; $m <= 12; $m++) {
            // Check if this month exists in realisasiData
            if (!isset($realisasiData[$m])) {
                continue; // Skip months with no data
            }

            $obj = new \stdClass();
            $obj->bulan = $m;
            $obj->tahun = $year;

            // Set Pagu (fixed for year) - Project Pagu onto this month
            $obj->pagu_51 = $paguData ? $paguData->pagu_51 : 0;
            $obj->pagu_52 = $paguData ? $paguData->pagu_52 : 0;
            $obj->pagu_53 = $paguData ? $paguData->pagu_53 : 0;
            $obj->pagu_posbakum = $paguData ? $paguData->pagu_posbakum : 0;
            $obj->pagu_prodeo = $paguData ? $paguData->pagu_prodeo : 0;

            // Set Realisasi (monthly)
            $rItem = $realisasiData[$m];
            $obj->realisasi_51 = $rItem->realisasi_51;
            $obj->realisasi_52 = $rItem->realisasi_52;
            $obj->realisasi_53 = $rItem->realisasi_53;
            $obj->realisasi_posbakum = $rItem->realisasi_posbakum;
            $obj->realisasi_prodeo = $rItem->realisasi_prodeo;

            $results[] = $obj;
        }

        return $results;
    }

    public static function getYears()
    {
        $db = Factory::getContainer()->get('DatabaseDriver');
        $query = $db->getQuery(true);

        $query->select('DISTINCT a.tahun')
            ->from($db->quoteName('#__grafik_keuangan', 'a'))
            ->order('a.tahun DESC');

        $db->setQuery($query);
        return $db->loadColumn();
    }
}
