<?php

namespace App\Services;

use App\Models\Academico\Horario;
use Illuminate\Database\Eloquent\Builder;
use Carbon\Carbon;

class SearchHorario
{
    public function buscarHorarios(?string $search, ?string $hora): Builder
    {
        $query = Horario::query();

        if ($hora) {
            $horaCarbon = Carbon::parse($hora);

            $query->where(function ($query) use ($horaCarbon) {
                $query->where(function ($subQuery) use ($horaCarbon) {
                    $subQuery->whereRaw("TIME_TO_SEC(?) >= TIME_TO_SEC(hora_entrada)", [$horaCarbon->toTimeString()])
                        ->whereRaw("TIME_TO_SEC(?) <= TIME_TO_SEC(ADDTIME(hora_entrada, '00:50:00'))", [$horaCarbon->toTimeString()]);
                });
            });
        }

        if ($search) {
            $query->where('nombre', 'like', "%$search%");
        }

        return $query;
    }
}
