<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Http\Controllers\BaseController;
use App\Http\Requests\MediaStoreRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Exception;

class MediaController extends BaseController
{

    public function store(MediaStoreRequest $request)
    {
        try {

            DB::table('medias')
            ->insert([
                'ecu_id' => $request->ecu_id,
                'chap_id' => $request->chap_id,
                'sequences' => $request->sequences,
                'titre' => $request->titre,
                'description' => $request->description,
                'miniature' => $request->miniature,
                'ext' => $request->ext,
                'url' => $request->url,
                'duree_video' => $request->duree_video,
                'rate' => $request->rate,
                'ordre' => $request->ordre,
                'downloadable' => $request->downloadable,
            ]);
            return sendResponse([], 'DATA_INSERTED_SUCCESSFULLY');
        } catch (Exception $e) {
            return sendError("SERVER ERROR, PLEASE CONTACT ADMINISTRATOR", $e->getMessage(), 500);
        }
    }

    /**
     * Recuperer les medias recents,les chapitres et leurs auteurs
     */

    public function show_recent_medias(Request $request){

        try {

            $userId = $request->get('User')->id;

            $matricule = DB::connection('tenant')
                ->table('users')
                ->where('id',$userId)
                ->get()->first()->matricule;

            // $server_response = getFromGest('api/v1/userStudents/'.$matricule.'/ecus', ['bd' => substr($CurrentDb, 10),'option' => 'notAll'])->json();
            $server_response = reqGest('POST','v1/userStudents/'.$matricule.'/ecus', ['option' => 'notAll'],2);

            if(isset($server_response['success']) && $server_response['success'] == true){

                $ids_ecus = $server_response['data']['ids_ecus'];
                $ecus = $server_response["data"]["infos_ecus"];

            }
            else if(isset($server_response['success']) && $server_response['success'] == false){

                return sendError($server_response['message']);

            }

            $medias = DB::connection('tenant')
                ->table('medias')
                ->whereIn('ecu_id',$ids_ecus)
                ->orderByDesc('published_at')
                ->take($request->limit)
                ->get();

            $chapitres_id = array_column($medias->toArray(),"chap_id");
            $chapitres_id = array_unique($chapitres_id);

            $toSend = [];

            /*foreach ($chapitres_id as $chap) {
                array_push($toSend,$chap);
            }*/

            foreach ($chapitres_id as $key => $value) {
                $toSend["id_$key"] = $value;
            }
            $toSend = encryptable($toSend);
            // Get from GestStudent API data on chapter

            // $server_response = getFromGest('api/v1/chapitres/data',['bd' => substr($CurrentDb, 10),'chapitres' => $toSend])->json();
            $server_response = reqGest('POST','v1/chapitres/data',['chapitres' => $toSend],2);

            if(isset($server_response['success']) && $server_response['success'] == true){

                $chapitres = $server_response['data'];

                $ecuIds = $medias->pluck('ecu_id')->toArray();
                $ecuIds = array_unique($ecuIds);

                //$toSend = [];

                /*foreach ($codes_ecus as $code) {
                    array_push($toSend,$code);
                }*/

                /*foreach ($codes_ecus as $key => $value) {
                    $toSend["id_$key"] = $value;
                }*/

                // Get from GestStudent API data on ECU

                // $server_response = getFromGest('api/v1/ecus/prof',['codes_ecus' => $toSend,'bd' => substr($CurrentDb, 10)])->json();
                $server_response = reqGest('POST','v1/ecus/prof',['ecuIds' => $ecuIds],2);


                if(isset($server_response['success']) && $server_response['success'] == true){

                    $profs = $server_response['data']['prof'];

                    return sendResponse([
                        'medias' => $medias,
                        'ecus' => $ecus,
                        'chapitres' => $chapitres,
                        'profs' => $profs
                    ],
                    'DATA_GOT_SUCCESSFULLY');

                }
                else if(isset($server_response['success']) && $server_response['success'] == false){

                    return sendError($server_response['message']);

                }

            }
            else if(isset($server_response['success']) && $server_response['success'] == false){

                return sendError($server_response['message']);

            }

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

    }

    /**
     * Mettre  le statut du media visualise par un user a started ou finished
     */

    public function statut_media(Request $request,$media_id)
    {
        try {

            if($request->statut == 0){

                DB::connection('tenant')
                ->table('user_medias')
                ->insert([
                    'user_id' => $request->user_id,
                    'media_id' => $media_id,
                    'statut' => 'started'
                ]);

            }
            else if($request->statut == 1){

                DB::connection('tenant')
                ->table('user_medias')
                ->updateOrInsert(
                    [
                        'user_id' => $request->user_id,
                        'media_id' => $request->media_id,
                    ],
                    [ 'statut' => 'finished' ]
                );
            } else {
                // Nothing to do here
            }


            return sendResponse([],'DATA_INSERTED_SUCCESSFULLY');

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

    /**
     * Prendre dernier media visualise par chaque etudiant avec le statut pour un cours donne
     */

    public function last_media_visualized(Request $request, $ecuId){

        try {
            // Etudiants ayant une ECU donnee

            // $server_response = getFromGest('api/v1/ecus/'.$code_ecu.'/students_ecu', ['bd' => substr($CurrentDb, 10)])->json();
            $server_response = reqGest('GET','v1/ecus/'.secure_me($ecuId).'/students_ecu',[],2);

            if(isset($server_response['success']) && $server_response['success'] == true){

                $students_normal = $server_response['data']['students_normal'];
                $students_reprise = $server_response['data']['students_reprise'];

                //$matricules_normal = [];
                //$matricules_reprise = [];

                $students = [];
                $matricules = [];

                foreach($students_normal as $student){
                    //array_push($matricules_normal,$student['matricule']);
                    $student['reprise'] = false;
                    array_push($students,$student);
                    array_push($matricules,$student['matricule']);

                }

                foreach($students_reprise as $student){
                    //array_push($matricules_reprise,$student['matricule']);
                    $student['reprise'] = true;
                    array_push($students,$student);
                    array_push($matricules,$student['matricule']);
                }

                // Prendre l'ensemble des medias visualises par chaque etudiant pour le cours

                $medias_visualized = [];

                foreach($matricules as $matricule){

                    // Prendre l'id de l'utilisateur chez nous
                    $user = DB::connection('tenant')
                        ->table('users')
                        ->where('matricule',$matricule)
                        ->select('id')->first();

                    if ($user) { // s'il s'est connecté une fois ...
                        $nbViewed = 0;

                        // Prendre le dernier media de l'ecu visualise par l'etudiant
                        $last_ecu_media = DB::connection('tenant')
                        ->table('medias')
                        ->where('ecu_id',$ecuId)
                        ->join('user_medias','user_medias.media_id','=','medias.id')
                        ->where('user_medias.user_id',$user->id)
                        ->orderByDesc('user_medias.updated_at')
                        ->get()->first();

                        DB::connection('tenant')
                        ->table('medias')
                        ->where('ecu_id',$ecuId)
                        ->join('user_medias','user_medias.media_id','=','medias.id')
                        ->where('user_medias.user_id',$user->id)
                        ->get()
                        ->lazy()->each(function ($media, $key) use(&$nbViewed) {
                            //pourcentage pondéré
                            if ($media->statut == "finished") {
                                $nbViewed += 1;
                            } else {
                                $nbViewed += 0.5;
                            }
                        });

                        if ($last_ecu_media) {
                            $last_ecu_media->total_viewed = $nbViewed;
                        }

                        $medias_visualized[$matricule] = $last_ecu_media;
                    }

                }

                return sendResponse([
                    'students' => $students,
                    'medias_visualized' => $medias_visualized
                ],'DATA_GOT_SUCCESSFULLY');

            }
            else if(isset($server_response['success']) && $server_response['success'] == false){

                return sendError($server_response['message']);

            }

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

    }

    /**
     *  Prendre dernier media visualise par un etudiant pour un cours donne
     */

    public function last_media(Request $request,$ecuId) {
        try {

            $userId = $request->get('User')->id;

            $last_ecu_media = DB::connection('tenant')
                ->table('medias')
                ->where('ecu_id',$ecuId)
                ->join('user_medias','user_medias.media_id','=','medias.id')
                ->where('user_medias.user_id',$userId)
                ->orderByDesc('user_medias.updated_at')
                ->select(
                    'medias.id','medias.ecu_id','medias.chap_id','medias.sequences','medias.titre','medias.description','medias.miniature','medias.ext','medias.url','medias.duree_video','medias.ordre','medias.statut','medias.published_at','medias.created_at','medias.updated_at',
                    'user_medias.id as user_medias_id','user_medias.user_id','user_medias.media_id','user_medias.statut'
                )
                ->get()
                ->first();

            if($last_ecu_media){
                return sendResponse($last_ecu_media,'DATA_GOT_SUCCESSFULLY');
            }

            return sendResponse([],'DATA_GOT_SUCCESSFULLY');

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

    /**
     * Prendre tout dernier media visualise par un etudiant avec le statut de son evolution pour chaque ecu
     */

    public function get_last_viewed(Request $request) {

        try {

            $userId = $request->get('User')->id;

            $matricule = DB::connection('tenant')
                ->table('users')
                ->where('id',$userId)
                ->get()->first()->matricule;

            // $server_response = getFromGest('api/v1/userStudents/'.$matricule.'/ecus', ['bd' => substr($CurrentDb, 10),'option' => 'notAll'])->json();
            $server_response = reqGest('POST','v1/userStudents/'.$matricule.'/ecus', ['option' => 'notAll'],2);


            if(isset($server_response['success']) && $server_response['success'] == true){

                $ids_ecus = $server_response['data']['ids_ecus'];

            }
            else if(isset($server_response['success']) && $server_response['success'] == false){

                return sendError($server_response['message']);

            }

            $last_media = DB::connection('tenant')
                ->table('medias')
                ->whereIn('ecu_id',$ids_ecus)
                ->join('user_medias','user_medias.media_id','=','medias.id')
                ->where('user_medias.user_id',$userId)
                ->orderByDesc('user_medias.updated_at')
                ->get()->first();

            if($last_media){
                return sendResponse($last_media,'DATA_GOT_SUCCESSFULLY');
            }

            return sendResponse([],'DATA_GOT_SUCCESSFULLY');

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

    /**
     * Prendre les medias visualises
     */

     public function medias_visualized_lastly (Request $request) {

        try {
            $userId = $request->get('User')->id;

            $medias = DB::connection('tenant')
                ->table('user_medias')
                ->where('user_id',$userId)
                ->join('medias','medias.id','=','user_medias.media_id')
                // ->join('commentaires','commentaires.media_id','=','user_medias.media_id')
                ->take($request->limit)
                ->orderByDesc('user_medias.created_at')
                ->select('user_medias.*','medias.ecu_id','medias.chap_id',
                'medias.sequences','medias.titre','medias.description',
                'medias.miniature','medias.ext','medias.url','medias.duree_video',
                'medias.ordre','medias.is_live','medias.downloadable',
                'medias.published_at','medias.statut as medias_statut')
                ->get();

            $ecuIds = $medias->pluck('ecu_id')->toArray();

            $ecuIds = array_unique($ecuIds);

            $toSend = [];

            /*foreach ($codes_ecus as $code) {
                array_push($toSend,$code);
            }*/

            foreach ($ecuIds as $key => $value) {
                $toSend["id_$key"] = secure_me($value,true); // crypt ids b4 sending to ohter api
            }

            // Get from GestStudent API data on ECU

            // $server_response = getFromGest('api/v1/ecus/prof',['codes_ecus' => $toSend,'bd' => substr($CurrentDb, 10)])->json();
            $server_response = reqGest('POST','v1/ecus/prof',['ecuIds' => $toSend],2);


            if(isset($server_response['success']) && $server_response['success'] == true){

                $profs = $server_response['data']['prof'];

                // $server_response = getFromGest('api/v1/ecus/infos',['codes_ecus' => $toSend,'bd' => substr($CurrentDb, 10)])->json();
                $server_response = reqGest('POST','v1/ecus/infos',['ecuIds' => $toSend],2);


                if(isset($server_response['success']) && $server_response['success'] == true){

                    $ecus = $server_response['data'];

                    return sendResponse([
                        'medias' => $medias,
                        'ecus' => $ecus,
                        'profs' => $profs
                    ],'DATA_GOT_SUCCESSFULLY');

                }
                else if(isset($server_response['success']) && $server_response['success'] == false){

                    return sendError($server_response['message']);

                }

            }
            else if(isset($server_response['success']) && $server_response['success'] == false){

                return sendError($server_response['message']);

            }

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

     /**
      * Prendre les details lies a un ecu
      */
     public function ecu_media (Request $request, $ecuId) {

        try {

            $medias = DB::connection('tenant')
                ->table('medias')
                ->where('ecu_id',$ecuId)
                ->groupBy('chap_id')
                ->get();

            $chaps_ids = $medias->pluck('chap_id')->toArray();

            $toSend = [];

            foreach ($chaps_ids as $key => $value) {
                $toSend["id_$key"] = $value;
            }

            $toSend = encryptable($toSend);

            // $server_response = getFromGest('api/v1/chapitres/data',['bd' => substr($CurrentDb, 10),'chapitres' => $chaps_ids])->json();
            $server_response = reqGest('POST','v1/chapitres/data',['chapitres' => $toSend],2);

            if(isset($server_response['success']) && $server_response['success'] == true){

                $chapitres = $server_response['data'];

                return sendResponse([
                    'medias' => $medias,
                    'chapitres' => $chapitres
                ],
                'DATA_GOT_SUCCESSFULLY');

            }
            else if(isset($server_response['success']) && $server_response['success'] == false){

                return sendError($server_response['message']);

            }

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

     }

    public function get_media($mediaId) {

        try {
            $media = DB::connection('tenant')
                ->table('medias')
                ->where('id',$mediaId)
                ->get();

            return sendResponse($media,'DATA_GOT_SUCCESSFULLY');

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