<?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 StickersTable extends Table
{
	public function initialize(array $config): void
	{
		parent::initialize($config);

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

		$this->hasMany('ProfileVisits', [
			'foreignKey' => 'sticker_id',
		]);
	}

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

	public function getAll(string $type, int $starting_point): ResultSetInterface
	{
		return $this->find()
			->limit(40)
			->offset($starting_point * 40)
			->all();
	}

	public function getAllAdmin(): ResultSetInterface
	{
		return $this->find()->all();
	}

	public function getProfileVisitorsUnreadCount(int $user_id): int
	{
		return $this->getAssociation('ProfileVisits')->getTarget()
			->find()
			->where([
				'ProfileVisits.user_id' => $user_id,
				'ProfileVisits.read' => 0
			])
			->group('ProfileVisits.visitor_id')
			->count();
	}

	public function updateReadCount(int $user_id): void
	{
		$this->getAssociation('ProfileVisits')->getTarget()
			->updateAll(
				['read' => 1],
				['user_id' => $user_id]
			);
	}
}
