<?php
namespace My\Component\GrafikKeuangan\Administrator\Model;

defined('_JEXEC') or die;

use Joomla\CMS\MVC\Model\ListModel;

class ItemsModel extends ListModel
{
	public function __construct($config = [])
	{
		if (empty($config['filter_fields'])) {
			$config['filter_fields'] = [
				'id',
				'a.id',
				'tahun',
				'a.tahun',
				'bulan',
				'a.bulan',
				'state',
				'a.state',
				'created',
				'a.created',
				'modified',
				'a.modified',
				'created_by',
				'a.created_by'
			];
		}

		parent::__construct($config);
	}

	public function getTable($type = 'Stats', $prefix = 'Administrator', $config = [])
	{
		return new \My\Component\GrafikKeuangan\Administrator\Table\GrafikKeuangan(\Joomla\CMS\Factory::getContainer()->get('DatabaseDriver'));
	}

	protected function populateState($ordering = 'a.id', $direction = 'desc')
	{
		$search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');
		$this->setState('filter.search', $search);

		$published = $this->getUserStateFromRequest($this->context . '.filter.published', 'filter_published', '');
		$this->setState('filter.published', $published);

		$year = $this->getUserStateFromRequest($this->context . '.filter.tahun', 'filter_tahun');
		$this->setState('filter.tahun', $year);

		parent::populateState($ordering, $direction);
	}

	protected function getListQuery()
	{
		$db = $this->getDatabase();
		$query = $db->getQuery(true);

		// Select all fields to allow calculation in view
		$query->select(
			$this->getState(
				'list.select',
				'a.*'
			)
		);
		$query->from($db->quoteName('#__grafik_keuangan', 'a'));

		// Filter by search in tahun
		$search = $this->getState('filter.search');
		if (!empty($search)) {
			if (stripos($search, 'id:') === 0) {
				$query->where('a.id = ' . (int) substr($search, 3));
			} else {
				$search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%'));
				$query->where('(' . $db->quoteName('a.tahun') . ' LIKE ' . $search . ')');
			}
		}

		// Filter by published state
		$published = $this->getState('filter.published');

		if (is_numeric($published)) {
			$query->where('a.state = ' . (int) $published);
		} elseif ($published === '') {
			$query->where('(a.state IN (0, 1))');
		} else {
			$query->where('(a.state IN (0, 1))');
		}

		// Filter by Year (Exact)
		$year = $this->getState('filter.tahun');
		if (!empty($year)) {
			$query->where('a.tahun = ' . (int) $year);
		}

		// Add ordering
		$orderCol = $this->state->get('list.ordering', 'a.id');
		$orderDirn = $this->state->get('list.direction', 'desc');

		if ($orderCol == 'year') {
			$orderCol = 'a.tahun';
		}

		// Sanitize ordering
		if (!in_array($orderCol, $this->filter_fields)) {
			// Fallback if sorting by unknown column
			if (strpos($orderCol, 'a.') !== 0) {
				$orderCol = 'a.id';
			}
		}

		$query->order($db->escape($orderCol . ' ' . $orderDirn));

		return $query;
	}
}
