<?php
declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\ORM\Query;

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

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

		$this->belongsTo('Sound', [
			'foreignKey' => 'sound_id',
			'joinType' => 'INNER'
		]);

		$this->belongsTo('User', [
			'foreignKey' => 'user_id',
			'joinType' => 'INNER'
		]);
	}

	public function getDetails(int $id): array
	{
		$result = $this->find()
			->where(['SoundFavourite.id' => $id])
			->contain(['Sound', 'User'])
			->first();

		return $result ? $result->toArray() : [];
	}

	public function getUserFavouriteSounds(int $user_id, int $starting_point): array
	{
		$query = $this->find()
			->where(['SoundFavourite.user_id' => $user_id])
			->limit(10)
			->offset($starting_point * 10)
			->contain(['Sound']);

		return $query->toArray();
	}

	public function ifExist(array $data): array
	{
		$result = $this->find()
			->where([
				'SoundFavourite.sound_id' => $data['sound_id'],
				'SoundFavourite.user_id' => $data['user_id']
			])
			->first();

		return $result ? $result->toArray() : [];
	}

	public function searchFavouriteSound(string $keyword, int $starting_point, int $user_id): array
	{
		$query = $this->find()
			->where([
				'SoundFavourite.user_id' => $user_id,
				'Sound.publish' => 1,
				'OR' => [
					['Sound.name LIKE' => "%$keyword%"],
					['Sound.description LIKE' => "%$keyword%"]
				]
			])
			->limit(10)
			->offset($starting_point * 10)
			->contain(['Sound']);

		return $query->toArray();
	}

	public function getAll(): array
	{
		return $this->find()->contain(['Sound', 'User'])->toArray();
	}
}
?>
