<?php

namespace App\Services;

use App\Models\PivoteHorarioCarreraEstudiante;
use Illuminate\Database\Eloquent\Builder;

class SearchHorarioCarreraEstudiante
{
    protected $searchHorario;
    protected $searchCarrera;
    protected $searchPersona;

    public function __construct(SearchHorario $searchHorario, SearchCarrera $searchCarrera, SearchPersona $searchPersona)
    {
        $this->searchHorario = $searchHorario;
        $this->searchCarrera = $searchCarrera;
        $this->searchPersona = $searchPersona;
    }

    public function buscarCarreraHorarioDocente(?string $search, ?int $ciclo): Builder
    {
        $query = PivoteHorarioCarreraEstudiante::query();

        if (!is_null($ciclo)) {
            // Filtra por ciclo si está definido
            $query->whereHas('pivote_horario.ciclo', function ($q) use ($ciclo) {
                $q->where('id_ciclo', $ciclo);
            });
        }

        if (!empty($search)) {

            $horarioQuery = $this->searchHorario->buscarHorarios($search, "");
            $carreraQuery = $this->searchCarrera->buscarCarreras($search);
            $personaQuery = $this->searchPersona->buscarPersonas($search);

            $query->where(function ($q) use ($horarioQuery, $carreraQuery, $personaQuery) {
                $q->whereHas('pivote_horario.horario', function ($subQuery) use ($horarioQuery) {
                    $subQuery->whereIn('id', $horarioQuery->pluck('id'));
                })
                    ->orWhereIn('id_carrera', $carreraQuery->pluck('id'))
                    ->orWhereHas('estudiante.persona', function ($personaQueryBuilder) use ($personaQuery) {
                        $personaQueryBuilder->whereIn('id', $personaQuery->pluck('id'));
                    });
            });
        }

        return $query->with(['estudiante.persona']);
    }
}
