<?php
declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Table;

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

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

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

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

	public function getAvgRatings(int $product_id): array
	{
		$result = $this->find()
			->select([
				'average' => $this->find()->func()->avg('ProductRating.star'),
				'total_ratings' => $this->find()->func()->count('ProductRating.id')
			])
			->where(['ProductRating.product_id' => $product_id])
			->group(['ProductRating.product_id'])
			->first();

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

	public function getComments(int $product_id): array
	{
		return $this->find()
			->contain(['User'])
			->where(['ProductRating.product_id' => $product_id])
			->toArray();
	}

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

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

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

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