<?php
namespace Joomla\Component\Panggilan\Site\Model;

use Joomla\CMS\MVC\Model\BaseDatabaseModel;

defined('_JEXEC') or die;

class DisplayModel extends BaseDatabaseModel
{
    /**
     * Get the active year from request or DB max
     */
    public function getActiveYear()
    {
        $input = \Joomla\CMS\Factory::getApplication()->input;
        $year = $input->getInt('year');

        if (!$year) {
            $db = $this->getDatabase();
            $query = $db->getQuery(true)
                ->select('MAX(year)')
                ->from('#__panggilan_items')
                ->where('state = 1');
            $db->setQuery($query);
            $year = (int) $db->loadResult();

            if (!$year) {
                $year = (int) date('Y');
            }
        }

        return $year;
    }

    /**
     * Get available years for sidebar
     */
    public function getAvailableYears()
    {
        $db = $this->getDatabase();
        $query = $db->getQuery(true)
            ->select('DISTINCT year')
            ->from('#__panggilan_items')
            ->where('state = 1')
            ->order('year DESC');

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

    /**
     * Get items for the year, grouped by month
     * Efficient single query fetch.
     */
    public function getItemsByYear($year)
    {
        $db = $this->getDatabase();
        $query = $db->getQuery(true)
            ->select('*')
            ->from('#__panggilan_items')
            ->where('state = 1')
            ->where('year = ' . (int) $year)
            ->order('month ASC, ordering ASC, hearing_date ASC');

        $db->setQuery($query);
        $items = $db->loadObjectList();

        // Initialize all months empty
        $grouped = [];
        for ($m = 1; $m <= 12; $m++) {
            $grouped[$m] = [];
        }

        // Group by PHP
        foreach ($items as $item) {
            $item->file_url = trim($item->file_url);
            if (isset($grouped[$item->month])) {
                $grouped[$item->month][] = $item;
            }
        }

        return $grouped;
    }
}
