<?php
declare(strict_types=1);

namespace App\Model\Table;

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

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

		$this->setTable('topic');
		$this->setPrimaryKey('id');
		$this->setDisplayField('title');
	}

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

	public function checkDuplicate(string $name): ?EntityInterface
	{
		return $this->find()
			->where(['Topics.title' => $name])
			->first();
	}

	public function getAll(): array
	{
		return $this->find()->toArray();
	}

	public function getPopularTopics(array $userTopicIds = []): array
	{
		$query = $this->find()
			->select(['Topics.id', 'Topics.title', 'count' => 'COUNT(UserTopics.id)'])
			->leftJoinWith('UserTopics')
			->group(['UserTopics.topic_id'])
			->orderDesc('count');

		if (!empty($userTopicIds)) {
			$query->where(['Topics.id NOT IN' => $userTopicIds]);
		}

		return $query->enableHydration(false)->toArray();
	}

	public function getSearchResults(string $keyword, int $startingPoint): array
	{
		return $this->find()
			->where(['Topics.title LIKE' => "$keyword%"])
			->limit(10)
			->offset($startingPoint * 10)
			->toArray();
	}

	public function setDefaultToZero(): int
	{
		return $this->updateAll(
			['default' => 0],
			['default' => 1]
		);
	}
}
