<?php

namespace Modules\Category\Http\Controllers;

use App\Functions\ResponseHelper;
use App\Http\Controllers\BasicController;
use Modules\Category\Entities\Model;
use Modules\Category\Http\Resources\CategoryResource;

class APIController extends BasicController
{
    public function index()
    {
        $Models = Model::where('status', 1)
            ->when(request('category_id'), function ($query) {
                return $query->where('parent_id', request('category_id'));
            })
            
            ->when(request('title') ?? request('search'), function ($query, $searchTerm) {
                $query->where(function ($subQuery) use ($searchTerm) {
                    $subQuery->where('title_ar', 'like', "%{$searchTerm}%")->orWhere('title_en', 'like', "%{$searchTerm}%");
                });
            })
            ->when(! request('category_id'), function ($query) {
                return $query->where(function ($query) {
                    $query->whereNull('parent_id')->orWhere('parent_id', 0);
                });
            })

            ->orderBy('arrangement')
            ->withCount('children')
            ->get();

        return ResponseHelper::make(CategoryResource::collection($Models));
    }
}
