<?php

namespace App\Metier;

use App\Models\Banque;
use App\Models\Competence;
use App\Models\Contexte;
use App\Models\Critere;
use App\Models\Domaine;
use App\Models\Encadrant_Service_Etudiant;
use App\Models\Enseignant;
use App\Models\Etudiant;
use App\Models\Etudiant_Examen;
use App\Models\Examen;
use App\Models\Item;
use App\Models\Niveau;
use App\Models\Patient_Simule;
use App\Models\Session;
use App\Models\Session_Medecin;
use App\Models\Station;
use App\Models\Systeme;
use App\Models\TitreGItem;
use Illuminate\Support\Facades\DB;


class GestSession
{


    public function recuper_id_niveau($niveau, $filiere)
    {
        $niv = Niveau::where('niveau', '=', $niveau, 'and', 'filiere', '=', $filiere)
            ->first();

        return $niv->id_Niveau;
    }

    function createSession($nom, $id_Niveau)
    {

        $this->session = new Session;
       

      
            $this->session->nom = $nom;
            $this->session->id_Niveau = $id_Niveau;
            $this->session->save();
        


        return $this->session;
    }

   public function createExamen($id_Stage, $date, $id_Session,$max_Places,$id_Jury)
    {


        $examens = Examen::whereIdSessionAndIdStage($id_Session, $id_Stage)
            ->where('date', '=', $date)
            ->get();


        if (count($examens) == 0) {
            $this->examen = new Examen;
            $this->examen->date = $date;
            $this->examen->id_Session = $id_Session;
            $this->examen->id_Stage = $id_Stage;
            $this->examen->max_Places= $max_Places ;
            $this->examen->nbre_Places = 0;
            $this->examen->id_Enseignant = $id_Jury ;
            $this->examen->save();
            return $this->examen;
        }

        return null; //S'il existe un examen dans ce date //Erreur d'ajout


    }

    public function createStations($banqueIDs, $ponderations, $id_Examen)
    {
        $i = 0;
        foreach ($banqueIDs as $banqueID) {
            $this->createStation($banqueID, $ponderations[$i], $id_Examen);
            $i++;
        }
    }

    public function createStation($banqueID, $ponderation, $id_Examen)
    {

        $station = Station::whereIdBanqueAndIdExamen($banqueID, $id_Examen)
            ->first();


        if (!$station) {
            $this->station = new Station;
            $this->station->id_Banque = $banqueID;
            $this->station->id_Examen = $id_Examen;
            $this->station->ponderation = $ponderation;
            $this->station->save();

            return $this->station;
        }

        return null;
    }

    public function createStationToBanque($id_Domaine, $id_Critere, $id_Systeme, $id_Contexte, Array $items, Array $inputs)
    {
        $this->banque = new Banque;

        $this->banque->label = $inputs['label'];
        $this->banque->situation_Clinique = $inputs['situation_Clinique'];
        $this->banque->instruction_Etudiant = $inputs['instruction_Etudiant'];
        $this->banque->id_Domaine = $id_Domaine;
        $this->banque->id_Critere = $id_Critere;
        $this->banque->id_Systeme = $id_Systeme;
        $this->banque->id_Contexte = $id_Contexte;

        $this->banque->save();

        foreach ($items as $item) {
            $id_Competance = $this->trouverId($item["competance"]);
            $this->createItem($id_Competance, $item["id_TitreGItem"], $this->banque->id_Banque, $item["val"]);
        }
    }

    public function trouverId($competance)
    {
        $com = Competence::where('nom', '=', $competance)
            ->first();

        return $com->id_Competence;
    }


    //Remplissage du Banque

    //Array items : element :
    //competance
    //id_titreGItem
    //valeur

    public function createItem($id_Competence, $id_TitreGItem, $id_Banque, $val)
    {
        $this->item = new Item;
        $this->item->id_Competence = $id_Competence;
        $this->item->id_TitreGItem = $id_TitreGItem;
        $this->item->id_Banque = $id_Banque;
        $this->item->valeur = $val;
        $this->item->save();

        return $this->item;
    }


    //Appel de fonction au cours de Saisir les infos sur la station

    public function createTitreGItem(Array $inputs)
    {
        $this->titregitem = new TitreGItem;
        $this->nom = $inputs['nom'];
        $this->ponderation = $inputs['ponderation'];
        $this->titregitem->save();

        return $this->titregitem;
    }

    public function affectPatientsSimule($patients, $id_Session)
    {
        foreach ($patients as $patient) {
            $this->affectPatientSimule($id_Session, $patient);
        }
    }

    public function affectPatientSimule($id_Session, Array $inputs)
    {

        $this->patient = new Patient_Simule;
        $this->patient->id_session = $id_Session;
        $this->patient->cin = $inputs['CIN'];
        $this->patient->nom = $inputs['nom'];
        $this->patient->prenom = $inputs['prenom'];

        $this->patient->save();

        return $this->patient;
    }

    public function affectMedSession($idsmedSess, $id_Session)
    {

        foreach ($idsmedSess as $id) {
            $this->createObserverToSession($id, $id_Session);
        }

    }

    public function createObserverToSession($id_Enseignant, $id_Session)
    {
        $observer = Session_Medecin::whereIdEnseignantAndIdSession($id_Enseignant, $id_Session)->first();
        if (!$observer) {
            $this->sess_med = new Session_Medecin;
            $this->sess_med->id_Enseignant = $id_Enseignant;
            $this->sess_med->id_Session = $id_Session;
            $this->sess_med->save();

        }
    }
    public function destroyMedObserver($sessionId){
        DB::table('Session_Medecin')
            ->where('id_Session','=',$sessionId)
            ->delete();
    }
    public function createEtudiantToExamen($id_Etudiant, $id_Examen)
    {

        //if(stageValid)
        $etudiant = Etudiant_Examen::whereIdExamenAndIdEtudiant($id_Examen, $id_Etudiant)
            ->first();


        if (!$etudiant) {

            $this->etudiantSess->id_Etudiant = $id_Etudiant;
            $this->etudiantSess->id_Examen = $id_Examen;
            $this->etudiantSess->save();

            return $this->etudiantSess;
        }

        return null; //Etudiant déja inscrit
        //else Stage Non valide


    }

    public function getNiveaux()
    {
        return Niveau::all();
    }

    public function getMedObserver($rech)
    {
        return Enseignant::join('Enseignant_Privilege', 'Enseignant_Privilege.id_Enseignant', '=', 'Enseignant.id_Enseignant')
            ->join('Privilege','Privilege.id_Privilege','=','Enseignant_Privilege.id_Privilege')
            ->where('Privilege.nom', '=', 'observateur')
            ->where('Enseignant.nom','LIKE',$rech.'%')
            ->select('Enseignant.*')
            ->orderBy('Enseignant.nom')
            ->get();
    }

    public function getStations($examenId){
        return Station::where('id_Examen','=',$examenId)
                ->join('Banque','Banque.id_Banque','=','Station.id_Banque')
                ->get();
    }
    
    public function getStation($stationId){
        return Station::where('id_Station','=',$stationId)
                ->join('Banque','Banque.id_Banque','=','Station.id_Banque')
                ->first();
    }

    public function getSession($date, $id_Niveau)
    {
        return Session::where('date', '=', $date, 'and', 'id_Niveau', '=', $id_Niveau)->get();
    }
    
    public function getSessionWithId($sessionId){
        return Session::find($sessionId);
    }

    public function getSessions()
    {
        return Session::join('Niveau','Session.id_Niveau','=','Niveau.id_Niveau')->get();
    }

    public function getDomaines()
    {
        return Domaine::all();
    }

    public function getCriteres()
    {
        return Critere::all();
    }

    public function getSystemes()
    {
        return Systeme::all();
    }

    public function getContextes()
    {
        return Contexte::all();
    }

    public function getDomaine($domaineId)
    {
        return Domaine::find($domaineId);
    }

    public function getCritere($critereId)
    {
        return Critere::find($critereId);
    }

    public function getSysteme($systemeId)
    {
        return Systeme::find($systemeId);
    }

    public function getContexte($contextId)
    {
        return Contexte::find($contextId);
    }

    public function getCompetences()
    {
        return Competence::all();
    }

    public function getTitreGItems(){
        return TitreGItem::all();
    }
   
    public function getTitreGItem($titreId){
        return TitreGItem::find($titreId);
    }
   
    public function getAllBanques()
    {
        return Banque::join('Domaine', 'Domaine.id_Domaine', '=', 'Banque.id_Domaine')
            ->join('Critere', 'Critere.id_Critere', '=', 'Banque.id_Critere')
            ->join('Contexte', 'Contexte.id_Contexte', '=', 'Banque.id_Contexte')
            ->join('Systeme', 'Systeme.id_Systeme', '=', 'Banque.id_Systeme')
            ->select(DB::raw('id_Banque ,label , situation_Clinique , instruction_Etudiant
                , Domaine.id_Domaine
                , Critere.id_Critere
                , Contexte.id_Contexte
                , Systeme.id_Systeme
                , Critere.code as code_critere
                , Critere.nom as nom_critere
                , Domaine.code as code_domaine
                , Domaine.nom as nom_domaine
                , Systeme.code as code_systeme
                , Systeme.nom as nom_systeme
                , Contexte.code as code_contexte
                , Contexte.nom as nom_contexte
                '))
            ->get();


    }

    public function getComp()
    {
        $banques = $this->getBanques();
        $arr = array();
        foreach ($banques as $banque) {
            $cmpArray = array();
            $comps = $this->getCompetencesBanque($banque->id_Banque);

            foreach ($comps as $comp) {
                array_push($cmpArray, $comp->prefix);
            }
            array_push($arr, $cmpArray);
        }
        return $arr;
    }

    public function getCompId()
    {
        $banques = $this->getBanques();
        $arr = array();
        foreach ($banques as $banque) {
            $cmpArray = array();
            $comps = $this->getCompetencesBanque($banque->id_Banque);

            foreach ($comps as $comp) {
                array_push($cmpArray, $comp->id_Competence);
            }
            array_push($arr, $cmpArray);
        }
        return $arr;
    }

    public function getBanques()
    {
        return Banque::all();
    }

    public function getCompetencesBanque($id_Banque)
    {
        return Item::join('Competence', 'Competence.id_Competence', '=', 'Item.id_Competence')
            ->where('Item.id_Banque', '=', $id_Banque)
            ->select('Competence.*')
            ->distinct()
            ->get();
    }

    public function verifEtudiant($cin, $email)
    {
        $etudiant = Etudiant::where('CIN', '=', $cin)
            //->where('email', '=', $email)
            ->first();

        return $etudiant ? $etudiant->id_Etudiant : null;
    }

    public function verifNiveauEtudiant($id_Etudiant, $id_Session)
    {
        $etudiant = Etudiant::where('id_Etudiant', '=', $id_Etudiant)->first();


        return Session::where('id_Session', '=', $id_Session)
            ->where('id_Niveau', '=', $etudiant->id_Niveau)
            ->first();
    }

    public function getValidationEtudiant($sessionId, $etudiantId)
    {
        $examens = $this->getExamens($sessionId);
        $validation = array();
        foreach ($examens as $examen) {
            $arr=[];
            $stageId = $examen->id_Stage;
            $valides = Encadrant_Service_Etudiant::where('id_Etudiant', '=', $etudiantId)
                ->where('isValid', '=', '0')
                ->orWhere('isValid','=','-1')
                ->join('Service', 'Service.id_Service', '=', 'Encadrant_Service_Etudiant.id_Service')
                ->where('Service.id_Stage', '=', $stageId)
                ->get();
            $nbreStages = Encadrant_Service_Etudiant::where('id_Etudiant', '=', $etudiantId)
                ->join('Service', 'Service.id_Service', '=', 'Encadrant_Service_Etudiant.id_Service')
                ->where('Service.id_Stage', '=', $stageId)
                ->get();
            if ((count($valides)==0)&&(count($nbreStages)>0)) {
                $etudiant = etudiant_examen::where('id_Etudiant', '=', $etudiantId)
                    ->where('id_Examen', '=', $examen->id_Examen)->first();
                if (!$etudiant){
                    if($examen->nbre_Places<$examen->max_Places){
                    array_push($arr, "");
                    array_push($arr, "");
                    array_push($validation, $arr);
                    }else {
                        array_push($arr, "disabled");
                        array_push($arr, "Pas de places restantes");
                        array_push($validation, $arr);
                    }
                } else{
                    array_push($arr, "disabled");
                    array_push($arr, "Vous étes inscrit");
                    array_push($validation, $arr);
                }
            } else {
                if(count($nbreStages)==0){
                    array_push($arr, "disabled");
                    array_push($arr, "Vous ne pouvez pas passer cet examen ");
                    array_push($validation, $arr); 
                }else {
                    array_push($arr, "disabled");
                    array_push($arr, "Votre stage est non validé");
                    array_push($validation, $arr); 
                }
            }
        }
        return $validation;
    }
    public function getItems($banqueId){
        return Item::where('id_Banque', '=', $banqueId)->get();
    }
    public function getItem($itemid){
        return Item::find($itemId);
    }
    public function getGrille($stationId){
        return Item::join('Banque','Banque.id_Banque','=','Item.id_Banque')
            ->join('Station','Station.id_Banque','=','Banque.id_Banque')
            ->where('Station.id_Station','=',$stationId)
            ->join('TitreGItem','TitreGItem.id_TitreGItem','=','Item.id_TitreGItem')
           ->orderBy('TitreGItem.id_TitreGItem')
           ->select('Item.*','TitreGItem.nom')
            ->get();
    }
    public function getExamens($sessionId)
    {
        return Examen::where("id_Session", "=", $sessionId)
            ->join('Stage','Stage.id_Stage','=','Examen.id_Stage')
            ->get();
    }
     public function getExamen($examenId)
    {
        return Examen::find($examenId);
    }
    public function getExamensJury($juryId){
        return Examen::whereIdEnseignant($juryId)->join('Session','Session.id_Session','=',
            'Examen.id_Session')
            ->join('Stage','Stage.id_Stage','=','Examen.id_Stage')
            ->join('Niveau','Niveau.id_Niveau','=','Session.id_Niveau')
            ->get();
    }

    public function inscrireEtudiantExamen($examenId, $etudiantId)
    {
        $Etudiant_Examen = new Etudiant_Examen;
        $examen=Examen::find($examenId);
        $examen->nbre_Places++;
        $examen->save();
        $Etudiant_Examen->id_Etudiant = $etudiantId;
        $Etudiant_Examen->id_Examen = $examenId;
        $Etudiant_Examen->save();
    }
    public function getEtudiantExamen($idExamen)
    {
       
        return Etudiant::join('Etudiant_Examen','Etudiant_Examen.id_Etudiant','=','Etudiant.id_Etudiant')
            ->where('Etudiant_Examen.id_Examen','=',$idExamen)->get();
    }
    public function destroyExamen($examenId){
        DB::table('Examen')->where('id_Examen', '=',$examenId)->delete();
    }
    public function destroySession($sessionId){
         DB::table('Session')->where('id_Session', '=',$sessionId)->delete();
    }
    public function getInfoExamen($examenId){
        return Examen::where('id_Examen','=',$examenId)->first();
    }
    public function updateExamen($examenId,$id_Stage,$date,$sessionId,$max_Places,$id_Jury){
        return DB::table('Examen')
            ->where('id_Examen',$examenId)
            ->update(array(
                'date' => $date ,
                'max_Places' => $max_Places ,
                'id_Session' => $sessionId ,
                'id_Stage' => $id_Stage ,
                'id_Enseignant' => $id_Jury 


                ));
    }
    public function getInfoSession($sessionId){
        return Session::where('id_Session','=',$sessionId)->first();
    }
    public function getMedObserSession($sessionId){
        return Enseignant::join('Session_Medecin','Session_Medecin.id_Enseignant','=','Enseignant.id_Enseignant')
            ->where('Session_Medecin.id_Session','=',$sessionId)
            ->get();
    }
    public function updateSession($sessionId,$nom,$id_Niveau){
         return DB::table('Session')
            ->where('id_Session',$sessionId)
            ->update(array(
                'nom' => $nom ,
                'id_Niveau' => $id_Niveau 
                ));
    }


}