<?php

declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\ORM\Query;
use Cake\Datasource\EntityInterface;
use Cake\Datasource\ResultSetInterface;

class StatesTable extends Table
{
	public function initialize(array $config): void
	{
		parent::initialize($config);

		$this->setTable('states');
		$this->setPrimaryKey('id');

		$this->belongsTo('Countries', [
			'foreignKey' => 'country_id',
		]);
	}

	public function getDetails(int $id): ?EntityInterface
	{
		return $this->find()
			->where(['States.id' => $id])
			->first();
	}

	public function getStates(): ResultSetInterface
	{
		return $this->find()
			->where(['States.active' => 1])
			->orderAsc('States.name')
			->all();
	}

	public function getStateAgainstName(string $name, int $country_id): ?EntityInterface
	{
		return $this->find()
			->where([
				'States.name' => $name,
				'States.country_id' => $country_id,
			])
			->first();
	}

	public function getStateAgainstShortName(string $name, int $country_id): ?EntityInterface
	{
		return $this->find()
			->where([
				'States.short_name' => $name,
				'States.country_id' => $country_id,
			])
			->first();
	}

	public function getStatesAgainstKeywordAndCountry(string $keyword, int $country_id): ResultSetInterface
	{
		return $this->find()
			->where([
				'States.active' => 1,
				'States.name LIKE' => $keyword . '%',
				'States.country_id' => $country_id,
			])
			->limit(5)
			->orderAsc('States.name')
			->all();
	}

	public function getStatesAgainstKeyword(string $keyword): ResultSetInterface
	{
		return $this->find()
			->where([
				'States.active' => 1,
				'States.name LIKE' => $keyword . '%',
			])
			->limit(5)
			->orderAsc('States.name')
			->all();
	}

	public function getStatesAgainstCountry(int $country_id): ResultSetInterface
	{
		return $this->find()
			->where(['States.country_id' => $country_id])
			->orderAsc('States.name')
			->all();
	}
}
