<?php
/**
 * MyCitySelector
 * @author Konstantin Kutsevalov
 * @version 2.0.0
 */

defined('_JEXEC') or die(header('HTTP/1.0 403 Forbidden') . 'Restricted access');

use joomx\mcs\plugin\helpers\McsData;

class MycityselectorModelCountries extends Joomla\CMS\MVC\Model\ListModel
{

    /**
     * Table name
     * @var string
     */
    private $table = '#__mycityselector_countries';

    /**
     * Table name of names :)
     * @var string
     */
    private $tableNames = '#__mycityselector_country_names';


    /**
     * For Input object link
     * @var null
     */
    private $input = null;

    /**
     * Limit of items on page
     * @var int
     */
    private $pageLimit = 20;

    public $_forms;

    /**
     * Init
     */
    function __construct($config = [])
    {
        if (empty($config['filter_fields'])) {
            $config['filter_fields'] = ['ordering', 'id', 'name', 'code', 'published'];
        }
		parent::__construct($config);
		$this->input = Joomla\CMS\Factory::getApplication()->input;
	}


    /**
     * @return JDatabaseQuery
     */
    protected function getListQuery()
    {
        $langId = McsData::getLangId();

    	$db = $this->getDbo();
        $query = $this->_db->getQuery(true);
        $query->select('t.*, n.lang_id, n.name, n.country_id')
            ->from($this->table . ' as t')
            ->innerJoin("`{$this->tableNames}` AS `n` ON `t`.`id` = `n`.`country_id`")
            ->where("`n`.`lang_id` = {$langId}");

	    // Filter by search in title or note or id:.
	    $search = $this->getState('filter.search');
	    if (!empty($search))
	    {
		    if (stripos($search, 'id:') === 0)
		    {
			    $query->where($db->quoteName('id') . ' = ' . (int) substr($search, 3));
		    }
		    else
		    {
			    $search = $db->quote('%' . strtolower($search) . '%');
			    $query->where("(LOWER(`n`.`name`) LIKE {$search})");
		    }
	    }

	    $query->order($db->qn($db->escape($this->getState('list.ordering', 'name'))) . ' ' . $db->escape($this->getState('list.direction', 'ASC')));

        return $query;
    }



    protected function populateState($ordering = 'ordering', $direction = 'ASC')
    {
	    parent::populateState($ordering, $direction); // TODO: Change the autogenerated stub
    }

}