<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;

class EnsureAdminAuthenticated
{
    public function handle(Request $request, Closure $next): Response
    {
        if (! $request->session()->get('admin_auth', false)) {
            return redirect()->route('login');
        }

        $role = Str::lower((string) $request->session()->get('admin_role', ''));
        if (! $this->isAllowedForRequest($request, $role)) {
            abort(403, 'No tienes permisos para acceder a este modulo.');
        }

        return $next($request);
    }

    private function isAllowedForRequest(Request $request, string $role): bool
    {
        if (in_array($role, ['admin', 'superadmin'], true)) {
            return true;
        }

        $routeName = (string) ($request->route()?->getName() ?? '');
        $section = Str::lower((string) $request->route('section', ''));

        if ($routeName === 'admin.dashboard') {
            return in_array($role, ['coordinadores', 'secretarias', 'docentes'], true);
        }

        if ($routeName === 'admin.cartera.index') {
            return in_array($role, ['coordinadores', 'secretarias'], true);
        }

        if ($routeName === 'admin.notas.index') {
            return in_array($role, ['coordinadores', 'docentes'], true);
        }

        if (Str::startsWith($routeName, 'admin.general.') || Str::startsWith($routeName, 'admin.estudiantes.') || Str::startsWith($routeName, 'admin.profesores.')) {
            return in_array($role, ['coordinadores', 'secretarias'], true);
        }

        if (Str::startsWith($routeName, 'admin.academia.asignacion.')) {
            return in_array($role, ['coordinadores', 'docentes'], true);
        }

        if (Str::startsWith($routeName, 'admin.academia.')) {
            return in_array($role, ['coordinadores'], true);
        }

        if (Str::startsWith($routeName, 'admin.calificaciones.')) {
            return in_array($role, ['coordinadores', 'docentes'], true);
        }

        if (Str::startsWith($routeName, 'admin.observador.')) {
            return in_array($role, ['coordinadores', 'docentes', 'secretarias'], true);
        }

        if ($routeName === 'admin.section') {
            if (in_array($section, ['general', 'matriculas', 'mensajeria'], true)) {
                return in_array($role, ['coordinadores', 'secretarias'], true);
            }
            if (in_array($section, ['academia'], true)) {
                return in_array($role, ['coordinadores'], true);
            }
            if (in_array($section, ['calificaciones', 'observador'], true)) {
                return in_array($role, ['coordinadores', 'docentes', 'secretarias'], true);
            }
            if (in_array($section, ['cartera'], true)) {
                return in_array($role, ['coordinadores', 'secretarias'], true);
            }
            if (in_array($section, ['contabilidad'], true)) {
                return false;
            }
        }

        return false;
    }
}
