<?php

namespace App\Exports;

use App\Models\Classe;
use App\Models\LevelPrimaryMatters;
use App\Models\EvaluatedLevel;
use Maatwebsite\Excel\Concerns\FromCollection;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;
use Illuminate\Support\Facades\DB;

class CompositionStudentNoteExport implements FromView
{
    protected $classe;
    protected $matter;
    public function __construct($classe, $matter)
    {
        $this->classe = $classe;
        $this->matter = $matter;
    }


    /**
    * @return \Illuminate\Support\Collection
    */
    public function view(): View
    {
        $class = Classe::where('id', $this->classe)->first();
        $evaluated = EvaluatedLevel::where('id', $this->matter)->first();
        $matters = LevelPrimaryMatters::where('level_id', $class['level_id'])->get();
        
        return view('exports.export_note_primaire', [
            'evaluated' => $evaluated,
            'classe' => $class,
            'matters' => $matters,
            'datas' => $this->getNoteEvaluated($class['id'],$class['school_year_id'])
        ]);
        
    }


    protected function getNoteEvaluated($class, $yearId)
    {
        $student = $this->getStudentClasse($class, $yearId);
        $tabs = [];
        foreach($student as $item){
            $tabs[] = [
                'id' => $item->id,
                'name' => strtoupper($item->first_name).' '.ucwords($item->last_name),
                'sexe' => strtoupper($item->sexe),
                'matricule' => $item->matricule,
            ];
        }
        return $tabs;
    }


    protected function getStudentClasse($id, $yearId)
    {
        $data = DB::table('students')
        ->join('inscriptions', 'students.id', '=', 'inscriptions.student_id')
        ->select('inscriptions.id', 'students.first_name', 'students.last_name', 'students.matricule', 'students.sexe', 'inscriptions.redoublant')
        ->where('inscriptions.classe_id', '=', $id)
        ->where('inscriptions.school_year_id', '=', $yearId)
        ->orderBy('students.first_name')->orderBy('students.last_name')
        ->get();
        return $data;
    }
}
