<?php

namespace App\Repositories\Catalog;

use App\Models\Items;
use App\Models\StoreCategoryMap;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class ProductRepository
{
    public function getList($params)
    { 
        $event = @$params["event"];
        $sort = @$params["sort"];
        $search = @$params["search"];
        $category_id = @$params["category_id"];
        $brand_id = @$params["brand_id"];
        $gender_id = @$params["gender_id"];
        $limit = @$params["limit"];
        $builder = Items::select('items.*','percent')
            ->leftJoin('item_dimension', 'item_dimension.no', 'items.number')
           ->leftJoin(DB::raw("(select distinct on (item_id) item_id, percent, discounts.created_at,
                case when discounts.valid_at is null then 'special-offer' else 'limited-sale' end as event
                from discount_items
                left join item_reference on item_reference_id = item_reference.id
                left join discounts on discounts.id = discount_id
                where discounts.type = 'discount' and
                ( discounts.valid_at is null or discounts.valid_at <= now()) and
                ( discounts.valid_at is null or discounts.expired_at >= now())
            order by item_id, discounts.created_at desc
                ) as d"),"d.item_id","=","items.id")
            ->when(true, function($query) use ($event, $sort){
            if ($event){
                $query->orderByRaw("case when brand = 'CHAMELO' then 1 else 2 end ASC ");

                $query->orderBy("percent", "desc");
            }else{

            /* if ($event == "special-offer"){
            $query->orderByRaw("case when brand = 'CHAMELO' then 1 else 2 end ASC ");
            } */

            if ($sort == "new"){
            \Log::info($sort);

                $query->orderByRaw("case when category1 in ('CLUBS','CLUB','COMPONENT HEAD') and brand = 'PXG' then 1 else 2 end ASC");
            }else{
                $query->orderByRaw("case when d.created_at is not null then 1 else 2 end ASC, random()");
            }

            //      $query->orderByRaw("items.created_at desc NULLS LAST");
            }

            }) 
            ->where("is_publish", true)
            ->when($search, function ($query) use ($search) {
                $query->where(function ($query) use ($search) {
                    $query->where('number', 'ILIKE', "%$search%")
                        ->orWhere('name', 'ILIKE', "%$search%")
                        ->orWhere('alias_name', 'ILIKE', "%$search%");
                });
            })
            ->when($brand_id, function ($query) use ($brand_id) {
                $query->where('brand_id', $brand_id);
            })
            ->when($gender_id, function ($query) use ($gender_id) {
                $query->where('gender_id', $gender_id);
            })
            ->when($event, function($query) use ($event){
                $query->where('d.event', $event);
            });

        if ($category_id) {
            $categories = StoreCategoryMap::where('store_category_id', $category_id)->get();
            $builder->where(function ($query) use ($categories) {
                $i = 0;
                foreach ($categories as $category) {
                    if ($i == 0) {
                        $query->where(function ($query) use ($category) {
                            $query->where('item_dimension.category1', $category->category1)
                                ->where('item_dimension.category2', $category->category2);
                        });
                    } else {
                        $query->orWhere(function ($query) use ($category) {
                            $query->where('item_dimension.category1', $category->category1)
                                ->where('item_dimension.category2', $category->category2);
                        });
                    }
                    $i++;
                }
            });
        }

        return $builder->paginate($limit);
    }

    public function show($slug)
    {
        $product = Items::where('slug', $slug)->first();



        if ($product == null) {
            abort(404);
        }

        $all = session()->get('viewed_products', []);
        $all[] = $product->id;
        session()->put('viewed_products', array_unique($all));

        return $product;
    }

    public function viewed_products($except_ids = [])
    {
        $ids = session()->get('viewed_products', []);
        if (empty($ids)) {
            return collect();
        }
        
        // Remove except_ids from the list
        $ids = array_diff($ids, (array)$except_ids);
        
        return Items::whereIn('id', $ids)->inRandomOrder()->take(10)->get();
    }
}
