<?php

namespace App\Http\Resources\Api\v1\Taxonomy;

use App\Models\Admin\Product;
use Illuminate\Http\Resources\Json\ResourceCollection;

class TaxonomyResourceCollection extends ResourceCollection
{
    private $mainCategoryId;
    private $subCategoryId;

    public function __construct($resource, $mainCategoryId = null, $subCategoryId = null)
    {
        parent::__construct($resource);
        $this->mainCategoryId = $mainCategoryId;
        $this->subCategoryId = $subCategoryId;
    }

    public function toArray($request)
    {
        return [
            'main_categories' => [
                'title' => get_language_variable('products.filter.main_category'),
                'content' => $this->collection,
            ],
            'dikkan_figures' => [
                'title' => get_language_variable('products.filter.figure'),
                'content' => $this->getDikkanFigures(),
            ],
            'impa_codes' => [
                'title' => get_language_variable('products.filter.impa'),
                'content' => $this->getImpaCodes(),
            ],
        ];
    }

    public function getDikkanFigures()
    {
        $productsQuery = Product::query();

        if ($this->mainCategoryId && $this->subCategoryId) {
            $productsQuery->whereHas('taxonomies', function ($query) {
                $query->where('taxonomy.id', $this->subCategoryId);
            });
        }
        elseif ($this->mainCategoryId) {
            $productsQuery->whereHas('taxonomies', function ($query) {
                $query->where('parent_id', $this->mainCategoryId);
            });
        }

        $products = $productsQuery->pluck('dikkan_figure')->toArray();
        $uniqueFigures = array_values(array_unique(array_filter($products)));

        $result = [];
        foreach ($uniqueFigures as $figure) {
            $result[] = ['figure' => $figure];
        }

        return $result;
    }

    public function getImpaCodes()
    {
        $productsQuery = Product::query();

        if ($this->mainCategoryId && $this->subCategoryId) {
            $productsQuery->whereHas('taxonomies', function ($query) {
                $query->where('taxonomy.id', $this->subCategoryId);
            });
        }
        elseif ($this->mainCategoryId) {
            $productsQuery->whereHas('taxonomies', function ($query) {
                $query->where('parent_id', $this->mainCategoryId);
            });
        }

        $products = $productsQuery->pluck('impa_code')->toArray();
        $uniqueCodes = array_values(array_unique(array_filter($products)));

        $result = [];
        foreach ($uniqueCodes as $code) {
            $result[] = ['impa' => $code];
        }

        return $result;
    }
}
