<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\Shop\Product\Attribute;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class FilterParamsController extends Controller
{
    public function index(Request $request)
    {
        $category_id = (int) $request->category_id;

        $attributes = Attribute::with('values:id,key,attribute_id,value')
            ->where('is_enabled', true)
            ->when($request->filled('category_id'), fn ($query) => $query->where('category_id', $category_id))
            ->get(['id', 'slug', 'name', 'type', 'category_id', 'is_enabled']);

        return [
            'brands' => $this->getBrands($request),
            'attributes' => $attributes->whereNotIn('slug', ['colour', 'size'])->flatten(1),
            'sizes' => $attributes->where('slug', 'size')->map(fn ($size_attribute) => [
                'attribute_id' => $size_attribute->id,
                'values' => $size_attribute->values,
            ])->first(),
            'colours' => $attributes->where('slug', 'colour')->map(fn ($colour_attribute) => [
                'attribute_id' => $colour_attribute->id,
                'values' => $colour_attribute->values,
            ])->first(),
        ];
    }

    public function getBrands($request)
    {
        if ($request->filled('category_id')) {
            $category_id = (int) $request->category_id;

            $brand_ids = DB::table('products')
                ->join('product_has_relations', function ($join) use ($category_id) {
                    $join->on('products.id', '=', 'product_has_relations.product_id')
                        ->where('product_has_relations.productable_id', '=', $category_id)
                        ->where('product_has_relations.productable_type', '=', 'category');
                })
                ->select(['id', 'brand_id'])
                ->pluck('brand_id');

            return DB::table('brands')
                ->where('is_enabled', true)
                ->whereIn('id', $brand_ids)
                ->get(['id', 'name']);
        }

        return DB::table('brands')->where('is_enabled', true)->get(['id', 'name']);
    }
}
