<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Http\Resources\BrandResource;
use App\Http\Resources\CategoryResource;
use App\Http\Resources\ProductPaginationResource;
use App\Models\Category;
use App\Models\Currency;
use Illuminate\Http\Request;

class CategoryController extends Controller
{
    public function index()
    {
        $categories = Category::where('parent_id', null)->orderBy('position', 'asc')->get();
        return CategoryResource::collection($categories);
    }

    public function products(Request $request, int $category_id)
    {
        $category = Category::find($category_id);

        // check if category exists
        if (!$category) {
            return response()->json(['message' => 'Category not found'], 404);
        }

        $currency = Currency::latest()->first();
        // add currency to cache
        cache()->put('currency', $currency, now()->addMinutes(60));

        // filter products by views (popular)
        // filter products by price (cheaper, expensive)
        // filter products by created_at (new)
        // filter products by brand_id
        // filter products by power (less_power, more_power)
        $products = $category->products()->where('published', true);

        if ($request->has('sort_by')) {
            switch ($request->sort_by) {
                case 'popular':
                    $products->orderBy('views', 'desc');
                    break;
                case 'cheaper':
                    // If price_discount is not null, order by price_discount; otherwise, order by price
                    $products->orderByRaw('CASE WHEN price_discount IS NOT NULL THEN price_discount ELSE price END ASC');
                    break;
                case 'expensive':
                    // If price_discount is not null, order by price_discount; otherwise, order by price
                    $products->orderByRaw('CASE WHEN price_discount IS NOT NULL THEN price_discount ELSE price END DESC');
                    break;
                case 'new':
                    $products->orderBy('created_at', 'desc');
                    break;
                case 'less_power':
                    $products->orderBy('power', 'asc');
                    break;
                case 'more_power':
                    $products->orderBy('power', 'desc');
                    break;
            }
        }
        // elseif ($category->is_filter_power) {
        // $products->orderBy('power', 'asc');
        // }
        else { // default sort by price
            $products->orderBy('price', 'asc');
        }


        if ($request->has('brand_id')) {
            $products->where('brand_id', $request->brand_id);
        }

        // price range filter
        if ($request->has('price_from') || $request->has('price_to')) {
            $products->where(function ($query) use ($request, $currency) {
                if ($request->has('price_from')) {
                    $query->where(function ($subQuery) use ($request, $currency) {
                        $subQuery->where(function ($q) use ($request, $currency) {
                            $q->whereNotNull('price_discount')
                                ->where('price_discount', '>=', $request->price_from / $currency->dollar);
                        })->orWhere(function ($q) use ($request, $currency) {
                            $q->whereNull('price_discount')
                                ->where('price', '>=', $request->price_from / $currency->dollar);
                        });
                    });
                }
                if ($request->has('price_to')) {
                    $query->where(function ($subQuery) use ($request, $currency) {
                        $subQuery->where(function ($q) use ($request, $currency) {
                            // dd($q->first());
                            $q->whereNotNull('price_discount')
                                ->where('price_discount', '<=', $request->price_to / $currency->dollar);
                        })->orWhere(function ($q) use ($request, $currency) {
                            $q->whereNull('price_discount')
                                ->where('price', '<=', $request->price_to / $currency->dollar);
                        });
                    });
                }
            });
        }

        $products = $products->paginate($request->limit ?? 20);

        return (new ProductPaginationResource($products))->response();
    }

    public function filter($category_id, Request $request)
    {
        $category = Category::find($category_id);

        $lang = $request->header('Accept-Language') ?? 'ru';

        return response()->json([
            'data' => [
                'sort_by' => [
                    [
                        'name' => $lang == 'ru' ? 'Популярные' : 'Mashhur',
                        'slug' => 'popular'
                    ],
                    [
                        'name' => $lang == 'ru' ? 'Сначало подешевле' : 'Avval arzonlari',
                        'slug' => 'cheaper'
                    ],
                    [
                        'name' => $lang == 'ru' ? 'Сначало подороже' : 'Avval qimmatlari',
                        'slug' => 'expensive'
                    ],
                    [
                        'name' => $lang == 'ru' ? 'Новые' : 'Yangi kelganlar',
                        'slug' => 'new'
                    ]
                ],
                'brands' => BrandResource::collection($category->brands)
            ]
        ]);
    }
}
