<?php
namespace My\Component\GrafikKeuangan\Site\Controller;

defined('_JEXEC') or die;

use Joomla\CMS\MVC\Controller\BaseController;
use Joomla\CMS\Response\JsonResponse;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;

class StatsController extends BaseController
{
	public function getData()
	{
		$app = Factory::getApplication();
		$input = $app->getInput();

		// 1. Sanitasi Input
		$year = $input->getInt('year', 0);

		// Validasi format JSON is requested (optional check, but good practice)
		if ($input->get('format') !== 'json') {
			// Fallback or error if strict
		}

		// 2. Validasi Input
		if ($year <= 1900 || $year > 2100) {
			echo new JsonResponse(null, Text::_('JERROR_ALERTNOAUTHOR'), true);
			$app->close();
		}

		// Get Model
		$model = $this->getModel('Graph', 'Site');

		if (!$model) {
			echo new JsonResponse(null, 'Model not found', true);
			$app->close();
		}

		// 3. Fetch Data (Model respects state=1 and Sorts by Count DESC)
		$items = $model->getData($year);

		// 4. Format Output
		$formattedData = [];
		foreach ($items as $item) {
			$formattedData[] = [
				'label' => $item->case_type,
				'value' => (int) $item->total
			];
		}

		$response = [
			'year' => $year,
			'seriesLabel' => Text::_('COM_GRAFIK_KEUANGAN_CHART_LEGEND'),
			'data' => $formattedData
		];

		// Return JSON
		echo new JsonResponse($response);
		$app->close();
	}
}
