<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Support\Facades\DB;
use App\Services\RandomFiliereService;

class ElearningController extends Controller
{
    public function index()
    {
        try {

            $annee_acad = current_acad();

            // DEPARTEMENTS, DOMAINS & MENTIONS for filter
            $deps = DB::connection('tenant')->table('departement')->where('afficher', "YES")->get();

            // take only mentions that have filieres linked to them
            $idMentions = DB::connection('tenant')->table('filieres')
            ->pluck("idMention")
            ->toArray();

            // FIXME : Remove this static thing later !
            // $staticDomaines = [
            //     [
            //         "idDomaine" => 1,
            //         "sigleDomaine" => "Sciences de la Santé",
            //     ], [
            //         "idDomaine" => 9,
            //         "sigleDomaine" => "Sciences de l'Information et de la Communication",
            //     ], [
            //         "idDomaine" => 10,
            //         "sigleDomaine" => "Sciences et Techniques",
            //     ],
            // ];

            $temp = DB::table('mention')
            ->whereIn("idDomaine", [1,9,10])
            ->pluck("idMention")
            ->toArray();

            $idMentions = array_merge($idMentions, $temp);
            // FIXME : Remove this static thing above later !
            

            $mentions = DB::table('mention')
            ->whereIn("idMention", $idMentions)
            ->get()
            ->groupBy('idDomaine');

            // fetch only the domaines that have mentions previously taken
            $domaines = DB::table('domaine')
            ->whereIn("idDomaine", array_keys($mentions->toArray()))
            ->get();

            // six random filieres  for school
            $filieres = RandomFiliereService::index();

            // get all ecs for some later requests
            $all_ecs = DB::connection('tenant')
            ->table('ecu')
            ->where('annee_acad', '=', $annee_acad)
            ->get();

            /*
                GET 3 random ECs of the school,
                the prof in charge and the number of students for each of them.

                *- BEWARE ! You can't do a for loop over these items because the key are not
                always in a consecutive order
            */
            $shuffled_ecs = DB::connection('tenant')
            ->table('ecu')
            ->where('annee_acad', '=', $annee_acad)
            ->inRandomOrder()
            ->get()
            ->unique('code_ecu')
            ->unique('matricule') // to not have the same prof twice
            ;

            $ecs = []; $i = 0;
            $MAX_TO_TAKE = min(3, $shuffled_ecs->count());
            foreach ($shuffled_ecs as $key => $shuffled_ec) {
                // get the ec
                $ecs[] = $shuffled_ec;

                // add prof's details
                $prof = DB::connection('tenant')->table('enseignant')
                    ->where('matricule', $ecs[$i]->matricule)
                    ->first()
                ;
                // $prof->{"pp_url"} = getFullPPPath($prof->cheminPhoto, 4);

                $ecs[$i]->{"prof"} = [
                    "nom" => $prof->nom,
                    "prenom" => $prof->prenom,
                    "pp_url" => getFullPPPath($prof->cheminPhoto, 4),
                ];

                // number of students of the course
                $ecs[$i]->{"total_etu"} = DB::connection('tenant')->table('tabinscriunite')
                ->where('inscription_actuelle','=',$annee_acad)
                ->where('code_unite','=',$ecs[$i]->code_unite)
                ->count()
                ;

                // Let's compose a description with the fields available 
                $desc = "";
                if ($ecs[$i]->masse_horaire) {
                    $desc = "Pour une durée totale de ". $ecs[$i]->masse_horaire. " heures, ";
                    if ($ecs[$i]->travaux_pratiques + $ecs[$i]->cours_theorique) {
                        switch ($ecs[$i]->travaux_pratiques + $ecs[$i]->cours_theorique) {
                            case $ecs[$i]->travaux_pratiques:
                                $desc .= "le cours est purement pratique et les travaux portent sur : ". $ecs[$i]->intituleEcu. ".";
                                break;

                            case $ecs[$i]->cours_theorique:
                                $desc .= "le cours est purement théorique et est axé sur les chapitres liés à : ". $ecs[$i]->intituleEcu. ".";
                                break;

                            case $ecs[$i]->masse_horaire:
                                $desc .= "le cours est à ". number_format(100*($ecs[$i]->travaux_pratiques/$ecs[$i]->masse_horaire), 2). "% pratiques et à ". number_format(100*($ecs[$i]->cours_theorique/$ecs[$i]->masse_horaire), 2). "% théoriques.\nIl est axé sur les chapitres liés à : ". $ecs[$i]->intituleEcu. ".";
                                break;

                            default:
                                $desc .= "l'apprenant est suivi à ". number_format(100*($ecs[$i]->travaux_diriges/$ecs[$i]->masse_horaire), 2). "% à travers des travaux dirigés sur les chapitres liés à : ". $ecs[$i]->intituleEcu. ".";
                                break;
                        }
                    } else {
                        $desc .= "la formation est axée sur les points essentiels en ".$ecs[$i]->intituleEcu. ".";
                    }
                } else {
                    $desc .= "Le cours est purement défini pour l'immersion dans le monde professionnelle.";
                }
                $ecs[$i]->{"description"} = $desc;

                $i++;
                if ($i >= $MAX_TO_TAKE) {
                    break;
                }
            }

            /*
                GET 4 random temporary ECs of the school
                + nb of chap, of students & prof !
            */
            $temp_ecs = DB::connection('tenant')
            ->table('cours_temporaire')
            ->where('cours_temporaire.annee_acad', '=', $annee_acad)
            ->inRandomOrder()
            ->limit(4)
            ->join('ecu','cours_temporaire.ecu_id','=','ecu.idEC')
            ->join('unites', function($join)
            {
                $join->on('ecu.code_unite', '=', 'unites.code_unite');
                $join->on('ecu.idFiliere','=','unites.idFiliere');
                $join->on('ecu.annee','=','unites.annee');
                $join->on('ecu.niveauFormation','=','unites.niveauFormation');
                $join->on('ecu.annee_acad','=','unites.annee_acad');
            })
            ->select("ecu.*","unites.intituleUnite", "cours_temporaire.montant as montant_cours")
            ->get()
            ;

            foreach ($temp_ecs as $i => $temp_ec) {
                // number of chapiters
                $temp_ecs[$i]->{"total_chapitre"} = DB::connection('tenant')->table('chapitre')
                ->where('idecu','=',$temp_ecs[$i]->idEC)
                ->count();

                // number of students of the course
                $temp_ecs[$i]->{"total_etu"} = DB::connection('tenant')->table('tabinscriunite')
                ->where('inscription_actuelle','=',$annee_acad)
                ->where('code_unite','=',$temp_ecs[$i]->code_unite)
                ->count()
                ;

                // add prof's details
                $prof = DB::connection('tenant')->table('enseignant')
                ->where('matricule', $temp_ecs[$i]->matricule)
                ->first()
                ;

                $temp_ecs[$i]->{"prof"} = [
                    "nom" => $prof->nom,
                    "prenom" => $prof->prenom,
                    "pp_url" => getFullPPPath($prof->cheminPhoto, 4),
                ];
            }

            // take 6 random teachers
            $profs = DB::connection('tenant')->table('enseignant')
            ->where('enfonction','YES')
            ->where('cheminPhoto','!=','enseignantImages/profil.png') // FIXME : NEED to provide good img for those lecturer
            ->inRandomOrder()
            ->limit(6)
            ->get();

            for ($i=0; $i < count($profs); $i++) {
                $profs[$i]->{"pp_url"} = getFullPPPath($profs[$i]->cheminPhoto, 4);

                $profs[$i]->{"grade"} = DB::table('grade')
                ->where('idGrade', $profs[$i]->idGrade)
                // ->select("sigleGrade", "nomGrade")
                ->first()
                ->nomGrade
                ;
            }

            // Let's build stats array
            $stats = [];

            // nombre d'etudiants inscrits durant l'année academique en cours
            $stats["nb_etu"] = DB::connection('tenant')->table('tabinscription')
            ->where('annee_acad','=',$annee_acad)
            ->count();

            // nombre d'enseignant faisant cours pour l'année courante
            $prof_matricules = $all_ecs->pluck("matricule")
            ->toArray();
            $stats["nb_enseignant"] =  count(array_unique($prof_matricules));

            // nb_filieres
            $stats["nb_filieres"] = DB::connection('tenant')->table('filieres')->count();

            // nb_ues
            $stats["nb_ues"] = DB::connection('tenant')->table('unites')
            ->where('annee_acad', '=', $annee_acad)
            ->get()
            ->unique('code_unite')
            ->count();

            // nb_ecs
            $stats["nb_ecs"] = $all_ecs->unique('code_ecu')
            ->count()
            ;

            /*
                The number of total media will be given by elearningAPI
                To count only thoses of this year, We provide it the IDs
                of the current year's ECs.

                TODO : Is it good to send ids ? Or we should just save year of media in MEDIA table ?
            */
            $stats["nb_media"] = "TODO_ELEARNING_API";

            $meta = [];
            $meta["ecs_id"] = DB::connection('tenant')->table('ecu')
            ->where('annee_acad', '=', $annee_acad)
            ->pluck('idEC')
            ->toArray()
            ;



            return sendResponse([
                'departements' => $deps,
                'domaines' => $domaines,
                'mentions' => $mentions,
                'filieres' => $filieres,
                'ecs' => $ecs,
                'temp_ecs' => $temp_ecs,
                'stats' => $stats,
                'meta' => $meta,
                'profs' => $profs,
            ], "DATA_GOT_SUCCESSFULLY");

        } catch (Exception $e) {
            return sendError("SERVER ERROR", $e->getMessage(), 500);
            // return sendError("SERVER ERROR", [
            //         "file" => $e->getFile(),
            //         "Line" => $e->getLine(),
            //         "message" => $e->getMessage(),
            //         "trace" => $e->getTrace(),
            //     ],500
            // );
        }
    }

    public function filterFilieres(Request $request) {
        try {
            // let start filtering
            $query = DB::connection('tenant')->table('filieres');

            // departement filter
            if ($request->departement != "all") {
                $query = $query->where("idDepartement", $request->departement);
            }

            // mention & domain filter
            if ($request->mention != "all") { // for a specific mention ?
                $query = $query->where("idMention", $request->mention);
            } else {
                if ($request->domaine != "all") {
                    // get all mentions of the domain
                    $mention_ids =  DB::table('mention')
                    ->where("idDomaine", $request->domaine)
                    ->pluck('idMention')
                    ->toArray()
                    ;

                    // restrict results to mentions of provided domaine
                    $query = $query->whereIn("idMention", $mention_ids);
                }
            }

            // total_filtered
            $total_filtered = $query->count();

            // get 6 random filtered data 
            $filtered_filieres = $query->inRandomOrder()
            ->limit(6)
            ->get();

            // just as an info ...
            $all_filieres = DB::connection('tenant')->table('filieres')->get();

            return sendResponse([
                // 'all_filieres' => $all_filieres,
                'total_records' => $all_filieres->count(),
                'total_filtered' => $total_filtered,
                'filtered_filieres' => $filtered_filieres,
            ], "DATA_GOT_SUCCESSFULLY");

        } catch (Exception $e) {
            return sendError("SERVER ERROR", $e->getMessage(), 500);
        }
    }
}
