<?php

namespace Modules\Region\Services;

use Illuminate\Http\Request;
use Modules\Region\Interfaces\RegionRepositoryInterface;
use Modules\Region\Models\Region;

class RegionService
{
    private RegionRepositoryInterface $regionRepository ;

    public function __construct(RegionRepositoryInterface $regionRepository)
    {
        $this->regionRepository = $regionRepository;
    }

    public function get(array $request = [])
    {
        $builder = $this->regionRepository->get($request);

        if (@$request['title'])
        {
            $builder->where('sd.title', 'LIKE', '%'.$request['title'].'%');
        }

        if (@$request['country_id'])
        {
            $builder->where('regions.country_id', $request['country_id']);
        }

        if (@$request['date_from'])
        {
            $builder->whereDate('regions.created_at', '>=', $request['date_from']);
        }

        if (@$request['date_to'])
        {
            $builder->whereDate('regions.created_at', '<=', $request['date_to']);
        }

        if (isset($request['status']))
        {
            if (@$request['status'] == 0)
            {
                $builder->onlyTrashed();
            }
        }

        if (@$request['paginate']) {
            $regions= $builder->paginate(50);
        }else{
            $regions=$builder->get();
        }
        return $regions;
    }
    public function checkItem($id)
    {
        $region = $this->regionRepository->checkItem($id);
        return $region;
    }

    public function getItem($id)
    {
        $region = $this->regionRepository->getItem($id);

        return $region;
    }

    public function getItemTrashed($id)
    {
        $region = $this->regionRepository->getItemTrashed($id);
        return $region;
    }

    public function create(array $request): Region
    {
        $region = $this->regionRepository->create($request);
        $this->regionRepository->saveData($request,$region->id);
        return $region;
    }
    public function update(array $request,int $id): Region
    {
        $region = $this->checkItem($id);


        $region = $this->regionRepository->update($request,$region);
        $this->regionRepository->saveData($request,$region->id);
        return $region;
    }
    public function destroy(int $id): void
    {
        $region = $this->checkItem($id);
        if ($region)
        {
            $this->regionRepository->destroy($region);
        }
        else
        {
            $region = $this->getItemTrashed($id);
            $this->regionRepository->restore($region);
        }
    }
    public function destroyAll(array $request): void
    {
        if ($request['status'] == 1)
        {
            $this->regionRepository->destroyAll($request['ids']);
        }
        else
        {
            $this->regionRepository->restoreAll($request['ids']);
        }
    }
}
