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

// MANUALLY REGISTER NAMESPACE so classes can be found without DB entry
if (!class_exists('My\Component\GrafikKeuangan\Site\Controller\DisplayController')) {
	JLoader::registerNamespace('My\\Component\\GrafikKeuangan\\Site', __DIR__ . '/src');
}

use Joomla\CMS\MVC\Controller\BaseController;

class GrafikKeuanganController extends BaseController
{
	protected $default_view = 'display';

	public function getData()
	{
		$app = \Joomla\CMS\Factory::getApplication();
		$input = $app->input;
		$year = $input->getInt('year', date('Y'));
		$month = $input->getInt('month', date('n'));

		// Manually load the model
		$modelClass = '\\My\\Component\\GrafikKeuangan\\Site\\Model\\GraphModel';

		if (class_exists($modelClass)) {
			$model = new $modelClass();
		} else {
			// Try to load via manual require if autoloader fails
			$modelPath = JPATH_COMPONENT_SITE . '/src/Model/GraphModel.php';
			if (file_exists($modelPath)) {
				require_once $modelPath;
				$model = new $modelClass();
			} else {
				echo new \Joomla\CMS\Response\JsonResponse(null, 'Model class not found', true);
				$app->close();
			}
		}

		// Use getChartData to get the full year merged structure
		$item = $model->getChartData($year);

		// Format data for JSON response if needed (though current view handles it in PHP)
		// This method might be used for AJAX updates
		$response = [
			'year' => $year,
			'data' => $item, // This is now an array of 12 month objects
			'success' => true
		];

		echo new \Joomla\CMS\Response\JsonResponse($response);
		$app->close();
	}
}
