<?php

namespace App\Http\Controllers\Site;

use App\Models\Admin\Page;
use Illuminate\Http\Request;
use App\Models\Admin\Product;
use App\Models\Admin\Taxonomy;
use App\Enums\ProductCategories;
use App\Http\Controllers\Controller;

class ProductController extends Controller
{
    public function index(Request $request)
    {
        $filter = $request->get('filter');

        $main_categories = Taxonomy::where('parent_id', ProductCategories::CATEGORY->value)->get();

        if($filter) {
            $mainCategoryId = $request->get('industry');
            $category = $request->get('category');
            $figure = $request->get('figure');
            $impa = $request->get('impa');

            $productsQuery = Product::query();

            if(!$category){
                $productsQuery->whereHas('taxonomies', function ($query) use ($mainCategoryId) {
                    $query->whereHas('parent', function ($parentQuery) use ($mainCategoryId) {
                        $parentQuery->where('id', $mainCategoryId);
                    });
                });
            } else {
                $productsQuery->whereHas('taxonomies', function ($query) use ($category) {
                    $query->where('taxonomy.id', $category);
                });
            }

            if($figure){
                $productsQuery->where('dikkan_figure', $figure);
            }

            if($impa){
                $productsQuery->where('impa_code', $impa);
            }

            $products = $productsQuery->paginate(12);
        }else{
            $products = Product::paginate(12);
        }

        return view('site.product.index', [
            'products' => $products,
            'mainCategoryId' => $mainCategoryId ?? null,
            'category' => $category ?? null,
            'figure' => $figure ?? null,
            'impa' => $impa ?? null,
            'main_categories' => $main_categories
        ]);
    }

    public function category(Request $request, $slug)
    {
        $main_categories = Taxonomy::where('parent_id', ProductCategories::CATEGORY->value)->get();

        $locale = app()->getLocale();

        $page = Page::where("slug->$locale", $slug)->first();
        $mainCategoryId = intval($page->description);

        $productsQuery = Product::query();

        $productsQuery->whereHas('taxonomies', function ($query) use ($mainCategoryId) {
            $query->whereHas('parent', function ($parentQuery) use ($mainCategoryId) {
                $parentQuery->where('id', $mainCategoryId);
            });
        });

        $products = $productsQuery->paginate(12);

        return view('site.product.category', [
            'page' => $page,
            'products' => $products,
            'mainCategoryId' => $mainCategoryId,
            'main_categories' => $main_categories
        ]);
    }

    public function detail(Request $request, $figure, $slug)
    {
        $absoluteHeader = true;

        $product = Product::where('slug', 'like', '%'.$slug.'%' )->where('dikkan_figure', $figure)->first();

        $category = $product->taxonomies->where('parent.parent_id', ProductCategories::CATEGORY->value)->first();

        $material = $product->taxonomies->where('parent_id', ProductCategories::MATERIAL->value)->first();
        $trim = $product->taxonomies->where('parent_id', ProductCategories::TRIM->value)->first();
        $type = $product->taxonomies->where('parent_id', ProductCategories::TYPE->value)->first();

        $icons = explode(',', $product->icons);

        $icons = collect($icons)->map(function($iconId){
            $taxonomy = Taxonomy::where('id', $iconId)->first();
            return [
                'id' => $iconId,
                'taxonomy' => $taxonomy
            ];
        });

        $relatedProducts = Product::select('title', 'dikkan_figure', 'slug', 'image_path')
            ->where('id', '!=', $product->id)
            ->whereHas('taxonomies', function ($query) use ($category) {
                $query->where('taxonomy.id', $category->id);
            })
            ->inRandomOrder()
            ->limit(4)
            ->get();

        $variationsTable = $this->generateVariantTable($this->transformVariants($product));

        return view('site.product.detail', [
            'absoluteHeader' => $absoluteHeader,
            'product' => $product,
            'category' => $category ?? null,
            'material' => $material ?? null,
            'trim' => $trim ?? null,
            'type' => $type ?? null,
            'icons' => $icons,
            'relatedProducts' => $relatedProducts,
            'variationsTable' => $variationsTable
        ]);
    }

    private function transformVariants($product)
    {
        $taxonomiesWithPivot = $product->taxonomies()->withPivot('value')->get();


        $variantInputGroup = [
            'product_code' => [],
            'flange' => [],
            'w_p__o_d__f_l' => [],
            'd_n' => []
        ];

        foreach ($taxonomiesWithPivot as $taxonomy) {
            $taxonomyId = $taxonomy->id;
            $value = $taxonomy->pivot->value ?? '';

            switch ($taxonomyId) {
                case 18:
                    $variantInputGroup['product_code'][] = $value;
                    break;
                case 19:
                    $variantInputGroup['flange'][] = $value;
                    break;
                case 20:
                    $variantInputGroup['w_p__o_d__f_l'][] = $value;
                    break;
                case 21:
                    $variantInputGroup['d_n'][] = $value;
                    break;
            }
        }

        $variantInputs = [];

        if (!empty($variantInputGroup)) {
            foreach (range(0, max(array_map('count', $variantInputGroup)) - 1) as $index) {
                $variantInputs[] = [
                    'product_code' => $variantInputGroup['product_code'][$index] ?? '',
                    'flange' => $variantInputGroup['flange'][$index] ?? '',
                    'w_p__o_d__f_l' => $variantInputGroup['w_p__o_d__f_l'][$index] ?? '',
                    'd_n' => $variantInputGroup['d_n'][$index] ?? '',
                ];
            }
        }

        return $variantInputs;
    }

    private function generateVariantTable($variants)
    {
        if (empty($variants))
            return '';

        $tableHtml = '<table><thead><tr><th>Product Code</th><th>Flange</th><th>WP/OD/FL</th><th>DN</th></tr></thead><tbody>';

        foreach ($variants as $variant) {
            $tableHtml .= '<tr>';
            $tableHtml .= '<td>' . htmlspecialchars($variant['product_code'], ENT_QUOTES, 'UTF-8') . '</td>';
            $tableHtml .= '<td>' . htmlspecialchars($variant['flange'], ENT_QUOTES, 'UTF-8') . '</td>';
            $tableHtml .= '<td>' . htmlspecialchars($variant['w_p__o_d__f_l'], ENT_QUOTES, 'UTF-8') . '</td>';
            $tableHtml .= '<td>' . htmlspecialchars($variant['d_n'], ENT_QUOTES, 'UTF-8') . '</td>';
            $tableHtml .= '</tr>';
        }

        $tableHtml .= '</tbody></table>';

        return $tableHtml;
    }
}