<?php

namespace App\Http\Controllers\Api;

use App\Enums\UsersTypesEnums;
use App\Http\Controllers\Controller;
use App\Http\Resources\CategoryResource;
use App\Http\Resources\CategoryShopsResource;
use App\Http\Resources\PaginateCollection;
use App\Http\Resources\ProductsResource;
use App\Http\Resources\ShopResource;
use App\Http\Resources\UserResource;
use App\Models\Category;
use App\Models\Product;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class CategoriesController extends Controller
{
    public function index() {
        return response()->json([
            'categories'    =>  CategoryResource::collection(Category::query()->orderBy('order')->where('is_active', 1)->get())
        ]);
    }

    public function categoryShops(Request $request) {
        $category = Category::query()->where('id', $request->input('category_id'))->first();

        $shops  =   User::query()
            ->whereHas('activeCategories')
            ->whereHas('activeProducts')
            ->where('is_active',true)
            ->when($request->input('search_word') != null, function ($q) use($request) {
                return $q->where(function($q) use($request){
                    $q->where('shop_name', 'like', "%{$request->input('search_word')}%")
                    ->orWhere('shop_name_en', 'like', "%{$request->input('search_word')}%");
                });
            })
            ->paginate(env('PerPage'), '*', 'shops_page');
        return response()->json([
            'category'  =>  $category ? new CategoryResource($category) : null,
            'shops'    =>  ShopResource::collection($shops)
        ]+ PaginateAttributes($shops, 'shops'));
    }

    public function ShopProducts(Request $request) {
        $shop = User::query()
            ->where('id', $request->input('shop_id'))
            ->firstOrFail();
        $products   =   $shop->activeProducts()
//            ->when($request->input('category_id'), function ($q) use($request){
//                return $q->where('category_id', $request->input('category_id'));
//            })
            ->when($request->input('search_word'), function ($q) use($request){
                return $q->where('ar_description', 'like', "%$request->input('search_word')%")
                    ->orWhere('en_description', 'like', "%$request->input('search_word')%");
            })
//            ->where('is_active' , 1)
//            ->where('is_approved' , 1)
            ->paginate(env('PerPage'), '*', 'products_page');
        return response()->json([
            'products'  =>  ProductsResource::collection($products),
            'shop'    =>  new ShopResource($shop)
        ]+ PaginateAttributes($products, 'products'));

    }
}
