<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Http\Requests\BdCheckRequest;
use App\Http\Requests\LoginAPIRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use \Carbon\Carbon;
use Exception;

class UserStudentController extends Controller
{
    public function login(LoginAPIRequest $request)
    {
        try {
            if ($this->checkUserStudent($request)) {
                // Authentication passed...

                //We generate a token
                $token = Str::random(80);

                $user_student = $this->checkUserStudent($request);

                return response()->json([
                    'success' =>  true,
                    'data' => [
                        'access_token' => $token,
                        'user_student_matricule' => $user_student->matricule,
                        'type_user' => $user_student->type_user,
                        'expires_at' => Carbon::now()->add(1, 'day')
                    ],
                    'message' => 'LOGIN_SUCCESSFULLY'
                ], 200);
            } else {
                return response()->json([
                    'success' =>  false,
                    'message' => 'UNAUTHORIZED'
                ], 401);
            }
        } catch (Exception $e) {
            return response()->json([
                'success' =>  false,
                'message' => $e->getMessage()
            ], 400);
        }
    }

    public function user_student_ues(BdCheckRequest $request, $matricule)
    {
        try {


            $user = DB::table('users_student')->where('matricule', $matricule)->first();
            if (isset($user)) {
                $tabinscriunites = DB::connection('tenant')->table('tabinscriunite')->where('matricule', $user->matricule)->get();
               // $use = DB::connection('tenant')->table('tabinscriunite')
                //->groupBy('noTicket')
                //->having(DB::raw('count(status)'), '<', 2)
                //->pluck('noTicket');
                $nor = DB::connection('tenant')->table('tabinscriunite')->where('matricule', $user->matricule)
                ->where('premiere_inscription','=', 'inscription_actuelle')->get()->pluck('code_unite')->toArray();

                $rep = DB::connection('tenant')->table('tabinscriunite')
                //->select('*')
               // ->where('matricule', $matricule)
                ->where('premiere_inscription', '=','inscription_actuelle')
               // ->select('code_unite')
               ->get();

                $info = DB::connection('tenant')->table('tabinscriunite')->where('matricule', $user->matricule)->get();

                //$userData = DB::connection('tenant')->table('tabinscriunite')->where(function($query) {
                //    $query->where('premiere_inscription', 'inscription_actuelle')
                 //       ->orWhere('premiere_inscription','<>', 'inscription_actuelle');
                //})
                //->where('matricule', $matricule)
                //->get();

                $results = array(
                    'normales' => [],
                    'reprises' => []
                );

                $i = 0;
                $j = 0;
                foreach ($tabinscriunites as $tiu) {
                    if ($tiu->premiere_inscription == $tiu->inscription_actuelle) {
                        $results['normales'][$i] = [
                            'ue' => DB::connection('tenant')->table('unites')->where('code_unite', $tiu->code_unite)->first(),
                            'ecus' => DB::connection('tenant')->table('ecu')->where('code_unite', $tiu->code_unite)->get()
                        ];
                        $i++;
                    } else {
                        $results['reprises'][$j] = [
                            'ue' => DB::connection('tenant')->table('unites')->where('code_unite', $tiu->code_unite)->first(),
                            'ecus' => DB::connection('tenant')->table('ecu')->where('code_unite', $tiu->code_unite)->get()
                        ];
                        $j++;
                    }
                }

                return response()->json([
                    'success' =>  true,
                    'data' => $results,
                    'userData' => $info,
                    'nor' => $rep,
                    'message' => 'USER_USES_GOT_SUCCESSFULLY'
                ], 200);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'USER_NOT_FOUND'
                ], 404);
            }
        } catch (Exception $e) {
            return response()->json([
                'success' =>  false,
                'message' => $e->getMessage()
            ], 400);
        }
    }

    public function user_student_profile(BdCheckRequest $request, $matricule)
    {

        try {

            $bd = $request->bd;

		    $profil = DB::connection('tenant')
                ->table('tabetudiant')
                ->where('matricule','=',$matricule)->first();

            $username = DB::table('users_student')
                ->where('matricule','=',$matricule)
                ->select('username')
                ->first();

            $filiere = DB::connection('tenant')
                ->table('tabinscription')
                ->where('matricule','=',$matricule)
                ->join('filieres','tabinscription.idFiliere','=','filieres.idFiliere')
                ->select('filieres.intituleFilieres')
                ->first();

            return response()->json([
                'success' => true,
                'data' => [
                    'profil' => $profil,
                    'filiere' =>$filiere->intituleFilieres,
                    'username' => $username
                ],
                'message' => 'USER_STUDENT_GOT_SUCCESSFULY'
            ])->withHeaders([
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ]);
        } catch (Exception $e) {

            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 400)->withHeaders([
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ]);
        }

    }


    public function user_student_state(BdCheckRequest $request, $matricule)
    {
        try {
            $acad = DB::connection('tenant')->table('periodeinscription')->where('affiche', 'YES')->select('annee_acad')->first();
            $annee_acad = $acad->annee_acad;

            $user_student = DB::connection('tenant')->table('tabinscription')->where('matricule', $matricule)
                                                ->select('tabinscription.*', 'tabinscription.annee_acad as annee_acad')
                                                ->get()->groupBy(['annee_acad']);

            $soutenant = DB::connection('tenant')->table('tabinscription')
            ->where([['matricule','=',$matricule],['annee_acad','=',$annee_acad]])
            ->where(function ($query){
                $query->where([['tabinscription.annee','=',3],['tabinscription.niveauFormation','=',1]])
                      ->orWhere([['tabinscription.annee','=',2],['tabinscription.niveauFormation','=',2]])
                      ->orWhere([['tabinscription.annee','=',3],['tabinscription.niveauFormation','=',3]]);
            })->get()->first();

            if($soutenant){
                $soutenant = true;
            }else{
                $soutenant = false;
            }



            if ($user_student != null) {
                return response()->json([
                    'success' => true,
                    'data' => $user_student,
                    'soutenant' => $soutenant,
                    'message' => 'USER_STUDENT_Statut_GOT_SUCCESSFULY'
                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'THIS_USER_STUDENT_DOESNT_EXIST',
                ], 400)->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 400)->withHeaders([
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ]);
        }
    }


    protected function getUserStudentData(Request $request){

        try {

            $matricules_array = $request->matricules_array;

            $matricules_array = is_array($matricules_array) ? $matricules_array : [$matricules_array];

            $data_mat_array = array();

            $toTreat = [];

            foreach ($matricules_array as $key => $value) {
                array_push($toTreat,$value);
            }

            /*foreach ($request->matricules_array as $matricule){

                $data = DB::connection('tenant')->table('tabetudiant')->where('matricule','=',$matricule)->first();

                $data_mat_array[$matricule] = $data;
                //array_push($data_mat_array,array($matricule => $data));
            }*/

            $data_mat_array = DB::connection('tenant')->table('tabetudiant')->select('*')->whereIn('matricule',$toTreat)
            ->get()
            ->groupBy('matricule');

            return sendResponse($data_mat_array, "USERS_DATA_GOT_SUCCESSFULY");

        } catch (Exception $e) {
            return sendError("SERVER ERROR, PLEASE CONTACT ADMINISTRATOR", $e->getMessage(), 400);
        }
    }

    protected function checkUserStudent($request)
    {
        try {
            if (
                $user_student = DB::connection('tenant')
                ->table('users_student')
                ->where([
                    ['username', $request->username],
                    ['password', $request->password]
                ])
                ->first()
            ) {
                return $user_student;
            } else {
                return false;
            }
        } catch (Exception $e) {
            return null;
        }
    }

    //Fonction pour récupérer les étudiants d'un département en annee de soutenance n'ayant pas de theme

    public function etudiants_sans_theme (Request $request,$id){
        try {

            $request->validate([
                'bd' => ['required', 'min:2'],
                //'data' => ['required','array']
                //'niveau' => ['required','integer']
            ]);
           /* $niveau = $request->niveau ;
            $annee = 0;

            if($niveau == 1){
                $annee = 3;
            }
            else if($niveau == 2 || $niveau == 3){
                $annee = 2;
            }*/

            $etudiants_sans_theme = DB::connection('tenant')->table('filieres')
                ->where('idDepartement','=',$id)
                ->join('tabinscription','filieres.idFiliere','=','tabinscription.idFiliere')
                /*->where(function ($query){
                    $query->where('tabinscription.annee_acad','=',date('Y', strtotime('+1 year')))
                          ->orWhere('tabinscription.annee_acad','=',date('Y'));
                })*/
                ->where(function ($query){
                    $query->where([['tabinscription.annee','=',3],['tabinscription.niveauFormation','=',1]])
                          ->orWhere([['tabinscription.annee','=',2],['tabinscription.niveauFormation','=',2]])
                          ->orWhere([['tabinscription.annee','=',2],['tabinscription.niveauFormation','=',3]]);
                })
                ->select('matricule','tabinscription.niveauFormation','filieres.idFiliere','filieres.intituleFilieres')
                ->whereNotIn('tabinscription.matricule',$request->data)
                ->orderBy('tabinscription.niveauFormation')
                ->get()
                ->toArray();

            //$matricules = array_column($etudiants_sans_theme,'matricule');

            if($etudiants_sans_theme){

                return response()->json([
                    'success' => true,
                    'data' => $etudiants_sans_theme,
                    'message' => 'DATA_GOT_SUCCESSFULY'
                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }


        } catch (Exception $e) {

            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 400)->withHeaders([
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ]);
        }
    }

    public function alumni(Request $request){

        // $request->validate([

        //     'bd' => ['required', 'min:2', 'string'],
        // ]);

        $matricules_array = $request->matricules_array;

        $matricules_array = is_array($matricules_array) ? $matricules_array : [$matricules_array];

        $data_mat_array = array();

 		$data_mat_array = DB::connection('tenant')->table('tabetudiant')
	          ->whereIn('tabetudiant.matricule',$matricules_array)
	          ->join('tabinscription','tabetudiant.matricule','=','tabinscription.matricule')
	          ->join('filieres','tabinscription.idFiliere','=','filieres.idFiliere')
	          ->select('tabetudiant.*','filieres.intituleFilieres as filiere')
	          ->get();

        return response()->json([
            'success' => true,
            'data' => $data_mat_array,
            'message' => 'USERS_DATA_GOT_SUCCESSFULY'
        ])->withHeaders([
            'Accept' => 'application/json',
            'Content-Type' => 'application/json'
        ]);
    }


    public function user_student_qcm (Request $request,$id){

        try {
            $request->validate([

                'bd' => ['required', 'min:2', 'string'],
            ]);

            $userStudent = DB::connection($request->bd)->table('users_student')
            ->where('matricule','=',$id)
            ->join('tabinscription','users_student.matricule','=','tabinscription.matricule')
            ->where(function ($query){
                $query->where('tabinscription.annee_acad','=',date('Y', strtotime('+1 year')))
                      ->orWhere('tabinscription.annee_acad','=',date('Y'));
            })->get();

            if($userStudent){

                $qcm = DB::connection($request->bd)->table('ecu')
                ->where(function ($query){
                    $query->where('ecu.annee_acad','=',date('Y', strtotime('+1 year')))
                          ->orWhere('ecu.annee_acad','=',date('Y'));
                })
                ->join('chapitres','ecu.idEC','=','chapitres.ecu_id')
                ->join('qcms','chapitres.id_chap','=','qcms.id_qcm')
                ->select('qcms.quiz');

                return response()->json([
                    'success' => true,
                    'data' => $qcm,
                    'message' => 'DATA_GOT_SUCCESSFULY'
                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }
            else{
                return response()->json([
                    'success' => false,
                    'message' => 'STUDENT_DATA_NOT_FOUND'
                ], 400)->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }

        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 400)->withHeaders([
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ]);
        }
    }

    //Ecus liees à un etudiant groupé par semestre

    public function user_student_ecus(Request $request,$matricule){

        try {

            $user = DB::table('users_student')->where('matricule', $matricule)->first();
            $user_filiere = 0;
            $acad = DB::connection('tenant')->table('periodeinscription')->where('affiche', 'YES')->select('annee_acad')->first();
            $annee_acad = $acad->annee_acad;
            //if (isset($user)) {

                $datas = DB::connection('tenant')->table('tabinscriunite')
                    ->where('matricule','=',$matricule)
                    ->where('inscription_actuelle','=',$annee_acad)
                    ->select('matricule','idFiliere as id_filiere','annee','code_unite','niveauFormation','premiere_inscription','inscription_actuelle','resultat')
                    ->get();

                /*
                if (!isset($datas)){
                    return response()->json([
                        'success' =>  false,
                        'data' => [],
                        'message' => 'SOME_REQUEST_DATA_NOT_FOUND'
                    ], 400);
                }
                */

                $codes_ues_normales = [];
                $codes_ues_reprises = [];

                foreach($datas as $data){

                    if($data->premiere_inscription == $data->inscription_actuelle){
                        $user_filiere = $data->id_filiere;
                        array_push($codes_ues_normales,$data->code_unite);
                    }
                    else{
                        array_push($codes_ues_reprises,$data->code_unite);
                    }
                }

                if ($request->option == 'all') {

                    $matricules_profs = [];

                    // $ues_normales = DB::connection('tenant')->table('unites')
                    //     ->whereIn('unites.code_unite',$codes_ues_normales)
                    //     ->where('unites.idFiliere','=',$user_filiere)
                    //     ->join('ecu','unites.code_unite','=','ecu.code_unite')
                    //     ->where('ecu.idFiliere','=',$user_filiere)
                    //     ->select('unites.idUE as id_UE','unites.code_unite','unites.intituleUnite','unites.credit','unites.semestre','unites.idFiliere as id_Filiere','unites.annee','unites.niveauFormation','unites.annee_acad','unites.type_ue','unites.moy_pondere','unites.insertion','unites.code_fiche',
                    //         'ecu.idEC as id_EC','ecu.code_ecu','ecu.code_unite','ecu.intituleEcu','ecu.credit','ecu.insertion','ecu.rattrapage','ecu.idFiliere as id_Filiere','ecu.annee','ecu.niveauFormation','ecu.annee_acad','ecu.matricule')
                    //     //->distinct()
                    //     ->get()
                    //     //->groupBy('code_ecu')
                    //     ->groupBy('semestre');

                    $ues_normales = DB::connection('tenant')->table('unites')
                        ->whereIn('unites.code_unite',$codes_ues_normales)
                        ->where('unites.idFiliere','=',$user_filiere)
                        ->where('unites.annee_acad',$annee_acad)
                        ->join('ecu','unites.code_unite','=','ecu.code_unite')
                        ->where('ecu.idFiliere','=',$user_filiere)
                        ->where('ecu.annee_acad','=',$annee_acad)
                        ->select('unites.idUE as id_UE','unites.code_unite','unites.intituleUnite','unites.credit','unites.semestre','unites.idFiliere as id_Filiere','unites.annee','unites.niveauFormation','unites.annee_acad','unites.type_ue','unites.moy_pondere','unites.insertion','unites.code_fiche',
                            'ecu.idEC as id_EC','ecu.code_ecu','ecu.code_unite','ecu.intituleEcu','ecu.credit','ecu.insertion','ecu.rattrapage','ecu.idFiliere as id_Filiere','ecu.annee','ecu.niveauFormation','ecu.annee_acad','ecu.matricule')
                        ->get()
                        ->groupBy('semestre');

                    $datas = DB::connection('tenant')->table('unites')
                        ->whereIn('unites.code_unite',$codes_ues_normales)
                        ->where('unites.idFiliere','=',$user_filiere)
                        ->where('unites.annee_acad',$annee_acad)
                        ->join('ecu','unites.code_unite','=','ecu.code_unite')
                        ->where('ecu.idFiliere','=',$user_filiere)
                        ->where('ecu.annee_acad','=',$annee_acad)
                        ->get()
                        ->pluck('matricule')->toArray();

                        $datas = array_unique($datas);

                    foreach($datas as $data){
                        array_push($matricules_profs,$data);
                    }

                    /*
                    if (!isset($ues_normales)){
                        return response()->json([
                            'success' =>  false,
                            'data' => [],
                            'message' => 'SOME_REQUEST_DATA_NOT_FOUND'
                        ], 400);
                    }
                    */

                    $ues_reprises = DB::connection('tenant')->table('unites')
                        ->whereIn('unites.code_unite',$codes_ues_reprises)
                        ->where('unites.idFiliere','=',$user_filiere)
                        ->where('unites.annee_acad',$annee_acad)
                        ->join('ecu','unites.code_unite','=','ecu.code_unite')
                        ->where('ecu.idFiliere','=',$user_filiere)
                        ->where('ecu.annee_acad','=',$annee_acad)
                        ->select('unites.idUE as id_UE','unites.code_unite','unites.intituleUnite','unites.credit','unites.semestre','unites.idFiliere as id_Filiere','unites.annee','unites.niveauFormation','unites.annee_acad','unites.type_ue','unites.moy_pondere','unites.insertion','unites.code_fiche',
                            'ecu.idEC as id_EC','ecu.code_ecu','ecu.code_unite','ecu.intituleEcu','ecu.credit','ecu.insertion','ecu.rattrapage','ecu.idFiliere as id_Filiere','ecu.annee','ecu.niveauFormation','ecu.annee_acad','ecu.matricule')
                        ->get()
                        //->groupBy('code_unite')
                        ->groupBy('semestre');

                    $datas = DB::connection('tenant')->table('unites')
                        ->whereIn('unites.code_unite',$codes_ues_reprises)
                        ->where('unites.idFiliere','=',$user_filiere)
                        ->where('unites.annee_acad',$annee_acad)
                        ->join('ecu','unites.code_unite','=','ecu.code_unite')
                        ->where('ecu.idFiliere','=',$user_filiere)
                        ->where('ecu.annee_acad','=',$annee_acad)
                        ->get()
                        ->pluck('matricule')->toArray();

                    $datas = array_unique($datas);

                    foreach($datas as $data){
                        array_push($matricules_profs,$data);
                    }

                    $matricules_profs = array_unique($matricules_profs);

                    $profs_data = DB::connection('tenant')->table('enseignant')
                        ->select('*')
                        ->whereIn('matricule',$matricules_profs)
                        ->get()
                        ->groupBy('matricule');

                    /*
                    if (!isset($ues_reprises)){
                        return response()->json([
                            'success' =>  false,
                            'data' => [],
                            'message' => 'SOME_REQUEST_DATA_NOT_FOUND'
                        ], 400);
                    }
                    */
                    $success = [
                        'codes_ues_normales' => $codes_ues_normales,
                        'codes_ues_reprises' => $codes_ues_reprises ,
                        'ues_normales' => $ues_normales,
                        'ues_reprises' => $ues_reprises,
                        'profs_data' => $profs_data
                    ];

                    return sendResponse($success, "DATA_GOT_SUCESSFULLY");

                } else if ($request->option == 'notAll') {

                    $codes_ecus = [];
                    $ecus_infos = [];

                    $dat = DB::connection('tenant')->table('unites')
                        ->whereIn('unites.code_unite',$codes_ues_normales)
                        ->where('unites.idFiliere','=',$user_filiere)
                        ->where('unites.annee_acad',$annee_acad)
                        ->join('ecu','unites.code_unite','=','ecu.code_unite')
                        ->where('ecu.idFiliere','=',$user_filiere)
                        ->where('ecu.annee_acad','=',$annee_acad)
                        ->select('unites.idUE as id_UE','unites.code_unite','unites.intituleUnite','unites.credit','unites.semestre','unites.idFiliere as id_Filiere','unites.annee','unites.niveauFormation','unites.annee_acad','unites.type_ue','unites.moy_pondere','unites.insertion','unites.code_fiche',
                            'ecu.idEC as id_EC','ecu.code_ecu','ecu.code_unite','ecu.intituleEcu','ecu.credit','ecu.insertion','ecu.rattrapage','ecu.idFiliere as id_Filiere','ecu.annee','ecu.niveauFormation','ecu.annee_acad','ecu.matricule')
                        ->get()
                        ->groupBy('id_EC');

                    $ids_ecus = array_keys($dat->toArray());

                    $dat = encryptKeys($dat);

                    $dat_2 = DB::connection('tenant')->table('unites')
                        ->whereIn('unites.code_unite',$codes_ues_normales)
                        ->where('unites.idFiliere','=',$user_filiere)
                        ->where('unites.annee_acad',$annee_acad)
                        ->join('ecu','unites.code_unite','=','ecu.code_unite')
                        ->where('ecu.idFiliere','=',$user_filiere)
                        ->where('ecu.annee_acad','=',$annee_acad)
                        ->get();

                    array_push($ecus_infos,$dat);

                    $datas = $dat_2->pluck('code_ecu')->toArray();

                    $datas = array_unique($datas);

                    foreach($datas as $data){
                        array_push($codes_ecus,$data);
                    }

                    $dat = DB::connection('tenant')->table('unites')
                        ->whereIn('unites.code_unite',$codes_ues_reprises)
                        ->where('unites.idFiliere','=',$user_filiere)
                        ->where('unites.annee_acad',$annee_acad)
                        ->join('ecu','unites.code_unite','=','ecu.code_unite')
                        ->where('ecu.idFiliere','=',$user_filiere)
                        ->where('ecu.annee_acad','=',$annee_acad)
                        ->select('unites.idUE as id_UE','unites.code_unite','unites.intituleUnite','unites.credit','unites.semestre','unites.idFiliere as id_Filiere','unites.annee','unites.niveauFormation','unites.annee_acad','unites.type_ue','unites.moy_pondere','unites.insertion','unites.code_fiche',
                            'ecu.idEC as id_EC','ecu.code_ecu','ecu.code_unite','ecu.intituleEcu','ecu.credit','ecu.insertion','ecu.rattrapage','ecu.idFiliere as id_Filiere','ecu.annee','ecu.niveauFormation','ecu.annee_acad','ecu.matricule')
                        ->get()
                        ->groupBy('id_EC');

                    array_merge($ids_ecus, array_keys($dat->toArray()));

                    $dat = encryptKeys($dat);

                    $dat_2 = DB::connection('tenant')->table('unites')
                        ->whereIn('unites.code_unite',$codes_ues_reprises)
                        ->where('unites.idFiliere','=',$user_filiere)
                        ->where('unites.annee_acad',$annee_acad)
                        ->join('ecu','unites.code_unite','=','ecu.code_unite')
                        ->where('ecu.idFiliere','=',$user_filiere)
                        ->where('ecu.annee_acad','=',$annee_acad)
                        ->get();

                    array_push($ecus_infos,$dat);

                    $datas = $dat_2->pluck('code_ecu')->toArray();

                    $datas = array_unique($datas);

                    foreach($datas as $data){
                        array_push($codes_ecus,$data);
                    }
                    $success = [
                        'codes_ecus' => $codes_ecus,
                        'infos_ecus' => $ecus_infos,
                        'ids_ecus' => $ids_ecus
                    ];

                    return sendResponse($success, "DATA_GOT_SUCESSFULLY");
                }

            /*
            }
            else{
                return response()->json([
                    'success' =>  false,
                    'data' => [],
                    'message' => 'USER_NOT_FOUND'
                ], 400);
            }
            */

        } catch (Exception $e) {
            return sendError("SERVER ERROR, PLEASE CONTACT ADMINISTRATOR", $e->getMessage(), 400);
        }
    }

    // ECS liées à l'étudiant 
    public function get_user_student_ecus(Request $request, $matricule){
        try {
            $user = DB::table('users_student')->where('matricule', $matricule)->first();

            if (!$user) {
                return sendError("USER DOESN'T EXIST !", [], 400);
            }
        
            $annee_acad = current_acad();

            $query = DB::connection('tenant')->table('tabinscriunite')
            ->where('tabinscriunite.matricule','=',$matricule)
            ->where('inscription_actuelle','=',$annee_acad)
            ->join('unites', function($join)
            {
                $join->on('tabinscriunite.inscription_actuelle','=','unites.annee_acad');
                $join->on('tabinscriunite.code_unite', '=', 'unites.code_unite');
                $join->on('tabinscriunite.idFiliere','=','unites.idFiliere');
                $join->on('tabinscriunite.annee','=','unites.annee');
                $join->on('tabinscriunite.niveauFormation','=','unites.niveauFormation');
            })
            ->join('ecu', function($join)
            {
                $join->on('tabinscriunite.inscription_actuelle','=','ecu.annee_acad');
                $join->on('tabinscriunite.code_unite', '=', 'ecu.code_unite');
                $join->on('tabinscriunite.idFiliere','=','ecu.idFiliere');
                $join->on('tabinscriunite.annee','=','ecu.annee');
                $join->on('tabinscriunite.niveauFormation','=','ecu.niveauFormation');
            })
            ->select(
                'tabinscriunite.premiere_inscription','tabinscriunite.inscription_actuelle','tabinscriunite.resultat',
                'unites.semestre',
                'ecu.idEC as id_EC','ecu.code_ecu','ecu.code_unite','ecu.intituleEcu','ecu.credit','ecu.insertion','ecu.rattrapage','ecu.idFiliere as id_Filiere','ecu.annee','ecu.niveauFormation','ecu.annee_acad','ecu.matricule'
                // 'ecu.*',
            )
            ->orderByDesc('ecu.niveauFormation')
            ->orderByDesc('ecu.annee')
            ->orderBy('unites.semestre', 'asc')
            ->orderBy('ecu.intituleEcu', 'asc')
            ;

            if ($request->get('limit')) {
                $query = $query->limit($request->get('limit'));
            }

            $ecs = $query->get();

            $prof_matricules = $ecs->pluck("matricule")->toArray();
            $prof_matricules = array_unique($prof_matricules);

            $profs = DB::connection('tenant')->table('enseignant')
                ->whereIn('matricule',$prof_matricules)
                ->get()
                ->groupBy('matricule');

            $meta = [
                'pp_path' => getImgPath("PROFIL", 4),
                // 'ec_img_path' => ...,
            ];

            return sendResponse([
                'ecs' => $ecs,
                'profs' => $profs,
                'meta' => $meta,
            ], "DATA_GOT_SUCESSFULLY");
        } catch (Exception $e) {
            return sendError("SERVER ERROR, PLEASE CONTACT ADMINISTRATOR", $e->getMessage(), 500);
        }
    }

    // Examens en attente de l'etudiant

    public function exam(Request $request) {

        try {

            date_default_timezone_set("Africa/Porto-Novo");

            /*$actualDate = Carbon::now();
            $actualDate = $actualDate->toDateString();

            $time = strtotime($actualDate);
            $newFormat = date('d/M/Y',$time);

            $exam = DB::connection('tenant')
                ->table('examen')
                ->where('date', '>',$newFormat)
                ->get();*/

            // $toTreat = [];

            // foreach ($request->codes_ecus as $key => $value) {
            //     array_push($toTreat,$value);
            // }

            // $ecus_ids = DB::connection('tenant')
            //     ->table('ecu')
            //     ->whereIn('code_ecu',$toTreat)
            //     ->get()
            //     ->pluck('idEC')->toArray();

            //$actualDate = date('d/m/Y');
            //$time = date('H:i');

            /*$exam = DB::connection('tenant')
                ->table('examen')
                ->whereIn('idecu', $ecus_ids)
                ->where('date', '>=', $actualDate)
                ->where('heure', '<', $time)
                ->orderBy('date')
                ->orderBy('heure')
                ->get();*/

            $ecus_ids = array_values($request->ids_ecus);

            $exam = DB::connection('tenant')
                ->table('examen')
                ->whereIn('idecu', $ecus_ids)
                ->where('valide', '=', 'O')
                ->orderBy('date')
                ->orderBy('heure')
                ->select('idexamen as id_examen','idecu as id_ecu','type_examen','date','heure','duree','poste_disponible','description','valide','pause')
                ->get();

            return sendResponse($exam, "DATA_GOT_SUCCESSFULY");

        } catch (Exception $e) {
            return sendError("SERVER ERROR, PLEASE CONTACT ADMINISTRATOR", $e->getMessage(), 400);
        }
    }
}
