<?php

namespace App\Services;

use App\Models\BusinessSubCategory;
use App\Models\BusinessSubCategoryChild;
use App\Models\User;
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

trait BusinessSubCategoryService
{
    /**
     * Store new record
     *
     * @param array $data
     * @return Builder|Model
     */
    public static function store(array $data): Model|Builder
    {
        return BusinessSubCategory::query()->create($data);
    }

    /**
     * Update existing record
     *
     * @param array $data
     * @return mixed
     */
    public function updateService(array $data): mixed
    {
        return tap($this)->update($data);
    }

    /**
     * FInd by id
     *
     * @param int $id
     * @return Builder|Builder[]|Collection|Model|null
     */
    public static function findById(int $id): Model|Collection|Builder|array|null
    {
        return BusinessSubCategory::query()->find($id);
    }

    /**
     * All business sub categories
     *
     * @return Collection|array
     */
    public static function getBusinessSubCategories(): Collection|array
    {
        return BusinessSubCategory::query()->get();
    }

    /**
     * Check Id exist
     *
     * @param array $idArray
     * @return Builder[]|Collection
     */
    public static function checkInterestExist(array $idArray): Collection|array
    {
        return BusinessSubCategory::query()->whereIn('id', $idArray)->pluck("id")->toArray();
    }


    /**
     * Get business subcategories by parent category
     *
     * @return Builder[]|Collection
     */
    public static function getByBusinessCategory(): Collection|array
    {
        /** @var User $user */
        $user = auth()->user();
        try {
            $businessCategoryId = $user->{"business"}->{"business_category_id"};
             $businessSubCategories = BusinessSubCategory::query()->where("business_category_id", $businessCategoryId)->get();

            $businessSubCategoriesArray = array();
            foreach ($businessSubCategories as $businessSubCategory) {
                $businessSubCategoriesArray[] = array(
                    "id" => $businessSubCategory->{"id"},
                    "designation" => $businessSubCategory->{"designation"},
                    "code" => $businessSubCategory->{"code"},
                    "description" => $businessSubCategory->{"description"},
                    "child_categories" => BusinessSubCategoryChild::getChildCategory($businessSubCategory->{"id"}),
                );
            }

            $result = $businessSubCategoriesArray;
        } catch (Exception $exception) {
            log_debug(exception: $exception, prefix: 'BusinessSubCategoryService::getByBusinessCategory');
            $result = null;
        }

        return  $result;
    }
}
