<?php

namespace App\Http\Controllers\Api\V1;

use App\CentralLogics\CategoryLogic;
use App\CentralLogics\Helpers;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\GeneralStore;
use App\Models\GeneralStoreCategory;
use App\Models\Item;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class CategoryController extends Controller
{
    public function get_categories(Request $request,$search=null): \Illuminate\Http\JsonResponse
    {
        try {
            $key = explode(' ', $search);
            $featured = $request->query('featured');
            $categories = new Category;//->with(['childes' => function($query)  {
            //$categories = Category::withCount(['products','childes']);//->with(['childes' => function($query)  {
            //    $query->withCount(['products','childes']);
            //}]);

            $itemQuery = Item::where('status', 1)->where('is_approved', 1);
            if (isset($request->store_id) and $request->store_id != 'null' and $request->store_id != null) {
                $itemQuery->where('store_id', $request->store_id);
            }
            $itemCategoryIds = $itemQuery->pluck('category_id')->toArray();

            if(isset($request->with_sub_categories) and $request->with_sub_categories == 'true') {
                $categories = $categories->where('status', 1)->where('position', '>', 0);
                if (!empty($itemCategoryIds)) {
                    $categories = $categories->whereIn('id', $itemCategoryIds);
                } else {
                    $categories = $categories->whereRaw('0 = 1');
                }
                if (isset($request->parent_id)) {
                    $categories = $categories->where('parent_id', $request->parent_id);
                }
            }else{
                $categories = $categories->where(['position' => 0, 'status' => 1]);
                if (!empty($itemCategoryIds)) {
                    $parentIds = Category::whereIn('id', $itemCategoryIds)
                        ->pluck('parent_id')
                        ->filter()
                        ->unique()
                        ->toArray();
                    $validCategoryIds = array_unique(array_merge($itemCategoryIds, $parentIds));
                    $categories = $categories->whereIn('id', $validCategoryIds);
                } else {
                    $categories = $categories->whereRaw('0 = 1');
                }
            }
            $categories = $categories->when(config('module.current_module_data'), function($query){
                $query->module(config('module.current_module_data')['id']);
            })
            ->when($featured, function($query){
                $query->featured();
            })
            ->when($search, function($query)use($key){
                $query->where(function ($q) use ($key) {
                    foreach ($key as $value) {
                        $q->orWhere('name', 'like', "%". $value."%");
                    }
                });
            })
            ->orderBy('priority','desc')->get();

            return response()->json(Helpers::category_data_formatting($categories, true), 200);
        } catch (\Exception $e) {
            return response()->json([], 200);
        }
    }

    public function getGeneralStoreCategories(Request $request): \Illuminate\Http\JsonResponse
    {
        $categoriesList = [];
        $categories = GeneralStoreCategory::orderBy('id','asc')->get();
        $firstItem = [
            'id' => 0,
            'en_name' => 'All',
            'ar_name' => 'الكل',
            'image' => '',
            'module_id' => 1,
            'created_at' => now(),
            'updated_at' => now(),
            'count' => GeneralStore::where('is_approved', 1)->count(),
        ];
        $categoriesList[] = $firstItem;
        foreach ($categories as $category) {
            $category['count'] = GeneralStore::where('is_approved', 1)->where('general_store_category_id', $category->id)->count();
            $categoriesList[] = $category;
        }

        //where('module_id', $request->module_id)->
        return response()->json($categoriesList, 200);
    }

    public function get_childes($id)
    {
        try {
            $categories = Category::query();
            if(is_numeric($id)){
                $categories = $categories->where('parent_id', $id);
            } else {
                $categories = $categories->whereHas('parent',function($query)use($id){
                    $query->where('slug',$id);
                });
            }
            $categories = $categories->where('status',1)->orderBy('priority','desc')->get();
            return response()->json(Helpers::category_data_formatting($categories, true), 200);
        } catch (\Exception $e) {
            return response()->json([], 200);
        }
    }

    public function get_products($id, Request $request)
    {
        if (!$request->hasHeader('zoneId')) {
            $errors = [];
            array_push($errors, ['code' => 'zoneId', 'message' => translate('messages.zone_id_required')]);
            return response()->json([
                'errors' => $errors
            ], 403);
        }
        $validator = Validator::make($request->all(), [
            'limit' => 'required',
            'offset' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => Helpers::error_processor($validator)], 403);
        }

        $zone_id= $request->header('zoneId');

        $type = $request->query('type', 'all');

        $moduleID = isset($request->module_id) ? $request->module_id : null;

        $data = CategoryLogic::products($id, $zone_id, $request['limit'], $request['offset'], $type, $moduleID);
        $data['products'] = Helpers::product_data_formatting($data['products'] , true, false, app()->getLocale());
        return response()->json($data, 200);
    }


    public function get_stores($id, Request $request)
    {
        if (!$request->hasHeader('zoneId')) {
            $errors = [];
            array_push($errors, ['code' => 'zoneId', 'message' => translate('messages.zone_id_required')]);
            return response()->json([
                'errors' => $errors
            ], 403);
        }
        $validator = Validator::make($request->all(), [
            'limit' => 'required',
            'offset' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => Helpers::error_processor($validator)], 403);
        }

        $zone_id= $request->header('zoneId');
        $longitude= $request->header('longitude');
        $latitude= $request->header('latitude');
        $type = $request->query('type', 'all');

        $data = CategoryLogic::stores($id, $zone_id, $request['limit'], $request['offset'], $type,$longitude,$latitude);
        $data['stores'] = Helpers::store_data_formatting($data['stores'] , true);
        return response()->json($data, 200);
    }



    public function get_all_products($id,Request $request)
    {
        if (!$request->hasHeader('zoneId')) {
            $errors = [];
            array_push($errors, ['code' => 'zoneId', 'message' => translate('messages.zone_id_required')]);
            return response()->json([
                'errors' => $errors
            ], 403);
        }
        $zone_id= $request->header('zoneId');

        try {
            return response()->json(Helpers::product_data_formatting(CategoryLogic::all_products($id, $zone_id), true, false, app()->getLocale()), 200);
        } catch (\Exception $e) {
            return response()->json([], 200);
        }
    }
}
