<?php

namespace Modules\Company\Services;

use Mcamara\LaravelLocalization\Facades\LaravelLocalization;
use Modules\Company\Interfaces\CompanyRepositoryInterface;
use Modules\Company\Models\Company;
use Modules\MainService\Views\ViewFactory;
use Modules\User\Enums\UserRoleEnum;

class CompanyService
{
    public function __construct(
        private CompanyRepositoryInterface $companyRepository,
        private ViewFactory $viewFactory
    ){}

    public function renderView($request = [])
    {
        $request['companies'] = $this->get($request);
        return $this->render($request);
    }

    public function render($request = [])
    {
        return $this->viewFactory
            ->render($request['view'])
            ->renderView($request);
    }

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

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

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

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

        if (@$request['sector_ids'])
        {
            $builder->whereIn('companies.sector_id', $request['sector_ids']);
        }

        if(@$request['employeeFilter'])
        {
            if($request['employeeFilter']->role == UserRoleEnum::Head_Department->value)
            {
                $builder->where(function ($q) use ($request) {
                    $q->where('added_by', $request['employeeFilter']->id)
                    ->orWhereHas('added', function ($query) use ($request) {
                        $query->where('manager_id', $request['employeeFilter']->id);
                    });
                });
            }
            else
            {
                // $builder->where('added_by',$request['employeeFilter']->id);
            }
        }

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

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

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

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

        if (@$request['orderBy'])
        {
            if($request['orderBy']['key'] == 'sector')
            {
                $builder
                    ->join('sector_descriptions AS cd', 'companies.sector_id', 'cd.sector_id')
                    ->where('local', LaravelLocalization::getCurrentLocale())
                    ->addSelect('cd.title as sector_name')
                    ->orderBy('sector_name', $request['orderBy']['value']);
            }
            elseif($request['orderBy']['key'] == 'country')
            {
                $builder
                    ->join('country_descriptions AS cd', 'companies.country_id', 'cd.country_id')
                    ->where('local', LaravelLocalization::getCurrentLocale())
                    ->addSelect('cd.title as country_name')
                    ->orderBy('country_name', $request['orderBy']['value']);
            }
            else
            {
                $builder->orderBy($request['orderBy']['key'],$request['orderBy']['value']);
            }
        }
        else
        {
            $builder->orderBy('id','DESC');
        }

        if (@$request['paginate']) {
            $companies= $builder->paginate(50);
        }
        elseif (@$request['groupSector'])
        {
            $companies = $builder->get()->groupBy(function($item) {
                return $item->sector->currentDescription->title;
            });

        }
        else
        {
            $companies=$builder->get();
        }
        return $companies;
    }
    public function checkItem($id)
    {
        $company = $this->companyRepository->checkItem($id);
        return $company;
    }

    public function getItem($id)
    {
        $company = $this->companyRepository->getItem($id);

        return $company;
    }

    public function getCompanyDescription(array $request)
    {
        $builder = $this->companyRepository->getCompanyDescription($request);
        if (@$request['title'])
        {
            $builder->where('title', $request['title']);
        }
        if (@$request['region_id'])
        {
            $builder->whereHas('company', function($query) use ($request) {
                $query->where('region_id', $request['region_id']);
            });
        }
        if (@$request['not_company_id'])
        {
            $builder->where('company_id','!=', $request['not_company_id']);
        }
        return $builder->count();
    }

    public function getItemTrashed($id)
    {
        $company = $this->companyRepository->getItemTrashed($id);
        return $company;
    }

    public function create(array $request): Company
    {
        $company = $this->companyRepository->create($request);
        $this->companyRepository->saveData($request,$company->id);
        return $company;
    }
    public function update(array $request,int $id): Company
    {
        $company = $this->checkItem($id);
        $company = $this->companyRepository->update($request,$company);
        if(@$request['title_en'])
        {
            $this->companyRepository->saveData($request,$company->id);
        }
        return $company;
    }

    public function updateLock($id)
    {
        $company = $this->checkItem($id);
        $this->update(['lock'=>($company->lock?0:1)],$id);
    }

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