<?php

namespace App\Http\Controllers;

use App\Models\Curso;
use App\Models\Edificio;
use App\Models\GrupoAcademico;
use App\Models\HorarioGrupo;
use App\Models\MateriaPlan;
use App\Models\PeriodoEscolar;
use App\Models\Salon;
use App\Models\User;
use App\Support\InstitutionalContext;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;

class CampusOperationsController extends Controller
{
    public function index(InstitutionalContext $context)
    {
        $sedeId = $context->sedeId();
        $edificios = Edificio::with('salones')->where('sede_id', $sedeId)->orderBy('nombre')->get();
        $salones = Salon::with('edificio')
            ->where('activo', true)
            ->whereHas('edificio', fn ($query) => $query->where('sede_id', $sedeId))
            ->orderBy('edificio_id')->orderBy('clave')->get();
        $periodos = PeriodoEscolar::where('sede_id', $sedeId)->orderByDesc('fecha_inicio')->get();
        $materias = MateriaPlan::whereHas('plan.programa', fn ($query) => $query->where('sede_id', $sedeId))
            ->with('plan.programa')->orderBy('nombre')->get();
        $grupos = GrupoAcademico::with(['materia.plan.programa', 'periodo', 'docentes.persona', 'horarios.salon.edificio', 'cursoLms'])
            ->whereHas('periodo', fn ($query) => $query->where('sede_id', $sedeId))
            ->latest()->get();
        $docentes = User::with('persona')
            ->whereHas('roles', fn ($query) => $query->where('roles.slug', 'DOCENTE')->where('membership_role.sede_id', $sedeId))
            ->whereHas('sedes', fn ($query) => $query->where('sedes.id', $sedeId)->where('sede_user.estatus', 'ACTIVO'))
            ->orderBy('email')->get();
        $cursosLms = Curso::where('sede_id', $sedeId)->orderBy('nombre')->get();
        $cargaDocente = DB::table('grupo_docente')
            ->join('users', 'users.id', '=', 'grupo_docente.docente_id')
            ->join('personas', 'personas.id', '=', 'users.persona_id')
            ->join('grupos_academicos', 'grupos_academicos.id', '=', 'grupo_docente.grupo_id')
            ->join('periodos_escolares', 'periodos_escolares.id', '=', 'grupos_academicos.periodo_escolar_id')
            ->where('periodos_escolares.sede_id', $sedeId)
            ->groupBy('users.id', 'personas.nombre_completo')
            ->selectRaw('users.id, personas.nombre_completo, SUM(grupo_docente.horas_asignadas) as horas, COUNT(DISTINCT grupo_docente.grupo_id) as grupos')
            ->orderBy('personas.nombre_completo')->get();

        return view('admin.universidad.operacion', compact(
            'edificios', 'salones', 'periodos', 'materias', 'grupos', 'docentes', 'cursosLms', 'cargaDocente'
        ));
    }

    public function storeBuilding(Request $request, InstitutionalContext $context)
    {
        $data = $request->validate([
            'clave' => ['required', 'string', 'max:20', Rule::unique('edificios')->where('sede_id', $context->sedeId())],
            'nombre' => ['required', 'string', 'max:255'],
            'ubicacion' => ['nullable', 'string', 'max:255'],
        ]);
        Edificio::create($data + ['sede_id' => $context->sedeId()]);

        return back()->with('success', 'Edificio registrado.');
    }

    public function storeRoom(Request $request, InstitutionalContext $context)
    {
        $data = $request->validate([
            'edificio_id' => ['required', 'integer', 'exists:edificios,id'],
            'clave' => ['required', 'string', 'max:20'],
            'nombre' => ['nullable', 'string', 'max:255'],
            'capacidad' => ['required', 'integer', 'min:1', 'max:1000'],
            'tipo' => ['required', Rule::in(['AULA', 'LABORATORIO', 'TALLER', 'AUDITORIO', 'CENTRO_COMPUTO', 'VIRTUAL'])],
        ]);
        abort_unless(Edificio::whereKey($data['edificio_id'])->where('sede_id', $context->sedeId())->exists(), 404);
        validator($data, ['clave' => Rule::unique('salones')->where('edificio_id', $data['edificio_id'])])->validate();
        Salon::create($data);

        return back()->with('success', 'Espacio académico registrado.');
    }

    public function storeGroup(Request $request, InstitutionalContext $context)
    {
        $data = $request->validate([
            'materia_id' => ['required', 'integer', 'exists:materias_plan,id'],
            'periodo_escolar_id' => ['required', 'integer', 'exists:periodos_escolares,id'],
            'curso_lms_id' => ['nullable', 'integer', 'exists:cursos,id'],
            'clave' => ['required', 'string', 'max:30'],
            'cupo' => ['required', 'integer', 'min:1', 'max:500'],
            'turno' => ['nullable', Rule::in(['MATUTINO', 'VESPERTINO', 'MIXTO'])],
        ]);
        $sedeId = $context->sedeId();
        abort_unless(PeriodoEscolar::whereKey($data['periodo_escolar_id'])->where('sede_id', $sedeId)->exists(), 404);
        abort_unless(MateriaPlan::whereKey($data['materia_id'])->whereHas('plan.programa', fn ($q) => $q->where('sede_id', $sedeId))->exists(), 404);
        abort_if(filled($data['curso_lms_id'] ?? null) && ! Curso::whereKey($data['curso_lms_id'])->where('sede_id', $sedeId)->exists(), 404);
        validator($data, ['clave' => Rule::unique('grupos_academicos')->where('periodo_escolar_id', $data['periodo_escolar_id'])])->validate();
        GrupoAcademico::create($data + ['estatus' => 'PROGRAMADO']);

        return back()->with('success', 'Grupo académico abierto.');
    }

    public function updateGroup(Request $request, GrupoAcademico $grupo, InstitutionalContext $context)
    {
        $this->assertGroupCampus($grupo, $context);
        $data = $request->validate([
            'estatus' => ['required', Rule::in(['PROGRAMADO', 'ABIERTO', 'CERRADO', 'CANCELADO'])],
            'cupo' => ['required', 'integer', 'min:1', 'max:500'],
            'curso_lms_id' => ['nullable', 'integer', 'exists:cursos,id'],
        ]);
        abort_if(filled($data['curso_lms_id'] ?? null) && ! Curso::whereKey($data['curso_lms_id'])->where('sede_id', $context->sedeId())->exists(), 404);
        $grupo->update($data);

        return back()->with('success', 'Operación del grupo actualizada.');
    }

    public function assignTeacher(Request $request, GrupoAcademico $grupo, InstitutionalContext $context)
    {
        $this->assertGroupCampus($grupo, $context);
        $data = $request->validate([
            'docente_id' => ['required', 'integer', 'exists:users,id'],
            'funcion' => ['required', Rule::in(['TITULAR', 'AUXILIAR', 'SUPLENTE'])],
            'horas_asignadas' => ['required', 'integer', 'min:1', 'max:80'],
        ]);
        $teacher = User::findOrFail($data['docente_id']);
        abort_unless($teacher->tieneRolEnSede('DOCENTE', $context->sedeId()), 422, 'La persona no es docente activo de esta sede.');
        $this->assertTeacherScheduleAvailable($grupo, $teacher);
        $grupo->docentes()->syncWithoutDetaching([$teacher->id => [
            'funcion' => $data['funcion'],
            'horas_asignadas' => $data['horas_asignadas'],
            'created_at' => now(),
            'updated_at' => now(),
        ]]);

        return back()->with('success', 'Carga docente asignada.');
    }

    public function storeSchedule(Request $request, GrupoAcademico $grupo, InstitutionalContext $context)
    {
        $this->assertGroupCampus($grupo, $context);
        $data = $request->validate([
            'salon_id' => ['required', 'integer', 'exists:salones,id'],
            'dia_semana' => ['required', 'integer', 'between:1,7'],
            'hora_inicio' => ['required', 'date_format:H:i'],
            'hora_fin' => ['required', 'date_format:H:i', 'after:hora_inicio'],
        ]);
        $room = Salon::whereKey($data['salon_id'])
            ->whereHas('edificio', fn ($query) => $query->where('sede_id', $context->sedeId()))
            ->firstOrFail();
        throw_if($room->capacidad < $grupo->cupo, ValidationException::withMessages([
            'salon_id' => "El salón admite {$room->capacidad} personas y el grupo tiene cupo de {$grupo->cupo}.",
        ]));
        $overlap = fn ($query) => $query
            ->where('dia_semana', $data['dia_semana'])
            ->where('hora_inicio', '<', $data['hora_fin'])
            ->where('hora_fin', '>', $data['hora_inicio']);
        throw_if(HorarioGrupo::where('salon_id', $room->id)->whereHas('grupo', fn ($q) => $q->where('periodo_escolar_id', $grupo->periodo_escolar_id))->where($overlap)->exists(), ValidationException::withMessages([
            'hora_inicio' => 'El salón ya está ocupado en ese horario.',
        ]));
        foreach ($grupo->docentes as $teacher) {
            throw_unless($this->isWithinLaborAvailability($teacher, $context->sedeId(), (int) $data['dia_semana'], $data['hora_inicio'], $data['hora_fin']), ValidationException::withMessages([
                'hora_inicio' => "El horario está fuera de la disponibilidad laboral de {$teacher->name}.",
            ]));
            $conflict = HorarioGrupo::whereHas('grupo', fn ($q) => $q
                ->where('periodo_escolar_id', $grupo->periodo_escolar_id)
                ->whereHas('docentes', fn ($teachers) => $teachers->whereKey($teacher->id)))
                ->where($overlap)->exists();
            throw_if($conflict, ValidationException::withMessages([
                'hora_inicio' => "El docente {$teacher->name} ya tiene otro grupo en ese horario.",
            ]));
        }
        $grupo->horarios()->create($data);

        return back()->with('success', 'Horario agregado al calendario semanal.');
    }

    private function assertTeacherScheduleAvailable(GrupoAcademico $group, User $teacher): void
    {
        foreach ($group->horarios as $schedule) {
            $campusId = (int) $group->periodo->sede_id;
            throw_unless($this->isWithinLaborAvailability($teacher, $campusId, (int) $schedule->dia_semana, $schedule->hora_inicio, $schedule->hora_fin), ValidationException::withMessages([
                'docente_id' => 'El grupo está fuera de la disponibilidad laboral registrada para el docente.',
            ]));
            $conflict = HorarioGrupo::whereHas('grupo', fn ($query) => $query
                ->where('periodo_escolar_id', $group->periodo_escolar_id)
                ->whereHas('docentes', fn ($teachers) => $teachers->whereKey($teacher->id)))
                ->where('dia_semana', $schedule->dia_semana)
                ->where('hora_inicio', '<', $schedule->hora_fin)
                ->where('hora_fin', '>', $schedule->hora_inicio)
                ->exists();
            throw_if($conflict, ValidationException::withMessages([
                'docente_id' => 'El docente ya tiene una asignación que coincide con el horario del grupo.',
            ]));
        }
    }

    private function isWithinLaborAvailability(User $teacher, int $campusId, int $day, string $start, string $end): bool
    {
        $recordId = DB::table('expedientes_laborales')->where('user_id', $teacher->id)->where('sede_id', $campusId)->where('estatus', 'ACTIVO')->value('id');
        if (! $recordId || ! DB::table('disponibilidad_laboral')->where('expediente_id', $recordId)->exists()) {
            return true;
        }

        return DB::table('disponibilidad_laboral')->where('expediente_id', $recordId)->where('dia_semana', $day)->where('hora_inicio', '<=', $start)->where('hora_fin', '>=', $end)->exists();
    }

    private function assertGroupCampus(GrupoAcademico $group, InstitutionalContext $context): void
    {
        abort_unless($group->periodo()->where('sede_id', $context->sedeId())->exists(), 404);
    }
}
