<?php

namespace App\Http\Controllers;

use App\Http\Helpers\AdditionalHelpers;
use App\Mail\ModifNoteMail;
use App\Mail\PreuveMail;
use App\Models\AnneeEtude;
use App\Models\Etablissement;
use App\Models\{Filieres, TabEtudiant, TabInscription, Montant};
use App\Models\NiveauFormation;
use App\Models\{ConfigPdf, EtablissementInfo, GestStudentR};
use App\Models\{UnitesE, ElementC, Config, NoteEcu, Statuts};
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Illuminate\Support\Facades\Mail;

class GenFichExcel
{

    //Définition de l'entête du tableau
    static function fichierExcel($sheet, $styleArray)
    {
        //Longueur de chaque colonne du tableau
        $sheet->getColumnDimension('A')->setWidth(4);
        $sheet->getColumnDimension('B')->setWidth(15);
        $sheet->getColumnDimension('C')->setWidth(20);
        $sheet->getColumnDimension('D')->setWidth(31);
        $sheet->getColumnDimension('E')->setWidth(18);
        $sheet->getColumnDimension('F')->setWidth(15);
        $sheet->getColumnDimension('G')->setWidth(6);
        $sheet->getColumnDimension('H')->setWidth(15);
        $sheet->getColumnDimension('I')->setWidth(5);
        $sheet->getColumnDimension('J')->setWidth(10);
        $sheet->getColumnDimension('K')->setWidth(13);
        $sheet->getColumnDimension('L')->setWidth(25);

        $sheet->getRowDimension('1')->setRowHeight(30);
        $sheet->getRowDimension('2')->setRowHeight(35);

        //Ecriture des titres d'entête
        $sheet->getStyle('A2')->applyFromArray($styleArray);
        $styleA1 = $sheet->getStyle('A2');
        $styleFont = $styleA1->getFont();
        $sheet->setCellValue('A' . 2, 'N°');

        $sheet->getStyle('B2')->applyFromArray($styleArray);
        $styleA1 = $sheet->getStyle('B2');
        $styleFont = $styleA1->getFont();
        $sheet->setCellValue('B' . 2, 'Matricule');

        $sheet->getStyle('C2')->applyFromArray($styleArray);
        $styleA1 = $sheet->getStyle('C2');
        $styleFont = $styleA1->getFont();
        $sheet->setCellValue('C' . 2, 'Nom');

        $sheet->getStyle('D2')->applyFromArray($styleArray);
        $styleA1 = $sheet->getStyle('D2');
        $styleFont = $styleA1->getFont();
        $sheet->setCellValue('D' . 2, 'Prénoms');
        // $sheet->getStyle('D2')->getAlignment()->setTextRotation(90);

        $sheet->getStyle('E2')->applyFromArray($styleArray);
        $styleA1 = $sheet->getStyle('E2');
        $styleFont = $styleA1->getFont();
        $sheet->setCellValue('E' . 2, 'Date de Naissance');
        // $sheet->getStyle('E2')->getAlignment()->setTextRotation(90);

        $sheet->getStyle('F2')->applyFromArray($styleArray);
        $styleA1 = $sheet->getStyle('F2');
        $styleFont = $styleA1->getFont();
        $sheet->setCellValue('F' . 2, 'Lieu de Naissance');
        // $sheet->getStyle('F2')->getAlignment()->setTextRotation(90);

        $sheet->getStyle('G2')->applyFromArray($styleArray);
        $styleA1 = $sheet->getStyle('G2');
        $styleFont = $styleA1->getFont();
        $sheet->setCellValue('G' . 2, 'Statut');

        $sheet->getStyle('H2')->applyFromArray($styleArray);
        $styleA1 = $sheet->getStyle('H2');
        $styleFont = $styleA1->getFont();
        $sheet->setCellValue('H' . 2, 'Filière');

        $sheet->getStyle('I2')->applyFromArray($styleArray);
        $styleA1 = $sheet->getStyle('I2');
        $styleFont = $styleA1->getFont();
        $sheet->setCellValue('I' . 2, 'Sexe');

        $sheet->getStyle('J2')->applyFromArray($styleArray);
        $styleA1 = $sheet->getStyle('J2');
        $styleFont = $styleA1->getFont();
        $sheet->setCellValue('J' . 2, 'Nationalité');

        $sheet->getStyle('K2')->applyFromArray($styleArray);
        $styleA1 = $sheet->getStyle('K2');
        $styleFont = $styleA1->getFont();
        $sheet->setCellValue('K' . 2, 'Niveau d\'étude');

        $sheet->getStyle('L2')->applyFromArray($styleArray);
        $styleA1 = $sheet->getStyle('L2');
        $styleFont = $styleA1->getFont();
        $sheet->setCellValue('L' . 2, 'Date de validation');

        //Définition de l'alignement du text
        $sheet->getStyle('A')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
        $sheet->getStyle('B')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
        $sheet->getStyle('C')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
        $sheet->getStyle('D')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
        $sheet->getStyle('E')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
        $sheet->getStyle('F')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
        $sheet->getStyle('G')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
        $sheet->getStyle('H')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
        $sheet->getStyle('I')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
        $sheet->getStyle('J')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
        $sheet->getStyle('K')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
        $sheet->getStyle('L')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
    }
};


class OperationsController extends Controller
{
    public function imprimerListe()
    {
        $studentsData = DB::connection('tenant')
            ->table('tabetudiant')
            ->selectRaw('tabetudiant.matricule,tabetudiant.nom,tabetudiant.prenom,
            tabetudiant.date_nais,tabetudiant.lieu_nais,tabetudiant.sexe,tabinscription.dateValidation,
            statuts.statut,filieres.sigleFilieres,tabetudiant.nationalite,
            tabinscription.annee, niveauformation.niveauFormation')
            ->join('tabinscription', 'tabetudiant.matricule', '=', 'tabinscription.matricule')
            ->join('statuts', 'tabinscription.statut', '=', 'statuts.idStatut')
            ->join('filieres', 'tabinscription.idFiliere', '=', 'filieres.idFiliere')
            ->join('niveauformation', 'tabinscription.niveauFormation', '=', 'niveauformation.id')
            ->where('tabinscription.annee_acad', Session::get('RESULTAT_DATA')['RESULTAT_YEAR']->annee_acad)
            ->orderBy('nom', 'asc')
            ->get();
        $data = [
            'studentsData' => $studentsData,
        ];

        return view('operations.imprimer', compact('data'));
    }

    public function exportExcel()
    {

        $user = DB::table('users')
            ->selectRaw(
                'users.matricule as matricule,
                namebase,
                geststudent_r.nom as nom,
                geststudent_r.prenom as prenom,
                users.email as email,
                users.phone as phone,
                geststudent_r.cheminPhoto as cheminPhoto,
                geststudent_r.idEtablissement as idEtablissement'
            )
            ->join('geststudent_r', 'users.matricule', '=', 'geststudent_r.matricule')
            ->join('etablissement', 'geststudent_r.idEtablissement', '=', 'etablissement.idEtablissement')
            ->where('username', session('RESULTAT_USERNAME'))
            ->first();

        $eta = Etablissement::where('idEtablissement', $user->idEtablissement)->first();

        //Création de la feuille de calcul
        $spreadsheet = new Spreadsheet();
        //Spécification des propriétés du document
        $spreadsheet->getProperties()
            ->setTitle('Liste des Etudiants')
            ->setSubject($eta->descreta)
            ->setDescription('Liste des Etudiants présents dans l\'établissement')
            ->setCreator($eta->sigle)
            ->setLastModifiedBy($eta->sigle);

        //On active la feuille
        $sheet = $spreadsheet->getActiveSheet();

        //Définition des styles qu'on aura à utiliser sur la feuille
        //Style de l'entête de la feuille
        $styleArray1 = [
            // FONT
            'font' => [
                'bold' => true,
                'italic' => true,
                'name' => "SimSun",
                'size' => 11
            ],

            // ALIGNMENT
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER
            ],

            // BORDER
            'borders' => [
                'top' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK
                ],
                'bottom' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK
                ],
                'left' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM
                ],
                'right' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN
                ]
            ],
            'fill' => [
                'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                'color' => ['argb' => 'FFF080FF']
            ]

        ];

        //Style de l'entête du tableau
        $styleArray2 = [
            // FONT
            'font' => [
                'bold' => true,
                'italic' => true,
                'shrinkToFit' => true,
                'name' => "Century Gothic",
                'size' => 9
            ],
            // ALIGNMENT
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER
            ],
            // BORDER
            'borders' => [
                'top' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN
                ],
                'bottom' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN
                ],
                'left' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN
                ],
                'right' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN
                ]
            ]
        ];

        //Style du contenu du tableau
        $styleArray3 = [
            // BORDER
            'borders' => [
                'top' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN
                ],
                'bottom' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN
                ],
                'left' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN
                ],
                'right' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN
                ]
            ]
        ];

        //Style des étudiants n'ayant pas valider l'inscription
        $styleArray4 = [
            // FONT
            'font' => [
                'italic' => true,
                'name' => "SimSun"
            ],

            'fill' => [
                'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                'color' => ['argb' => 'f90606']
            ]

        ];

        //L'entête de la feuille
        $sheet->mergeCells('A1:L1');
        $sheet->getRowDimension(1)->setRowHeight(20);
        $sheet->getStyle('A1:L1')->applyFromArray($styleArray1);
        $sheet->setCellValue('A1', 'École : ' . $eta->sigle . ' -   Année-Académique : ' . Session::get('RESULTAT_DATA')['RESULTAT_YEAR']->periode);
        $sheet->getStyle('A2:L2')->getAlignment()->setWrapText(true);

        //Création du tableau et et son entête
        GenFichExcel::fichierExcel($sheet, $styleArray2);

        //La liste des étudiants
        $etudiantInfos = DB::connection('tenant')
            ->table('tabetudiant')
            ->selectRaw('tabetudiant.matricule,tabetudiant.nom,tabetudiant.prenom,
            tabetudiant.date_nais,tabetudiant.lieu_nais,tabetudiant.sexe,tabinscription.dateValidation,
            statuts.statut,filieres.sigleFilieres,tabetudiant.nationalite,
            tabinscription.annee, niveauformation.niveauFormation')
            ->join('tabinscription', 'tabetudiant.matricule', '=', 'tabinscription.matricule')
            ->join('statuts', 'tabinscription.statut', '=', 'statuts.idStatut')
            ->join('filieres', 'tabinscription.idFiliere', '=', 'filieres.idFiliere')
            ->join('niveauformation', 'tabinscription.niveauFormation', '=', 'niveauformation.id')
            ->where('tabinscription.annee_acad', Session::get('RESULTAT_DATA')['RESULTAT_YEAR']->annee_acad)
            ->orderBy('nom', 'asc')
            ->get();

        //Le contenu du tableau
        $numero = 1;
        $iter = 3;
        foreach ($etudiantInfos as $etudiantInfo) {
            //ajout des données
            $sheet->setCellValue('A' . $iter, $numero);
            $sheet->setCellValue('B' . $iter, $etudiantInfo->matricule);
            $sheet->setCellValue('C' . $iter, $etudiantInfo->nom);
            $sheet->setCellValue('D' . $iter, $etudiantInfo->prenom);
            $sheet->setCellValue('E' . $iter, $etudiantInfo->date_nais);
            $sheet->setCellValue('F' . $iter, $etudiantInfo->lieu_nais);
            $sheet->setCellValue('G' . $iter, $etudiantInfo->statut);
            $sheet->setCellValue('H' . $iter, $etudiantInfo->sigleFilieres . '' . $etudiantInfo->annee);
            $sheet->setCellValue('I' . $iter, $etudiantInfo->sexe);
            $sheet->setCellValue('J' . $iter, $etudiantInfo->nationalite);
            $sheet->setCellValue('K' . $iter, $etudiantInfo->niveauFormation);
            $sheet->setCellValue('L' . $iter, $etudiantInfo->dateValidation);

            //application du style
            $sheet->getStyle('A' . $iter)->applyFromArray($styleArray3);
            $sheet->getStyle('B' . $iter)->applyFromArray($styleArray3);
            $sheet->getStyle('C' . $iter)->applyFromArray($styleArray3);
            $sheet->getStyle('D' . $iter)->applyFromArray($styleArray3);
            $sheet->getStyle('E' . $iter)->applyFromArray($styleArray3);
            $sheet->getStyle('F' . $iter)->applyFromArray($styleArray3);
            $sheet->getStyle('G' . $iter)->applyFromArray($styleArray3);
            $sheet->getStyle('H' . $iter)->applyFromArray($styleArray3);
            $sheet->getStyle('I' . $iter)->applyFromArray($styleArray3);
            $sheet->getStyle('J' . $iter)->applyFromArray($styleArray3);
            $sheet->getStyle('K' . $iter)->applyFromArray($styleArray3);
            $sheet->getStyle('L' . $iter)->applyFromArray($styleArray3);

            //Si l'étudiant n'a pas encore validé son inscription
            if ($etudiantInfo->dateValidation == "0001-01-01 00:00:00") {
                $sheet->getStyle('L' . $iter . ':L' . $iter)->applyFromArray($styleArray4);
            }

            $numero++;
            $iter++;
        }

        // Définir l'index de la feuille active sur la première feuille, afin qu'Excel l'ouvre en tant que première feuille
        $spreadsheet->setActiveSheetIndex(0);

        //Le nom du fichier à générer
        // $filename = 'ListeInscription.xlsx';

        // Rediriger la sortie vers le navigateur Web d'un client (Xlsx)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="ListeInscription.xlsx"');
        header('Cache-Control: max-age=0');

        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }



    public function bilanInsertion()
    {
        $data = [
            'etudes' => AnneeEtude::all(),
            'filieres' => Filieres::all(),
            'formations' => NiveauFormation::all(),
        ];

        return view('operations.bilan', compact('data'));
    }

    public function bilanInsertionListe(Request $request)
    {
        [
            "session" => $session,
            "idFiliere" => $idFiliere,
            "acadYear" => $acadYear,
            "formation" => $niveauFormation,
            "etudeYear" => $etudeYear
        ] = $request->all();

        $data = $request->except('_token');
        if ($etudeYear != "") {
            $annees = UnitesE::selectRaw('DISTINCT annee')->where(['idFiliere' => $idFiliere, 'annee' => $etudeYear, 'niveauFormation' => $niveauFormation, 'annee_acad' => $acadYear])->get();
        } else {
            $annees = UnitesE::selectRaw('DISTINCT annee')->where(['idFiliere' => $idFiliere, 'niveauFormation' => $niveauFormation, 'annee_acad' => $acadYear])
                ->orderBy('annee')->get();
        }
        $data["session"] = $session;
        $data['annees'] = $annees;
        $data['sigle'] = Filieres::where('idFiliere', $idFiliere)->first()->sigleFilieres;

        Session::put('RESULTATS_BILAN_INSERTION', [
            "data" => $data,
        ]);
        return view('operations.bilan-liste', compact('data'));
    }

    public function suppressionNotes()
    {
        $data = [
            'filieres' => Filieres::all(),
            'formations' => NiveauFormation::all(),
            'etudes' => AnneeEtude::all()
        ];
        return view('operations.suppression', compact('data'));
    }

    public function modificationNotes()
    {
        //Mode d'insertion des notes
        $mode = ConfigPdf::select("modeResultat")->first()->modeResultat;
        if ($mode != 'U') {
            $label = "Choisir un EC";
            $placeholder = "Choisir un Elément Constitutif...";
            $validation = "La matiere est requise...";
        } else {
            $label = "Choisir une UE";
            $placeholder = "Choisir une Unité d'enseignement...";
            $validation = "L'Unité d'Ensignement est requis...";
        }
        $data = [
            'formations' => NiveauFormation::all(),
            'etudes' => AnneeEtude::all(),
            'filieres' => Filieres::all(),
            'label' => $label,
            'placeholder' => $placeholder,
            'input_name' => ($mode != 'U') ? 'ec' : 'ue',
            'mode' => $mode,
            'validation' => $validation
        ];
        return view('operations.modification', compact('data'));
    }
    public function updateNote(Request $request)
    {
        try {
            $search  = array('À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'à', 'á', 'â', 'ã', 'ä', 'å', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ð', 'ò', 'ó', 'ô', 'õ', 'ö', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ');
            $replace = array('A', 'A', 'A', 'A', 'A', 'A', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 'a', 'a', 'a', 'a', 'a', 'a', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y');

            $idEtablissement = EtablissementInfo::first()->idEtablissement;
            $emailfrom = Etablissement::where('idEtablissement', $idEtablissement)->first()->email;
            $d  = getdate();

            $y  = $d["year"];
            $mo = str_pad($d["mon"], 2, '0', STR_PAD_LEFT);
            $wd = str_pad($d["mday"], 2, '0', STR_PAD_LEFT);

            $h = $d["hours"];
            $m = $d["minutes"];
            $s = $d["seconds"];

            date_default_timezone_set('Africa/Porto-Novo');
            // Récupère l'heure
            $localtime =  localtime();
            $seconde   =  str_pad($localtime[0], 2, '0', STR_PAD_LEFT);
            $minute    =  str_pad($localtime[1], 2, '0', STR_PAD_LEFT);
            $heure     =  str_pad($localtime[2], 2, '0', STR_PAD_LEFT);

            $date = "$y-$mo-$wd $heure:$minute:$seconde";
            $ip = $request->ip();
            $annee_acad = Session::get('RESULTAT_DATA')['RESULTAT_YEAR']->annee_acad;
            $tab = Config::where('annee_acad', $annee_acad)->first();
            $echelle = $tab->echelle;
            $p1       = $tab->poids_cc;
            $p2       = $tab->poids_examen;
            $note             = trim($request->value);
            $id             = $request->id;
            if ($request->column_name == 'noteUE') {
                $notes = NoteEcu::where('id', $id)->first();
                $noteEC     = $notes->noteEcu;
                $matric     = $notes->matricule;
                $annee      = $notes->annee;
                $niveau      = $notes->niveauFormation;
                $idFiliere     = $notes->idFiliere;
                $code_unite    = $notes->code_unite;
                $compteur     = $notes->compteur;
                $nb = count(NoteEcu::where('id', $id)->get()->all());
                $inscrit = Tabinscription::where([
                    'matricule' => $matric,
                    'annee_acad' => $annee_acad
                ])->first();
                $statutetud = $inscrit->statut;

                $resMontant = Montant::where('annee', $annee)
                    ->where('idFiliere', $idFiliere)
                    ->where('idStatut', $statutetud)
                    ->where('periode', $annee_acad)->first();

                $montant             = $resMontant->scolarite;
                $fraisInscription   = $resMontant->fraisInscription;
                $scolarite = $montant + $fraisInscription;
                try {
                    DB::connection('tenant')->table('noteEcu')->where([
                        ['code_unite', $code_unite],
                        ['annee_acad', $annee_acad],
                        ['idFiliere', $idFiliere],
                        ['annee', $annee],
                        ['matricule', $matric],
                        ['niveauFormation', $niveau]
                    ])->update(['noteEcu' => $note]);
                    $modif = 'YES';
                    //On garde les traces en cas de modification.
                    if ($noteEC != $note) {
                        $compteur     = $compteur + 1;
                        $mat = Session::get('RESULTAT_MATRICULE');
                        DB::connection('tenant')->table('noteEcu')->where([
                            ['code_unite', $code_unite],
                            ['annee_acad', $annee_acad],
                            ['idFiliere', $idFiliere],
                            ['annee', $annee],
                            ['matricule', $matric],
                            ['niveauFormation', $niveau]
                        ])->update([
                            'compteur' => $compteur,
                            'date_modif' => $date,
                            'auteur_modif' => $mat,
                            'modif' => $modif
                        ]);
                        $etudiant = TabEtudiant::where('matricule', $matric)->first();
                        $nome         = $etudiant->nom;
                        $prenome    = $etudiant->prenom;
                        $email      = $etudiant->email;
                        $emailp     = $etudiant->emailp;
                        $unite         = UnitesE::where([
                            ['code_unite', $code_unite],
                            ['idFiliere', $idFiliere],
                            ['annee', $annee],
                            ['annee_acad', $annee_acad],
                            ['niveauFormation', $niveau]
                        ])->first();
                        $nomUE = $unite->intituleUnite;
                        $filiere = Filieres::where('idFiliere', $idFiliere)->first();
                        $sigleFiliere = $filiere->sigleFilieres;
                        $operation  = 'Etudiant : ' . $nome . ' ' . $prenome . '. Modification de la note de : ' . $nomUE . '. Filière : ' . $sigleFiliere . ' Année : ' . $annee;
                        $operation .= '. Ancienne note : [' . $noteEC . '] en date du : ' . $date;
                        $operation .= '. Nouvelle note : [' . $note . '].';
                        if ($nb != 0) {
                            try {
                                DB::table('historique')->insert([
                                    'matricule' => $mat,
                                    'dateActivite' => $date,
                                    'operation' => $operation,
                                    'idEtablissement' => $idEtablissement,
                                    'adresseip' => $ip
                                ]);
                            } catch (Exception $e) {
                                return response()->json([
                                    'success' => false,
                                    'message' => $e->getMessage()
                                ]);
                            }
                        }
                        $auteur = GestStudentR::where('matricule', $mat)->first();
                        $nom_auteur     = $auteur->nom;
                        $prenom_auteur     = $auteur->prenom;
                        if ($nb != 0) {
                            if ($compteur >= 1) {
                                $expediteur   = 'info@geststudent.net'; // L'email de l'exp&eacute;diteur.
                                $message = 'Bonjour, ' . $compteur . ' eme modification de notes par : ' . $nom_auteur . ' ' . $prenom_auteur . '. <br /><br />' . $operation;
                                $sms = 'Bonjour, ' . $compteur . ' eme modification de notes par : ' . $nom_auteur . ' ' . $prenom_auteur . '. ' . $operation;
                                //$message    = str_replace('<br />', "\n", $message);// message trait&eacute; pour les sauts de ligne
                                $to         = 'preuve@geststudent.net'; // e-mail du destinataire
                                $subject   = 'Modification de notes de : ' . $nome . ' ' . $prenome;
                                $headers   = 'From: ' . $expediteur . "\r\n";   // en-tête de l'e-mail
                                // Mail::to($to)
                                //     ->queue(new ([
                                //         'from' => $expediteur,
                                //         'message' => $message,
                                //         'sujet' => $subject
                                //     ]));
                                //$retval = mail($to, $subject, $message, $headers);
                                //sendSms('22994172879', $sms, 'IITECH-BJ', $datetime = '');
                                //sendSms('22996896636', $message, 'IITECH-BJ', $datetime = '');
                            }
                        }
                        $sujet = "Modification de notes de : " . str_replace($search, $replace, $nomUE);
                        $sujetp = "Modification de notes de votre enfant pour : " . str_replace($search, $replace, $nomUE);
                        $mailheader = 'GestStudent';
                        $montantp = $inscrit->montant;
                        $soldedu = $scolarite - $montantp;
                        $percent = 0;
                        if ($scolarite != 0) {
                            $percent = ($montantp / $scolarite) * 100;
                        }
                        if ($email) {
                            Mail::to($email)
                                ->queue(new ModifNoteMail([
                                    'note' => $note,
                                    'nomUE' => $nomUE,
                                    'echelle' => $echelle,
                                    'sujet' => $sujet
                                ]));
                        } else if ($emailp) {
                            Mail::to($emailp)
                                ->queue(new ModifNoteMail([
                                    'note' => $note,
                                    'nomUE' => $nomUE,
                                    'echelle' => $echelle,
                                    'sujet' => $sujetp
                                ]));
                        }
                    }
                    if ($nb == 0) {
                        return response()->json([
                            'success' => false,
                            'message' => 'Impossible de mettre à jour cette note. Veuillez insérer la note de l\'étudiant concerné par session normale d\'abord...'
                        ]);
                    }
                } catch (Exception $e) {
                    return response()->json([
                        'success' => false,
                        'message' => $e->getMessage()
                    ]);
                }
            } else {
                try {
                    $notes = NoteEcu::where('id', $id)->first();
                    $noteCCA     = $notes->noteCC;
                    $noteEXA     = $notes->noteEX;
                    $noteECA     = $notes->noteEcu;
                    $compteur     = $notes->compteur;

                    $compteur     = $notes->compteur;
                    DB::connection('tenant')->table('noteEcu')->where('id', $id)->update([$request->column_name => $note]);
                    $noteN = NoteEcu::where('id', $id)->first();
                    $noteCC     = $noteN->noteCC;
                    $noteEX     = $noteN->noteEX;
                    $noteEC     = $noteN->noteEcu;
                    $matric     = $noteN->matricule;
                    $annee      = $noteN->annee;
                    $niveau      = $noteN->niveauFormation;
                    $idFiliere     = $noteN->idFiliere;
                    $code_unite    = $noteN->code_unite;
                    $code_ecu    = $noteN->code_ecu;
                    $nb = count(NoteEcu::where('id', $id)->get()->all());
                    $inscrit = Tabinscription::where([
                        'matricule' => $matric,
                        'annee_acad' => $annee_acad
                    ])->first();
                    $statutetud = $inscrit->statut;

                    $resMontant = Montant::where('annee', $annee)
                        ->where('idFiliere', $idFiliere)
                        ->where('idStatut', $statutetud)
                        ->where('periode', $annee_acad)->first();
                    $montant             = $resMontant->scolarite;
                    
                    $fraisInscription   = $resMontant->fraisInscription;
                    $scolarite = $montant + $fraisInscription;

                    $moy = AdditionalHelpers::moyenne($noteCC, $noteEX, $p1, $p2);
                    $moy = AdditionalHelpers::myround($moy, 2);
                    if ($request->column_name != 'noteEcu') {
                        DB::connection('tenant')->table('noteEcu')->where('id', $id)->update(['noteEcu' => $moy]);
                    }

                    $modif = 'YES';
                    //On garde les traces en cas de modification.
                    if ($noteEC != $moy) {
                        $compteur     = $compteur + 1;
                        $mat = Session::get('RESULTAT_MATRICULE');
                        DB::connection('tenant')->table('noteEcu')->where('id', $id)->update([
                            'compteur' => $compteur,
                            'date_modif' => $date,
                            'auteur_modif' => $mat,
                            'modif' => $modif
                        ]);
                        $etudiant = TabEtudiant::where('matricule', $matric)->first();
                        $nome         = $etudiant->nom;
                        $prenome    = $etudiant->prenom;
                        $email      = $etudiant->email;
                        $emailp     = $etudiant->emailp;

                        if ($request->column_name == 'noteEX') {
                            $anncienneNote = $noteEXA;
                        } else {
                            $anncienneNote = $noteCCA;
                        }
                        $nomEC = ElementC::where([
                            'idFiliere' => $idFiliere,
                            'code_unite' => $code_unite,
                            'code_ecu' => $code_ecu,
                            'annee_acad' => $annee_acad,
                            'niveauFormation' => $niveau,
                            'annee' => $annee
                        ])->first()->intituleEcu;

                        $unite         = UnitesE::where([
                            ['code_unite', $code_unite],
                            ['idFiliere', $idFiliere],
                            ['annee', $annee],
                            ['annee_acad', $annee_acad],
                            ['niveauFormation', $niveau]
                        ])->first();
                        $nomUE = $unite->intituleUnite;
                        $filiere = Filieres::where('idFiliere', $idFiliere)->first();
                        $sigleFiliere = $filiere->sigleFilieres;
                        $operation  = 'Etudiant : ' . $nome . ' ' . $prenome . '. Modification de la note de : ' . $nomEC . ' (' . $request->column_name . '). Filière : ' . $sigleFiliere . ' Année : ' . $annee;
                        $operation .= '. Ancienne note : [' . $anncienneNote . '] en date du : ' . $date;
                        $operation .= '. Nouvelle note : [' . $note . '].';
                        if ($nb != 0) {
                            try {
                                DB::table('historique')->insert([
                                    'matricule' => $mat,
                                    'dateActivite' => $date,
                                    'operation' => $operation,
                                    'idEtablissement' => $idEtablissement,
                                    'adresseip' => $ip
                                ]);
                            } catch (Exception $e) {
                                return response()->json([
                                    'success' => false,
                                    'message' => $e->getMessage()
                                ]);
                            }
                        }
                        $auteur = GestStudentR::where('matricule', $mat)->first();
                        $nom_auteur     = $auteur->nom;
                        $prenom_auteur     = $auteur->prenom;
                        if ($nb != 0) {
                            if ($compteur >= 1) {
                                $expediteur   = 'info@geststudent.net'; // L'email de l'exp&eacute;diteur.
                                $message = 'Bonjour, ' . $compteur . ' eme modification de notes par : ' . $nom_auteur . ' ' . $prenom_auteur . '. <br /><br />' . $operation;
                                $sms = 'Bonjour, ' . $compteur . ' eme modification de notes par : ' . $nom_auteur . ' ' . $prenom_auteur . '. ' . $operation;
                                //$message    = str_replace('<br />', "\n", $message);// message trait&eacute; pour les sauts de ligne
                                $to         = 'preuve@geststudent.net'; // e-mail du destinataire
                                $subject   = 'Modification de notes de : ' . $nome . ' ' . $prenome;
                                $headers   = 'From: ' . $expediteur . "\r\n";   // en-tête de l'e-mail
                                Mail::to($to)
                                    ->queue(new PreuveMail([
                                        'from' => $expediteur,
                                        'message' => $message,
                                        'sujet' => $subject
                                    ]));
                                //$retval = mail($to, $subject, $message, $headers);
                                //sendSms('22994172879', $sms, 'IITECH-BJ', $datetime = '');
                                //sendSms('22996896636', $message, 'IITECH-BJ', $datetime = '');
                            }
                        }
                    }
                    if ($nb == 0) {
                        return response()->json([
                            'success' => false,
                            'message' => 'Impossible de mettre à jour cette note. Veuillez insérer la note de l\'étudiant concerné par session normale d\'abord...'
                        ]);
                    } else {
                        $sujet = "Modification de notes de : " . str_replace($search, $replace, $nomUE);
                        $sujetp = "Modification de notes de votre enfant pour : " . str_replace($search, $replace, $nomUE);
                        $mailheader = 'GestStudent';
                        $montantp = $inscrit->montant;
                        $soldedu = $scolarite - $montantp;
                        $percent = 0;
                        if ($scolarite != 0) {
                            $percent = ($montantp / $scolarite) * 100;
                        }
                        if ($email) {
                            Mail::to($email)
                                ->queue(new ModifNoteMail([
                                    'note' => $note,
                                    'nomUE' => $nomUE,
                                    'echelle' => $echelle,
                                    'sujet' => $sujet
                                ]));
                        } else if ($emailp) {
                            Mail::to($emailp)
                                ->queue(new ModifNoteMail([
                                    'note' => $note,
                                    'nomUE' => $nomUE,
                                    'echelle' => $echelle,
                                    'sujet' => $sujetp
                                ]));
                        }
                    }
                } catch (Exception $e) {
                    return response()->json([
                        'success' => false,
                        'message' => $e->getMessage()
                    ]);
                }
            }

            return response()->json([
                'success' => true,
                'data' => [
                    'Resultats' => 'Enregistré avec succès'
                ],
                'message' => 'DONE'
            ]);
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ]);
        }
    }
    public function listModif(Request $request)
    {
        try {
            $request->validate([
                'acadYear' => 'bail|required',

                'etudeYear' => 'bail|required',
                'idFiliere' => 'bail|required',
                'formation' => 'bail|required'
            ]);

            $unite         = UnitesE::where([
                ['idUE', $request->ue],
                ['idFiliere', $request->idFiliere],
                ['annee', $request->etudeYear],
                ['annee_acad', $request->acadYear],
                ['niveauFormation', $request->formation]
            ])->first();
            $nomUE = $unite->intituleUnite;
            $code_unite = $unite->code_unite;


            $idFiliere  = $request->idFiliere;
            $annee         = $request->etudeYear;
            $annee_acad = $request->acadYear;
            $acad = $annee_acad - 1;
            $niveau     = $request->formation;

            $filiere = Filieres::where('idFiliere', $idFiliere)->first();
            $idEtablissement = EtablissementInfo::first()->idEtablissement;
            $echelle = Config::where([
                ['annee_acad', $annee_acad],
                ['idEtablissement', $idEtablissement]
            ])->first()->echelle;
            $mat = Session::get('RESULTAT_MATRICULE');

            $elements = ElementC::where([
                'idFiliere' => $idFiliere,
                'code_unite' => $code_unite,
                'annee_acad' => $annee_acad,
                'niveauFormation' => $niveau,
                'annee' => $annee
            ])->get()->all();
            $nombreEC = count($elements);
            $selection = '';
            $nombredentrees = '';
            $dateValidation = '0001-01-01 00:00:00';

            $selections = DB::connection('tenant')
                ->table('tabetudiant')
                ->select('*')
                ->join('tabinscription', 'tabetudiant.matricule', '=', 'tabinscription.matricule')
                ->where([
                    'tabinscription.annee_acad' => $annee_acad,
                    'annee_acad' => $annee_acad,
                    'niveauFormation' => $niveau,
                    'annee' => $annee,
                    'idFiliere' => $idFiliere
                ])->where('tabinscription.dateValidation', '!=', $dateValidation)
                ->get()->all();
            $nombredentrees = count($selections);
            $ETUDIANTS_PAR_PAGE = 25;
            $nombredepages = ceil($nombredentrees / $ETUDIANTS_PAR_PAGE);
            $operation = $request->operation;
            $notes = NoteEcu::where([
                'code_unite' => $code_unite,
                'annee_acad' => $annee_acad,
                'annee' => $annee,
                'niveauFormation' => $niveau,
                'idFiliere' => $idFiliere
            ])->get()->all();
            $statuts = Statuts::all();
            if ($nombredentrees == 0) {
                return back()->with('error', 'Aucun étudiant n\'est inscrit dans la filière :  ' . $filiere->intituleFilieres . ' ' . $annee . ' ou certainement tous les étudiants disposent déjà de notes dans cette matière.');
            } else {
                return view('operations.listModif', compact('nomUE', 'filiere', 'selections', 'elements', 'operation', 'annee', 'annee_acad', 'niveau', 'notes', 'code_unite', 'statuts'));
            }
        } catch (Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }
    public function suppression(Request $request)
    {
        try {
            $d  = getdate();
            $y  = $d["year"];
            $mo = $d["mon"];
            $wd = $d["mday"];

            $h = $d["hours"];
            $m = $d["minutes"];
            $s = $d["seconds"];
            $ip = $request->ip();
            date_default_timezone_set('Africa/Porto-Novo');
            // Récupère l'heure
            $localtime =  localtime();
            $seconde   =  $localtime[0];
            $minute    =  $localtime[1];
            $heure     =  $localtime[2];

            $date = "$y-$mo-$wd $heure:$minute:$seconde";
            $request->validate([
                'academique' => 'bail|required',
                'ec' => 'bail|required',
                'code_unite' => 'bail|required',
                'code_ec' => 'bail|required',
                'totale' => 'bail|required',
                'annee' => 'bail|required',
                'niveau' => 'bail|required',
                'sigle' => 'bail|required'
            ]);
            $code_ecu   = $request->code_ec;
            $code_unite = $request->code_unite;
            $idFiliere  = $request->idFiliere;
            $annee         = $request->annee;
            $annee_acad = $request->academique;
            $periode    = ($annee_acad - 1) . '-' . $annee_acad;
            $niveau     = $request->niveau;
            $sigle         = $request->sigle;
            $ec         = $request->ec;
            $operation  = 'Suppression de la note de : ' . $ec . '. Filière : ' . $sigle . ' Année : ' . $annee;

            try {
                DB::connection('tenant')->table('noteEcu')->where([
                    ['code_ecu', $code_ecu],
                    ['code_unite', $code_unite],
                    ['annee_acad', $annee_acad],
                    ['idFiliere', $idFiliere],
                    ['annee', $annee],
                    ['niveauFormation', $niveau]
                ])->delete();
                $mat =  Session::get('RESULTAT_MATRICULE');
                $idEtablissement = EtablissementInfo::first()->idEtablissement;
                DB::table('historique')->insert([
                    'matricule' => $mat,
                    'dateActivite' => $date,
                    'operation' => $operation,
                    'idEtablissement' => $idEtablissement,
                    'adresseip' => $ip
                ]);
            } catch (Exception $e) {
                return response()->json([
                    'success' => false,
                    'message' => $e->getMessage()
                ]);
            }
            try {
                DB::connection('tenant')->table('ecu')->where([
                    'idFiliere' => $idFiliere,
                    'code_ecu' => $code_ecu,
                    'code_unite' => $code_unite,
                    'annee_acad' => $annee_acad,
                    'niveauFormation' => $niveau,
                    'annee' => $annee
                ])->update(['insertion' => 'YES']);
            } catch (Exception $e) {
                return response()->json([
                    'success' => false,
                    'message' => $e->getMessage()
                ]);
            }
            $noteEcus2 = NoteEcu::where([
                'idFiliere' => $idFiliere,
                'code_unite' => $code_unite,
                'annee_acad' => $annee_acad,
                'niveauFormation' => $niveau,
                'annee' => $annee
            ])->get()->all();
            $nombre2 = count($noteEcus2);
            if ($nombre2 == 0) {
                try {
                    DB::connection('tenant')->table('unites')->where([
                        'idFiliere' => $idFiliere,
                        'code_unite' => $code_unite,
                        'annee_acad' => $annee_acad,
                        'niveauFormation' => $niveau,
                        'annee' => $annee
                    ])->update(['insertion' => 'YES']);
                } catch (Exception $e) {
                    return response()->json([
                        'success' => false,
                        'message' => $e->getMessage()
                    ]);
                }
            }
            return response()->json([
                'success' => true,
                'data' => [
                    'Resultats' => 'Supprimé avec succès'
                ],
                'message' => 'DONE'
            ]);
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ]);
        }
    }
    public function listSuppression(Request $request)
    {
        // try {
        $d  = getdate();
        $y  = $d["year"];
        $mo = $d["mon"];
        $wd = $d["mday"];

        $h = $d["hours"];
        $m = $d["minutes"];
        $s = $d["seconds"];
        $ip = $request->ip();
        date_default_timezone_set('Africa/Porto-Novo');
        // Récupère l'heure
        $localtime =  localtime();
        $seconde   =  $localtime[0];
        $minute    =  $localtime[1];
        $heure     =  $localtime[2];

        $date = "$y-$mo-$wd $heure:$minute:$seconde";
        $request->validate([
            'idFiliere' => 'bail|required',
            'ec' => 'bail|required',
            'etudeYear' => 'bail|required',
            'formation' => 'bail|required',
            'acadYear' => 'bail|required'
        ]);
        $element = ElementC::where('idEC', $request->ec)->first();
        $nomEC = $element->intituleEcu;
        $nomFichierExcel = explode('.', $request->file)[0];
        $code_ecu   = $element->code_ecu;
        $code_unite = $element->code_unite;
        $idFiliere  = $request->idFiliere;
        $annee         = $request->etudeYear;
        $annee_acad = $request->acadYear;
        $niveau     = $request->formation;
        $tab = Config::where('annee_acad', $annee_acad)->first();
        $echelle = $tab->echelle;
        $filiere = Filieres::where('idFiliere', $idFiliere)->first();
        $intituleFilieres = $filiere->intituleFilieres;
        $sigleFilieres = $filiere->sigleFilieres;
        if ($nomFichierExcel != '') {
            if (strcmp($nomEC, $nomFichierExcel) != 0) {
                return back()->with('error', 'Le nom de la matière : {' . $nomEC . '} ne correspond pas au nom choisi : {' . $nomFichierExcel . '}
                    dans le champ choisir un fichier. Le processus d\'insertion par fichier excel est donc suspendu. Veuillez recharger la page !');
            } else {
                $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($request->file);
                $sheet = $spreadsheet->getActiveSheet();
                $i = 3;
                $j = 0;
                foreach ($sheet->getRowIterator() as $row) {
                    $matricule = $sheet->getCell('A' . $i)->getValue();
                    $nom        = $sheet->getCell('B' . $i)->getValue();
                    $prenom       = $sheet->getCell('C' . $i)->getValue();
                    //Si matricule NULL sortir de la boucle
                    if ($matricule == "") {
                        if ($i == 3) {
                            return back()->with('error', 'Votre fichier excel semble etre vide. Verifier son contenu...');
                        }
                        break;
                    } else if (($nom == '') || ($prenom == '')) {
                        $etudiant = TabEtudiant::where('matricule', $matricule)->first();
                        $nom = $etudiant->nom;
                        $prenom = $etudiant->prenom;
                    }
                    $noteEcu = NoteEcu::where([
                        'idFiliere' => $idFiliere,
                        'matricule' => $matricule,
                        'code_ecu' => $code_ecu,
                        'code_unite' => $code_unite,
                        'annee_acad' => $annee_acad,
                        'niveauFormation' => $niveau,
                        'annee' => $annee
                    ])->first();
                    $anncienneNote    = $noteEcu->noteEcu;
                    $date_last         = $noteEcu->date_modif;
                    $operation  = 'Etudiant : ' . $nom . ' ' . $prenom . '. Suppression de la note de : ' . $nomEC . '. Filière : ' . $sigleFilieres . ' Année : ' . $annee;
                    $operation .= '. Ancienne note : [' . $anncienneNote . '] en date du : ' . $date_last;
                    try {
                        DB::connection('tenant')->table('noteEcu')->where([
                            ['code_ecu', $code_ecu],
                            ['code_unite', $code_unite],
                            ['annee_acad', $annee_acad],
                            ['idFiliere', $idFiliere],
                            ['annee', $annee],
                            ['niveauFormation', $niveau],
                            ['matricule', $matricule]
                        ])->delete();
                        $mat = Session::get('RESULTAT_MATRICULE');
                        $idEtablissement = EtablissementInfo::first()->idEtablissement;
                        DB::table('historique')->insert([
                            'matricule' => $mat,
                            'dateActivite' => $date,
                            'operation' => $operation,
                            'idEtablissement' => $idEtablissement,
                            'adresseip' => $ip
                        ]);
                    } catch (Exception $e) {
                        return  back()->with('error', $e->getMessage());
                    }
                    $i++;
                    $j++;
                }
                $noteEcus = NoteEcu::where([
                    'idFiliere' => $idFiliere,
                    'code_ecu' => $code_ecu,
                    'code_unite' => $code_unite,
                    'annee_acad' => $annee_acad,
                    'niveauFormation' => $niveau,
                    'annee' => $annee
                ])->get()->all();
                $nombre = count($noteEcus);
                if ($nombre == 0) {
                    try {
                        DB::connection('tenant')->table('ecu')->where([
                            'idFiliere' => $idFiliere,
                            'code_ecu' => $code_ecu,
                            'code_unite' => $code_unite,
                            'annee_acad' => $annee_acad,
                            'niveauFormation' => $niveau,
                            'annee' => $annee
                        ])->update(['insertion' => 'YES']);
                    } catch (Exception $e) {
                        return  back()->with('error', $e->getMessage());
                    }
                }
                $noteEcus2 = NoteEcu::where([
                    'idFiliere' => $idFiliere,
                    'code_unite' => $code_unite,
                    'annee_acad' => $annee_acad,
                    'niveauFormation' => $niveau,
                    'annee' => $annee
                ])->get()->all();
                $nombre2 = count($noteEcus2);
                if ($nombre2 == 0) {
                    try {
                        DB::connection('tenant')->table('unites')->where([
                            'idFiliere' => $idFiliere,
                            'code_unite' => $code_unite,
                            'annee_acad' => $annee_acad,
                            'niveauFormation' => $niveau,
                            'annee' => $annee
                        ])->update(['insertion' => 'YES']);
                    } catch (Exception $e) {
                        return  back()->with('error', $e->getMessage());
                    }
                }
            }
        } else {

            $etu = 15;
            $selections = TabEtudiant::join('tabinscription', 'tabinscription.matricule', '=', 'tabetudiant.matricule')->whereRaw('idFiliere=? AND annee=? AND niveauFormation=? AND tabinscription.annee_acad=? AND tabinscription.matricule
						IN (SELECT matricule FROM noteEcu WHERE idFiliere =? AND annee =? AND niveauFormation=? AND annee_acad =?
						AND code_unite =? AND code_ecu =?)', [$idFiliere, $annee, $niveau, $annee_acad, $idFiliere, $annee, $niveau, $annee_acad, $code_unite, $code_ecu])
                ->orderBy('nom', 'ASC')->orderBy('prenom', 'ASC')->get()->all();

            $nombredentrees = count($selections);
            $nombredepages = ceil($nombredentrees / $etu);
            $retourTotal = "";
            if ($nombredentrees == 0) {

                // return  back()->with('insert', "Aucun étudiant n'est inscrit dans la filière : " . $intituleFilieres . " " . $annee . "Suppression de notes pour : " . $nomEC . " impossible.");
                return  back()->with('insert', "Aucune note insérée pour pout cet élément constitutif : " . $intituleFilieres . " " . $annee . ". La suppression de notes pour : " . $nomEC . " est impossible.");

            } else {
                $notes = NoteEcu::where([
                    'idFiliere' => $idFiliere,
                    'code_ecu' => $code_ecu,
                    'code_unite' => $code_unite,
                    'annee_acad' => $annee_acad,
                    'niveauFormation' => $niveau,
                    'annee' => $annee
                ])->get()->all();
                $students = GestStudentR::all();
                return view('operations.listSuppression', compact('students', 'notes', 'selections', 'nomEC', 'filiere', 'code_ecu', 'code_unite', 'annee', 'annee_acad', 'niveau', 'echelle', 'etu', 'nombredepages'));
            }
        }
        // } catch (Exception $e) {
        //     return  back()->with('error',$e->getMessage());
        // }

    }
}
