<?php
declare(strict_types=1);

namespace App\Model\Table;

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

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

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

		$this->belongsTo('Topic', [
			'foreignKey' => 'topic_id',
			'dependent' => true
		]);

		$this->hasMany('RoomMember', [
			'foreignKey' => 'room_id',
			'dependent' => true
		]);
	}

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

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

	public function getRoomsAgainstClub(int $club_id): array
	{
		return $this->find()
			->where([
				'Room.club_id' => $club_id,
				'Room.privacy' => 0
			])
			->contain(['RoomMember.User'])
			->toArray();
	}

	public function getSearchResults(string $keyword, int $starting_point): array
	{
		return $this->find()
			->where([
				'Room.title LIKE' => "$keyword%",
				'Room.delete' => 0
			])
			->contain(['RoomMember.User', 'Topic'])
			->limit(10)
			->offset($starting_point * 10)
			->toArray();
	}

	public function getRoomsCreatedAgainstUser(): array
	{
		return $this->find()
			->where([
				'Room.club_id' => 0,
				'Room.delete' => 0
			])
			->contain(['RoomMember.User'])
			->toArray();
	}

	public function getUserRooms(int $user_id): array
	{
		return $this->find()
			->where([
				'Room.user_id' => $user_id,
				'Room.delete' => 0
			])
			->contain(['RoomMember.User', 'Topic'])
			->toArray();
	}

	public function getAll(): array
	{
		$query = $this->find()
			->contain(['RoomMember.User', 'Topic'])
			->leftJoinWith('RoomMember')
			->leftJoinWith('RoomMember.User')
			->where([
				'OR' => [
					'User.id IS NOT' => null,
					'RoomMember.user_id IS' => null
				]
			])
			->group(['Room.id']);

		return $query->toArray();
	}
}
?>
