<?php

declare(strict_types=1);

namespace App\Model\Table;

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

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

		$this->setTable('category');

		$this->belongsTo('Parent', [
			'className' => self::class,
			'foreignKey' => 'parent_id',
		]);

		$this->hasMany('Product', [
			'className' => 'App\Model\Table\ProductsTable',
			'foreignKey' => 'category_id',
			'dependent' => true,
		]);

		$this->hasMany('Children', [
			'className' => self::class,
			'foreignKey' => 'parent_id',
			'dependent' => true,
		]);
	}

	public function getDetails(int $id): array
	{
		return $this->get($id)->toArray();
	}

	public function getAll(int $parent_id): array
	{
		return $this->find()
			->where(['Category.parent_id' => $parent_id])
			->toArray();
	}

	public function getAllMostOccurance(): array
	{
		$query = $this->find();

		$query->select([
				'Category.id',
				'Category.name',
				'product_count' => $query->func()->count('Product.id')
			])
			->innerJoinWith('Product')
			->group('Category.id')
			->orderDesc('product_count')
			->limit(10)
			->contain([
				'Product' => function (Query $q) {
					return $q->limit(10)
						->contain([
							'ProductImage',
							'ProductAttribute.ProductAttributeVariation'
						]);
				}
			]);

		return $query->toArray();
	}
}
