<?php

namespace App\Http\Controllers;

use App\Models\AnneeEtude;
use App\Models\CodeQrEtablis;
use App\Models\Config;
use App\Models\Domaine;
use App\Models\ElementC;
use App\Models\Enseignant;
use App\Models\EtablissementInfo;
use App\Models\Filieres;
use App\Models\Mention;
use App\Models\NiveauFormation;
use App\Models\TransitUEEnseign;
use App\Models\UnitesE;
use App\Models\Universite;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;
use PDF;

class FicheDeNotesController extends Controller
{
    public function ficheEc()
    {
        $data = [
            'formations' => NiveauFormation::all(),
            'etudes' => AnneeEtude::all(),
            'filieres' => Filieres::all()
        ];

        return view('fiche.ficheEc', compact("data"));
    }

    public function tabFicheEc(Request $request)
    {
        $data = $request->except(['_token']);

        //Check des reprises
        $acadr1 = $request->acadYear - 1;
        $acadr2 = $request->acadYear - 2;
        $periodeR = $acadr2 . '-' . $acadr1;

        $data['etudeYear'] = $request->etudeYear;
        $data['anneeAcadR'] = $acadr1;
        $data['periodeR'] = $periodeR;

        $periode = Session::get('RESULTAT_DATA')['RESULTAT_YEAR']->periode;

        $filiere = Filieres::where('idFiliere', $request->idFiliere)->first();
        $data['titre'] = $filiere->sigleFilieres . ' ' . $request->etudeYear . ' & Année académique : ' . $periode;

        //Génération des pdfs
        $etablissement = EtablissementInfo::first();
        $chemin = config('pdffiche.path') . '/' . $etablissement->idEtablissement . '/';

        if (!is_dir(public_path($chemin))) {
            mkdir(public_path($chemin), 0777, true);
        }

        //Récupération des anciens fichiers
        $files = glob($chemin . '*');
        foreach ($files as $file) {
            $lastModifiedTime = filemtime(public_path($file));
            $currentTime = time();
            $timeDiff = abs($currentTime - $lastModifiedTime) / (60); //in mn
            if (is_file(public_path($file)) && $timeDiff >= 20) //check if file is modified before 20mn
                unlink(public_path($file));
        }

        //Université
        $universite = Universite::where('idUniversite', $etablissement->idUniversite)->first();

        //Code Qr Details
        $qrCodeEta = CodeQrEtablis::select('codeQrEtablis')->where([
            ['idEtablissement', $etablissement->idEtablissement],
            ['idFiliere', $request->idFiliere],
            ['annee_acad', $request->acadYear],
            ['annee', $request->etudeYear]
        ])->first();

        //Requête des consantes de délibération
        $tabDelib = Config::where('annee_acad', $request->acadYear)->first();

        if ($request->ue == 0) {
            $allUEs = UnitesE::where([
                ['idFiliere', $request->idFiliere],
                ['annee_acad', $request->acadYear],
                ['annee', $request->etudeYear],
                ['niveauFormation', $request->formation]
            ])->get();
        } else {
            $allUEs = UnitesE::where([
                ['idFiliere', $request->idFiliere],
                ['annee_acad', $request->acadYear],
                ['annee', $request->etudeYear],
                ['niveauFormation', $request->formation],
                ['idUE', $request->ue]
            ])->get();
        }

        if ($request->formation == 1) {
            $diplome = "Licence";
        } else if ($request->formation  == 2) {
            $diplome = "Master";
        } else {
            $diplome = "Doctorat";
        }

        $resultatMention = Mention::selectRaw('idDomaine, sigleMention')->where('idMention', $filiere->idMention)->first();
        $resultatDomaine = Domaine::select('sigleDomaine')->where('idDomaine', $resultatMention->idDomaine)->first();

        $allFiches = [];
        $allFichesName = [];
        $allFichesUE = [];
        $countEcu = 0;
        //Génération du PDF
        foreach ($allUEs as $UE) {

            if ($UE->type_ue == 1 || $UE->type_ue == 2) {
                $noteValidation = $tabDelib->note;   // Note requise par ecu spécialité/méthodologie
            } else {
                $noteValidation = $tabDelib->note2;   // Note requise par ecu Culture Générale/Connaissances Fondamentales
            }

            $semestre = $UE->semestre;

            //Les ECU
            $ecus = ElementC::where([
                ['idFiliere', $request->idFiliere],
                ['annee_acad', $request->acadYear],
                ['annee', $request->etudeYear],
                ['niveauFormation', $request->formation],
                ['code_unite', $UE->code_unite]
            ])->get();

            $nbrEcus = $ecus->count();
            $i = 0;

            foreach ($ecus as $ecu) {
                $i++;
                $countEcu++;
                //Enseignant
                $enseignant = Enseignant::where('matricule', $ecu->matricule)->first();

                $dateValidation = '0001-01-01 00:00:00';

                if (!$request->session) { //Session normale
                    $session = 'Session Normale';

                    $studentValid = DB::connection('tenant')
                        ->table('tabinscriunite')
                        ->where([
                            ['idFiliere', $request->idFiliere],
                            ['annee', $request->etudeYear],
                            ['niveauFormation', $request->formation],
                            ['code_unite', $ecu->code_unite],
                            ['premiere_inscription', $request->acadYear]
                        ])
                        ->select('matricule')
                        ->get();
                    $matricules = array();
                    foreach ($studentValid as $matricule) {
                        array_push($matricules, $matricule->matricule);
                    }

                    $students = DB::connection('tenant')
                        ->table('tabetudiant')
                        ->join('tabinscription', 'tabetudiant.matricule', '=', 'tabinscription.matricule')
                        ->where('tabinscription.annee_acad', $request->acadYear) //Etudiant inscrit dans la filiere
                        ->where('tabinscription.dateValidation', '!=', '0001-01-01 00:00:00') //Validé l'inscription
                        ->whereIn('tabetudiant.matricule', $matricules)
                        ->orderBy('nom')
                        ->orderBy('prenom')
                        ->get();
                } else {
                    $session = 'Session de Rattrapage';

                    $studentValid = DB::connection('tenant')
                        ->table('tabinscriunite')
                        ->where([
                            ['idFiliere', $request->idFiliere],
                            ['annee', $request->etudeYear],
                            ['niveauFormation', $request->formation],
                            ['code_unite', $ecu->code_unite],
                            ['premiere_inscription', $request->acadYear],
                            ['resultat', 'R']
                        ])
                        ->select('matricule')
                        ->get();
                    $matricules = array();
                    foreach ($studentValid as $matricule) {
                        array_push($matricules, $matricule->matricule);
                    }

                    $students = DB::connection('tenant')
                        ->table('tabetudiant')
                        ->selectRaw('tabetudiant.matricule as matricule,
                        tabinscription.annee as annee, tabinscription.niveauFormation as niveauFormation,
                        tabinscription.annee_acad as annee_acad, nom, prenom, sexe')
                        ->join('tabinscription', 'tabetudiant.matricule', '=', 'tabinscription.matricule')
                        ->where('tabinscription.annee_acad', $request->acadYear) //Etudiant inscrit dans la filiere
                        ->where('tabinscription.dateValidation', '!=', '0001-01-01 00:00:00') //Validé l'inscription
                        ->whereIn('tabetudiant.matricule', $matricules)
                        ->orderBy('nom')
                        ->orderBy('prenom')
                        ->get();
                }

                $pdf =  PDF::loadView(
                    'pdf.fiche-ec1',
                    [
                        'universite' => $universite,
                        'etablissement' => $etablissement,
                        'enseignant' => $enseignant,
                        'UE' => $UE,
                        'session' => $session,
                        'typeSession' => $request->session,
                        'qrCodeEta' => $qrCodeEta,
                        'resultatDomaine' => $resultatDomaine,
                        'resultatMention' => $resultatMention,
                        'filiere' => $filiere,
                        'diplome' => $diplome,
                        'periode' => $periode,
                        'semestre' => $semestre,
                        'nbrEcus' => $nbrEcus,
                        'i' => $i,
                        'ecu' => $ecu,
                        'students' => $students,
                        'noteValidation' => $noteValidation,
                        'line' => $request->line,
                        'titre' => 'Fiche de note ' . $UE->intituleUnite
                    ]
                );

                $filename = 'fiche-' . mt_rand() . '_' . $countEcu;
                $allFiches[$countEcu] = $chemin . $filename;
                $allFichesName[$countEcu] = $ecu->intituleEcu;
                $allFichesUE[$countEcu] = $UE->intituleUnite;

                $data['allFiches'] = $allFiches;
                $data['allFichesName'] = $allFichesName;
                $data['allFichesUE'] = $allFichesUE;

                $options = [
                    'orientation' => $request->orientation,
                    'page-size' => $request->format,
                    'margin-left' => '15mm',
                    'margin-bottom' => '25mm',
                    'margin-top' => '15mm',
                    'margin-right' => '15mm',
                    'footer-left' => 'Paraphe de l' . '\'enseignant..............',
                    'footer-font-size' => 9,
                    'footer-center' => 'https://geststudent.net/',
                    'footer-right' => 'Page [page] / [toPage]'
                ];
                $pdf->setOptions($options);

                $pdf->save(public_path($allFiches[$countEcu] . '.pdf'));
                //Storage::disk('s3')->put($allFiches[$countEcu] . '.pdf',  file_get_contents($allFiches[$countEcu] . '.pdf'));
            }
        }

        //Zone de définition des sessions:
        Session::put('RESULTAT_REPRISE_EC', [
            'data' => $request->except(['_token']),
            'chemin' => $chemin,
            'universite' => $universite,
            'etablissement' => $etablissement,
            'qrCodeEta' => $qrCodeEta,
            'resultatDomaine' => $resultatDomaine,
            'resultatMention' => $resultatMention,
            'filiere' => $filiere,
            'diplome' => $diplome,
            'titre' => 'Fiche de note ' . $UE->intituleUnite
        ]);

        return view('fiche.tabFicheEc', compact('data'));
    }

    public function tabFicheEc2(Request $request)
    {
        $data = [];
        $periode = ($request->r - 1) . '-' . $request->r;

        $req = Session::get('RESULTAT_REPRISE_EC');

        $chemin = config('pdffiche.path') . '/' . $req['etablissement']->idEtablissement . '/';
        //Récupération des anciens fichiers
        $files = glob($chemin . '*');
        foreach ($files as $file) {
            $lastModifiedTime = filemtime(public_path($file));
            $currentTime = time();
            $timeDiff = abs($currentTime - $lastModifiedTime) / (60); //in mn
            if (
                is_file(public_path($file)) && $timeDiff >= 20
            ) //check if file is modified before 20mn
                unlink(public_path($file));
        }

        if ($req['data']['ue'] == 0) {
            $allUEs = UnitesE::where([
                ['idFiliere', $req['data']['idFiliere']],
                ['annee_acad', $request->r],
                ['annee', $request->a],
                ['niveauFormation', $req['data']['formation']]
            ])->get();
        } else {
            //Code Unité de l'UE
            $code_unite = UnitesE::where('idUE', $req['data']['ue'])->first()->code_unite;
            $allUEs = UnitesE::where([
                ['idFiliere', $req['data']['idFiliere']],
                ['annee_acad', $request->r],
                ['annee', $request->a],
                ['niveauFormation', $req['data']['formation']],
                ['code_unite', $code_unite]
            ])->get();
        }

        foreach ($allUEs as $UE) {
            //Enseignant
            $transitUnites = TransitUEEnseign::where([
                ['niveauFormation', $req['data']['formation']],
                ['code_unite', $UE->code_unite],
                ['idFiliere', $req['data']['idFiliere']],
                ['annee_acad', $request->r],
                ['annee', $request->a],
            ])->first();

            $enseignant = Enseignant::where('matricule', $transitUnites->matricule)->first();

            //Semestre
            $semestre = $UE->semestre;

            //Les ECU
            $ecus = ElementC::where([
                ['idFiliere', $req['data']['idFiliere']],
                ['annee_acad', $request->r],
                ['annee', $request->a],
                ['niveauFormation', $req['data']['formation']],
                ['code_unite', $UE->code_unite]
            ])->get();

            $nbrEcus = $ecus->count();
            $i = 0;
            $k = 0;
            foreach ($ecus as $ecu) {
                $i++;
                $k++;
                $session = 'Session de Reprise';

                $studentValid = DB::connection('tenant')
                    ->table('tabinscriunite')
                    ->where([
                        ['idFiliere', $req['data']['idFiliere']],
                        ['annee', $request->a],
                        ['niveauFormation', $req['data']['formation']],
                        ['code_unite', $ecu->code_unite],
                        ['premiere_inscription', $request->r],
                        ['resultat', 'R']
                    ])
                    ->select('matricule')
                    ->get();
                $matricules = array();
                foreach ($studentValid as $matricule) {
                    array_push($matricules, $matricule->matricule);
                }

                $students = DB::connection('tenant')
                    ->table('tabetudiant')
                    ->join('tabinscription', 'tabetudiant.matricule', '=', 'tabinscription.matricule')
                    ->where('tabinscription.annee_acad', $request->r) //Etudiant inscrit dans la filiere
                    ->where('tabinscription.dateValidation', '!=', '0001-01-01 00:00:00') //Validé l'inscription
                    ->whereIn('tabetudiant.matricule', $matricules)
                    ->orderBy('nom')
                    ->orderBy('prenom')
                    ->get();

                $pdf =  PDF::loadView(
                    'pdf.fiche-ec2',
                    [
                        'universite' => $req['universite'],
                        'etablissement' => $req['etablissement'],
                        'enseignant' => $enseignant,
                        'UE' => $UE,
                        'session' => $session,
                        'qrCodeEta' => $req['qrCodeEta'],
                        'resultatDomaine' => $req['resultatDomaine'],
                        'resultatMention' => $req['resultatMention'],
                        'filiere' => $req['filiere'],
                        'diplome' => $req['diplome'],
                        'periode' => $periode,
                        'semestre' => $semestre,
                        'nbrEcus' => $nbrEcus,
                        'i' => $i,
                        'ecu' => $ecu,
                        'students' => $students,
                        'line' => $req['data']['line'],
                        'titre' => 'Fiche de note ' . $UE->intituleUnite
                    ]
                );

                $filename = 'fiche-' . mt_rand() . '_' . $k;
                $allFiches[$k] = $filename;
                $allFichesSave[$k] = $req['chemin'] . $filename;
                $allFichesName[$k] = $ecu->intituleEcu;
                $allFichesUE[$k] = $UE->intituleUnite;

                $data['allFiches'] = $allFiches;
                $data['allFichesName'] = $allFichesName;
                $data['allFichesUE'] = $allFichesUE;

                $options = [
                    'orientation' => $req['data']['orientation'],
                    'page-size' => $req['data']['format'],
                    'margin-left' => '15mm',
                    'margin-bottom' => '25mm',
                    'margin-top' => '15mm',
                    'margin-right' => '15mm',
                    'footer-left' => 'Paraphe de l' . '\'enseignant..............',
                    'footer-font-size' => 9,
                    'footer-center' => 'https://geststudent.net/',
                    'footer-right' => 'Page [page] / [toPage]'
                ];
                $pdf->setOptions($options);

                $pdf->save(public_path($allFichesSave[$k] . '.pdf'));
            }
        }
        $data['titre'] = $req['filiere']->sigleFilieres . ' ' . $request->a . ' & Année académique : ' . $periode;
        $data['id'] = $req['etablissement']->idEtablissement;
        // Session::forget('RESULTAT_REPRISE_EC');
        return view('fiche.tabFicheEc2', compact('data'));
    }

    public function showFiche(Request $request)
    {
        if (EtablissementInfo::first()->idEtablissement == $request->id) {
            return response()->file(public_path('pdffiche/' . $request->id . '/' . $request->slug . '.pdf'));
        } else
            return route('404-not-found');
    }

    public function showFicheUE(Request $request)
    {
        try {
            if (EtablissementInfo::first()->idEtablissement == $request->id) {
                return response()->file(public_path('pdffiche/' . $request->id . '/' . $request->slug . '.pdf'));
            } else
                return route('404-not-found');
        } catch (Exception $e) {
            return route('404-not-found');
        }
    }

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

    public function tabFicheUe(Request $request)
    {
        $data = $request->except(['_token']);

        //Check des reprises
        $acadr1 = $request->acadYear - 1;
        $acadr2 = $request->acadYear - 2;
        $periodeR = $acadr2 . '-' . $acadr1;

        $data['etudeYear'] = $request->etudeYear;
        $data['anneeAcadR'] = $acadr1;
        $data['periodeR'] = $periodeR;

        $periode = Session::get('RESULTAT_DATA')['RESULTAT_YEAR']->periode;

        $filiere = Filieres::where('idFiliere', $request->idFiliere)->first();
        $data['titre'] = $filiere->sigleFilieres . ' ' . $request->etudeYear . ' & Année académique : ' . $periode;

        //Génération des pdfs
        $etablissement = EtablissementInfo::first();
        $chemin = config('pdffiche.path') . '/' . $etablissement->idEtablissement . '/';

        if (!is_dir(public_path($chemin))) {
            mkdir(public_path($chemin), 0777, true);
        }

        //Récupération des anciens fichiers
        $files = glob($chemin . '*');
        foreach ($files as $file) {
            $lastModifiedTime = filemtime(public_path($file));
            $currentTime = time();
            $timeDiff = abs($currentTime - $lastModifiedTime) / (60); //in mn
            if (is_file(public_path($file)) && $timeDiff >= 20) //check if file is modified before 20mn
                unlink(public_path($file));
        }

        //Université
        $universite = Universite::where('idUniversite', $etablissement->idUniversite)->first();

        //Code Qr Details
        $qrCodeEta = CodeQrEtablis::select('codeQrEtablis')->where([
            ['idEtablissement', $etablissement->idEtablissement],
            ['idFiliere', $request->idFiliere],
            ['annee_acad', $request->acadYear],
            ['annee', $request->etudeYear]
        ])->first();

        if ($request->ue == 0) {
            $allUEs = UnitesE::where([
                ['idFiliere', $request->idFiliere],
                ['annee_acad', $request->acadYear],
                ['annee', $request->etudeYear],
                ['niveauFormation', $request->formation]
            ])->get();
        } else {
            $allUEs = UnitesE::where([
                ['idFiliere', $request->idFiliere],
                ['annee_acad', $request->acadYear],
                ['annee', $request->etudeYear],
                ['niveauFormation', $request->formation],
                ['idUE', $request->ue]
            ])->get();
        }

        if ($request->formation == 1) {
            $diplome = "Licence";
        } else if ($request->formation  == 2) {
            $diplome = "Master";
        } else {
            $diplome = "Doctorat";
        }

        $resultatMention = Mention::selectRaw('idDomaine, sigleMention')->where('idMention', $filiere->idMention)->first();
        $resultatDomaine = Domaine::select('sigleDomaine')->where('idDomaine', $resultatMention->idDomaine)->first();

        $allFiches = [];
        $allFichesUE = [];
        $k = 0;
        //Génération du PDF
        foreach ($allUEs as $UE) {
            $k++;
            $semestre = $UE->semestre;

            //Les ECU
            $ecus = ElementC::where([
                ['idFiliere', $request->idFiliere],
                ['annee_acad', $request->acadYear],
                ['annee', $request->etudeYear],
                ['niveauFormation', $request->formation],
                ['code_unite', $UE->code_unite]
            ])->get();

            $nbrEcus = $ecus->count();

            //Enseignant
            $transitUnites = TransitUEEnseign::where([
                ['niveauFormation', $request->formation],
                ['code_unite', $UE->code_unite],
                ['idFiliere', $request->idFiliere],
                ['annee_acad', $request->acadYear],
                ['annee', $request->etudeYear],
            ])->first();

            $enseignant = Enseignant::where('matricule', $transitUnites->matricule)->first();

            if (!$request->session) { //Session normale
                $session = 'Session Normale';

                $studentValid = DB::connection('tenant')
                    ->table('tabinscriunite')
                    ->where([
                        ['idFiliere', $request->idFiliere],
                        ['annee', $request->etudeYear],
                        ['niveauFormation', $request->formation],
                        ['code_unite', $UE->code_unite],
                        ['premiere_inscription', $request->acadYear]
                    ])
                    ->select('matricule')
                    ->get();
                $matricules = array();
                foreach ($studentValid as $matricule) {
                    array_push($matricules, $matricule->matricule);
                }

                $students = DB::connection('tenant')
                    ->table('tabetudiant')
                    ->join('tabinscription', 'tabetudiant.matricule', '=', 'tabinscription.matricule')
                    ->where('tabinscription.annee_acad', $request->acadYear) //Etudiant inscrit dans la filiere
                    ->where('tabinscription.dateValidation', '!=', '0001-01-01 00:00:00') //Validé l'inscription
                    ->whereIn('tabetudiant.matricule', $matricules)
                    ->orderBy('nom')
                    ->orderBy('prenom')
                    ->get();
            } else {
                $session = 'Session de Rattrapage';

                $studentValid = DB::connection('tenant')
                    ->table('tabinscriunite')
                    ->where([
                        ['idFiliere', $request->idFiliere],
                        ['annee', $request->etudeYear],
                        ['niveauFormation', $request->formation],
                        ['code_unite', $UE->code_unite],
                        ['premiere_inscription', $request->acadYear],
                        ['resultat', 'R']
                    ])
                    ->select('matricule')
                    ->get();
                $matricules = array();
                foreach ($studentValid as $matricule) {
                    array_push($matricules, $matricule->matricule);
                }

                $students = DB::connection('tenant')
                    ->table('tabetudiant')
                    ->selectRaw('tabetudiant.matricule as matricule,
                        tabinscription.annee as annee, tabinscription.niveauFormation as niveauFormation,
                        tabinscription.annee_acad as annee_acad, nom, prenom, sexe')
                    ->join('tabinscription', 'tabetudiant.matricule', '=', 'tabinscription.matricule')
                    ->where('tabinscription.annee_acad', $request->acadYear) //Etudiant inscrit dans la filiere
                    ->where('tabinscription.dateValidation', '!=', '0001-01-01 00:00:00') //Validé l'inscription
                    ->whereIn('tabetudiant.matricule', $matricules)
                    ->orderBy('nom')
                    ->orderBy('prenom')
                    ->get();
            }

            $percent = 35 / $nbrEcus;
            $p = 7;
            $p2 = 30;
            if ($nbrEcus == 1) {
                $p = 12;
                $percent = 11;
                $p2 = 44;
            } else if ($nbrEcus == 2) {
                $p = 11;
                $percent = 11;
                $p2 = 35;
            } else if ($nbrEcus == 3) {
                $p = 9;
                $percent = 9;
                $p2 = 34;
            } else if ($nbrEcus == 4) {
                $p = 8;
                $percent = 8;
                $p2 = 31;
            }

            $td = '';
            $td2 = '';
            $tr = '';
            foreach ($ecus as $ecu) {
                $td .= '<th  align = "center"  width="' . $percent . '%"><b>' . $ecu->code_ecu . '</b></th>';
                $td2 .= '<td  align = "center" width="' . $percent . '%"></td>';
                $tr .= '<tr>
                        <td width="12%" align = "center">' . $ecu->code_ecu . '</td>

                        <td width="50%">' . $ecu->intituleEcu . '</td>
                    </tr>';
            }

            $pdf =  PDF::loadView(
                'pdf.fiche-ue1',
                [
                    'universite' => $universite,
                    'etablissement' => $etablissement,
                    'enseignant' => $enseignant,
                    'UE' => $UE,
                    'session' => $session,
                    'typeSession' => $request->session,
                    'qrCodeEta' => $qrCodeEta,
                    'resultatDomaine' => $resultatDomaine,
                    'resultatMention' => $resultatMention,
                    'filiere' => $filiere,
                    'diplome' => $diplome,
                    'periode' => $periode,
                    'semestre' => $semestre,
                    'nbrEcus' => $nbrEcus,
                    'students' => $students,
                    'line' => $request->line,
                    'titre' => 'Fiche de note ' . $UE->intituleUnite,
                    'tr' => $tr,
                    'td' => $td,
                    'td2' => $td2,
                    'p' => $p,
                    'p2' => $p2
                ]
            );

            $filename = 'fiche_ue-' . mt_rand() . '_' . $k;
            $allFiches[$k] = $chemin . $filename;
            $allFichesUE[$k] = $UE->intituleUnite;

            $data['allFiches'] = $allFiches;
            $data['allFichesUE'] = $allFichesUE;

            $options = [
                'orientation' => $request->orientation,
                'page-size' => $request->format,
                'margin-left' => '15mm',
                'margin-bottom' => '25mm',
                'margin-top' => '15mm',
                'margin-right' => '15mm',
                'footer-left' => 'Paraphe de l' . '\'enseignant..............',
                'footer-font-size' => 9,
                'footer-center' => 'https://geststudent.net/',
                'footer-right' => 'Page [page] / [toPage]'
            ];
            $pdf->setOptions($options);

            $pdf->save(public_path($allFiches[$k] . '.pdf'));
        }

        //Zone de définition des sessions:
        Session::put('RESULTAT_REPRISE_UE', [
            'data' => $request->except(['_token']),
            'chemin' => $chemin,
            'universite' => $universite,
            'etablissement' => $etablissement,
            'qrCodeEta' => $qrCodeEta,
            'resultatDomaine' => $resultatDomaine,
            'resultatMention' => $resultatMention,
            'filiere' => $filiere,
            'diplome' => $diplome,
            'titre' => 'Fiche de note ' . $UE->intituleUnite
        ]);

        return view('fiche.tabFicheUe', compact('data'));
    }

    public function tabFicheUe2(Request $request)
    {
        $data = [];
        $periode = ($request->r - 1) . '-' . $request->r;

        $req = Session::get('RESULTAT_REPRISE_UE');

        $chemin = config('pdffiche.path') . '/' . $req['etablissement']->idEtablissement . '/';
        //Récupération des anciens fichiers
        $files = glob($chemin . '*');
        foreach ($files as $file) {
            $lastModifiedTime = filemtime(public_path($file));
            $currentTime = time();
            $timeDiff = abs($currentTime - $lastModifiedTime) / (60); //in mn
            if (
                is_file(public_path($file)) && $timeDiff >= 20
            ) //check if file is modified before 20mn
                unlink(public_path($file));
        }


        if ($req['data']['ue'] == 0) {
            $allUEs = UnitesE::where([
                ['idFiliere', $req['data']['idFiliere']],
                ['annee_acad', $request->r],
                ['annee', $request->a],
                ['niveauFormation', $req['data']['formation']]
            ])->get();
        } else {
            //Code Unité de l'UE
            $code_unite = UnitesE::where('idUE', $req['data']['ue'])->first()->code_unite;
            $allUEs = UnitesE::where([
                ['idFiliere', $req['data']['idFiliere']],
                ['annee_acad', $request->r],
                ['annee', $request->a],
                ['niveauFormation', $req['data']['formation']],
                ['code_unite', $code_unite]
            ])->get();
        }

        $k = 0;

        foreach ($allUEs as $UE) {
            $k++;
            //Enseignant
            $transitUnites = TransitUEEnseign::where([
                ['niveauFormation', $req['data']['formation']],
                ['code_unite', $UE->code_unite],
                ['idFiliere', $req['data']['idFiliere']],
                ['annee_acad', $request->r],
                ['annee', $request->a],
            ])->first();

            $enseignant = Enseignant::where('matricule', $transitUnites->matricule)->first();

            //Semestre
            $semestre = $UE->semestre;

            //Les ECU
            $ecus = ElementC::where([
                ['idFiliere', $req['data']['idFiliere']],
                ['annee_acad', $request->r],
                ['annee', $request->a],
                ['niveauFormation', $req['data']['formation']],
                ['code_unite', $UE->code_unite]
            ])->get();

            $nbrEcus = $ecus->count();

            $percent = 35 / $nbrEcus;
            $p = 7;
            $p2 = 30;
            if ($nbrEcus == 1) {
                $p = 12;
                $percent = 11;
                $p2 = 44;
            } else if ($nbrEcus == 2) {
                $p = 11;
                $percent = 11;
                $p2 = 35;
            } else if ($nbrEcus == 3) {
                $p = 9;
                $percent = 9;
                $p2 = 34;
            } else if ($nbrEcus == 4) {
                $p = 8;
                $percent = 8;
                $p2 = 31;
            }

            $studentValid = DB::connection('tenant')
                ->table('tabinscriunite')
                ->where([
                    ['idFiliere', $req['data']['idFiliere']],
                    ['annee', $request->a],
                    ['niveauFormation', $req['data']['formation']],
                    ['code_unite', $UE->code_unite],
                    ['premiere_inscription', $request->r],
                    ['resultat', 'R']
                ])
                ->select('matricule')
                ->get();
            $matricules = array();
            foreach ($studentValid as $matricule) {
                array_push($matricules, $matricule->matricule);
            }

            $students = DB::connection('tenant')
                ->table('tabetudiant')
                ->join('tabinscription', 'tabetudiant.matricule', '=', 'tabinscription.matricule')
                ->where('tabinscription.annee_acad', $request->r) //Etudiant inscrit dans la filiere
                ->where('tabinscription.dateValidation', '!=', '0001-01-01 00:00:00') //Validé l'inscription
                ->whereIn('tabetudiant.matricule', $matricules)
                ->orderBy('nom')
                ->orderBy('prenom')
                ->get();

            $td = '';
            $td2 = '';
            $tr = '';
            foreach ($ecus as $ecu) {
                $td .= '<th  align = "center"  width="' . $percent . '%"><b>' . $ecu->code_ecu . '</b></th>';
                $td2 .= '<td  align = "center" width="' . $percent . '%"></td>';
                $tr .= '<tr>
                        <td width="12%" align = "center">' . $ecu->code_ecu . '</td>

                        <td width="50%">' . $ecu->intituleEcu . '</td>
                    </tr>';
            }


            $session = 'Session de Reprise';

            $pdf =  PDF::loadView(
                'pdf.fiche-ue2',
                [
                    'universite' => $req['universite'],
                    'etablissement' => $req['etablissement'],
                    'enseignant' => $enseignant,
                    'UE' => $UE,
                    'session' => $session,
                    'qrCodeEta' => $req['qrCodeEta'],
                    'resultatDomaine' => $req['resultatDomaine'],
                    'resultatMention' => $req['resultatMention'],
                    'filiere' => $req['filiere'],
                    'diplome' => $req['diplome'],
                    'periode' => $periode,
                    'semestre' => $semestre,
                    'nbrEcus' => $nbrEcus,
                    'students' => $students,
                    'line' => $req['data']['line'],
                    'titre' => 'Fiche de note ' . $UE->intituleUnite,
                    'tr' => $tr,
                    'td' => $td,
                    'td2' => $td2,
                    'p' => $p,
                    'p2' => $p2
                ]
            );

            $filename = 'fiche-' . mt_rand() . '_' . $k;
            $allFiches[$k] = $filename;
            $allFichesSave[$k] = $req['chemin'] . $filename;
            $allFichesUE[$k] = $UE->intituleUnite;

            $data['allFiches'] = $allFiches;
            $data['allFichesUE'] = $allFichesUE;

            $options = [
                'orientation' => $req['data']['orientation'],
                'page-size' => $req['data']['format'],
                'margin-left' => '15mm',
                'margin-bottom' => '25mm',
                'margin-top' => '15mm',
                'margin-right' => '15mm',
                'footer-left' => 'Paraphe de l' . '\'enseignant..............',
                'footer-font-size' => 9,
                'footer-center' => 'https://geststudent.net/',
                'footer-right' => 'Page [page] / [toPage]'
            ];
            $pdf->setOptions($options);

            $pdf->save(public_path($allFichesSave[$k] . '.pdf'));
        }

        $data['titre'] = $req['filiere']->sigleFilieres . ' ' . $request->a . ' & Année académique : ' . $periode;
        $data['id'] = $req['etablissement']->idEtablissement;
        // Session::forget('RESULTAT_REPRISE_UE');
        return view('fiche.tabFicheUe2', compact('data'));
    }
}
