<?php
declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Table;

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

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

		$this->belongsTo('Product', [
			'foreignKey' => 'product_id'
		]);

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

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

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

	public function ifProductFavourite(int $user_id, int $product_id): array
	{
		$result = $this->find()
			->where([
				'ProductFavourite.user_id' => $user_id,
				'ProductFavourite.product_id' => $product_id
			])
			->first();

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

	public function productFavouriteCount(int $product_id): int
	{
		return $this->find()
			->where(['ProductFavourite.product_id' => $product_id])
			->count();
	}

	public function getUserFavouriteProducts(int $user_id, int $starting_point): array
	{
		return $this->find()
			->contain(['Product.ProductImage', 'Product.User'])
			->where(['ProductFavourite.user_id' => $user_id])
			->limit(10)
			->offset($starting_point * 10)
			->toArray();
	}

	public function deleteFavourite(int $user_id, int $product_id): void
	{
		$this->deleteAll([
			'ProductFavourite.user_id' => $user_id,
			'ProductFavourite.product_id' => $product_id
		], false);
	}
}
?>
