<?php

namespace App\Services\Project;

use App\Http\Messages\ErrorMessages;
use Illuminate\Support\Facades\DB;
use App\Repositories\Project\ProjectRepositoryInterface;

class ProjectService
{
    protected $projectRepository;

    public function __construct(ProjectRepositoryInterface $projectRepository){
        $this->projectRepository = $projectRepository;
    }

    public function getAllProject(){
        return $this->projectRepository->all();
    }

    public function createProject($data){
        return DB::transaction(function () use ($data) {
            return $this->projectRepository->create($data)->refresh();
        });
    }

    public function updateProject($id, $data){
        return DB::transaction(function () use ($id, $data) {
             $this->projectRepository->update($id, $data);
             return $this->projectRepository->find($id);
        });
    }

    private function isProjectExists($projectId){
        return $this->projectRepository->find($projectId)
            ?? throw new \Exception(ErrorMessages::PROJECT_NOT_FOUND, 404);
    }

    public function getProjectbyId($id){
        return $this->isProjectExists($id);
    }

    public function getAllProjectpagination($datos){
        $query = $this->projectRepository->allquery();

        if ($datos->filled('search')) {
            $searchTerm = $datos->query('search');
            $query->where(function ($query) use ($searchTerm) {
                $query->where('title', 'like', '%' . $searchTerm . '%');
            });
        }

        if ($datos->query('sortBy') && $datos->query('orderBy')) {
            $sortBy = $datos->query('sortBy');
            $orderBy = $datos->query('orderBy');
            $query->orderBy($sortBy, $orderBy);
        }

        $itemsPerPage = $datos->query('itemsPerPage',10) ;
        $page = $datos->query('page',1);
        return  $query->paginate($itemsPerPage, ['*'], 'page', $page);
    }
}

