<?php 

namespace Modules\Reports\Controllers;

use Maatwebsite\Excel\Facades\Excel;
use Modules\Base\Controllers\Controller;
use Modules\Reports\Excel\ConsolidatedNotesExcel;
use Modules\Reports\Excel\RegistrationRecordExcel;
use Modules\Reports\Helpers\ModuloHelper;
use Illuminate\Http\Request;
use Modules\Reports\Helpers\AlumnoHelper;
use Modules\Reports\Helpers\EspecialidadHelper;
use Modules\Reports\Helpers\GrupoHelper;
use Modules\Reports\Helpers\InscripcionHelper;

class ReportConsolidadoNotasController extends Controller {

    public function config()
    {
        $listYear = GrupoHelper::getYears();
        $listEspecialidad = EspecialidadHelper::all();
        return $this->info([
            'listYear' => $listYear,
            'listEspecialidad' => $listEspecialidad
        ]);
    }

    public function reportConsolidatedNotes(Request $request)
    {   

        $specialtyId = $request->specialtyId;
        $year        = $request->year;

        $modules = ModuloHelper::bySpecialty($specialtyId);

        $modulesIds = $modules->pluck('id')->toArray();

        $groups = GrupoHelper::byModulesAndYear($modulesIds,(int)$year);

        $inscriptions = InscripcionHelper::byGroups($groups->pluck('id')->toArray());

        $alumsIds  = $inscriptions->unique('alumno_id')->pluck('alumno_id')->toArray();

        $studentsList = AlumnoHelper::getByIds($alumsIds);

        foreach ($studentsList as $student)
        {
            $myModules = collect();

            $student->fecha_inicio = $groups->min('fecha_inicio');

            $student->fecha_fin    = $groups->max('fecha_fin');

            foreach ($modules as  $module)
            {
                $inscription = null;

                $group = $groups->where('modulo_id',$module->id)->where('anio',$year)->first();

                if ($group)
                    $inscription = $inscriptions->where('alumno_id',$student->id)->where('grupo_id',$group->id)->first();

                $myModules->push((Object)[
                    'id' => $module->id,
                    'name' => $module->nombre,
                    'inscription' => $inscription,
                    'group'       => $group,
                    
                ]);
            }
            
            $student->modules = $myModules;
        }

        //return dd($studentsList);

        return Excel::download(new ConsolidatedNotesExcel($studentsList,$modules), 'consolidado_notas.xlsx');
    }

    public function reportRegistrationRecord()
    {
        return Excel::download(new RegistrationRecordExcel(), 'registro_matriculas.xlsx');
    }

}
