<?php

declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Table;

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

		$this->setTable('cities');

		$this->belongsTo('States', [
			'foreignKey' => 'state_id',
			'className' => 'App\Model\Table\StatesTable',
		]);

		$this->belongsTo('Countries', [
			'foreignKey' => 'country_id',
			'className' => 'App\Model\Table\CountriesTable',
		]);
	}

	public function getDetails(int $id): ?array
	{
		$entity = $this->find()
			->where(['City.id' => $id])
			->first();

		return $entity ? $entity->toArray() : null;
	}

	public function getCities(): array
	{
		return $this->find()
			->where(['City.active' => 1])
			->order(['City.name' => 'ASC'])
			->toArray();
	}

	public function getCityAgainstName(string $name, int $state_id, int $country_id): ?array
	{
		$entity = $this->find()
			->where([
				'City.name' => $name,
				'OR' => [
					'City.country_id' => $country_id,
					'City.state_id' => $state_id,
				],
			])
			->first();

		return $entity ? $entity->toArray() : null;
	}

	public function getCitiesAgainstKeywordAndStateID(string $keyword, int $state_id): array
	{
		return $this->find()
			->contain(['States', 'States.Countries'])
			->where([
				'City.active' => 1,
				'City.name LIKE' => $keyword . '%',
				'City.state_id' => $state_id,
			])
			->limit(5)
			->order(['City.name' => 'ASC'])
			->toArray();
	}

	public function getCitiesAgainstKeyword(string $keyword): array
	{
		return $this->find()
			->contain(['States', 'States.Countries'])
			->where([
				'City.active' => 1,
				'City.name LIKE' => $keyword . '%',
			])
			->limit(5)
			->order(['City.name' => 'ASC'])
			->toArray();
	}

	public function getCitiesAgainstState(int $state_id): array
	{
		return $this->find()
			->where(['City.state_id' => $state_id])
			->order(['City.name' => 'ASC'])
			->toArray();
	}
}
