<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\API\v1\NotificationController;
use App\Http\Requests\CourseStoreRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use Exception;

class CourseController extends BaseController
{
    public function course_index()
    {
        return DB::table('courses')->get();
    }

    public function pcourse_index(Request $request)
    {

        try {

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

            $server_response = reqGest('GET','v1/profs/'.$User->matricule.'/ecues', [],2);
            if($server_response && $server_response['success']){
                $success['Ecues'] = $server_response['data'];
                return sendResponse($success, "DATA_GOT_SUCCESSFULLY");

            } else{
                return sendError("Echec getting data");
            }
        } catch (Exception $e) {
            return sendError("Request failed", $e->getMessage(), 400);
        }
    }

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

        try {
            $server_response = reqGest('GET','v1/ecues/'.secure_me($ecuId,true).'/chapitres', [],2);
            if($server_response && $server_response['success']){

                return sendResponse([
                   "Chapitres" => $server_response['data']
                ], "DATA_GOT_SUCCESSFULLY");

            } else{
                return sendError("Echec getting data");
            }
        } catch (Exception $e) {
            return sendError("Request failed", $e->getMessage(), 400);
        }
    }

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

             $User= $request->get('User');
            //  $User = 1010;
             // $server_response = getFromGest('api/v1/profs/'.$User->matricule.'/ecues', ['bd' => substr($CurrentDb, 5)])->json();
            //  $server_response = getFromGest('api/v1/profs/'.$User.'/ecues', ['bd' => substr($CurrentDb, 10)])->json();
            $server_response = reqGest('GET','v1/profs/'.$User->matricule.'/ecues', [],2);

             if($server_response && $server_response['success']){
                 $success['Ecues'] = $server_response['data'];
                 return sendResponse($success, "DATA_GOT_SUCCESSFULLY");

             } else{
                 return sendError("Echec getting data");
             }

            $ecues = DB::connection('tenant')->table('courses')
                ->where('ecu_id','=',$id)
                ->join('filieres','ecu.idFiliere','=','filieres.idFiliere')
                ->join('departement','filieres.idDepartement','=','departement.idDepartement')
                ->select('ecu.*', 'filieres.intituleFilieres', 'filieres.sigleFilieres', 'departement.sigledept', 'departement.desrdept')
                ->get();

            if($ecues){
                return sendResponse($ecues, "DATA_GOT_SUCCESSFULLY");
            }
            else{
                return sendError("NO_DATA_FOUND_FOR_PROF", 400);
            }

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

    public function store(CourseStoreRequest $request)
    {
        DB::table('commentaires')
            ->insert([
                'comment_text' => $request('comment_text'),
                'user_media_id' => $request('user_media_id'),
                'comment_id' => $request('comment_id')
            ]
        );
    }

    public function update(Request $request, $id)
    {
        DB::table('users')
            ->where('id', $id)
            ->update([
                'comment_text' => $request('comment_text'),
                'user_media_id' => $request('user_media_id'),
                'comment_id' => $request('comment_id')
            ]
        );
    }

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

    }

    //Chapitres et Media d'un ecu

    public function ecu_courses(Request $request,$ecu)
    {

        try {

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

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

                $chapitres = $server_response['data']['chapitres'];
                $chapitres_id = [];

                foreach($chapitres as $chapitre){
                    array_push($chapitres_id,$chapitre['idchapitre']);
                }

                $medias = DB::table('medias')
                ->whereIn('chap_id',$chapitres_id)
                ->get()
                ->groupBy('chap_id');

                $result = array(
                    'chapitres' => $chapitres,
                    'medias' => $medias,
                );

                return sendResponse($result,'DATA_GOT_SUCCESSFULLY');
            } else{
                return sendError($server_response['message']);
            }

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

    public function index_lesson(Request $request, $ecuId, $statut = null)
    {

        try {

            if ($statut == null) {
                $condition = [
                    ['ecu_id',$ecuId]
                ];
            } else {
                $condition = [
                    ['ecu_id',$ecuId],
                    ['statut','PUBLISHED'],
                    ['published_at','<=',Carbon::now()->toDateTimeString()]
                ];
            }

            $medias = DB::connection('tenant')->table('medias')
                ->where($condition)
                ->select('*')
                ->orderBy('ordre', 'asc')
                ->get()
                ->groupBy('chap_id');

            $medias = encryptKeys($medias);

            return sendResponse($medias, "DATA_GOT_SUCCESSFULLY");

        } catch (Exception $e) {
            return sendError("Request failed", $e->getMessage(), 400);
        }
    }

    public function store_lesson(Request $request)
    {

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

        // id ecu_id chap_id sequences titre description miniature ext url duree_video rate ordre statut published_at
        try {

            $ordre = 1;

            $ordreMax = DB::connection('tenant')
            ->table('medias')
            ->where('ecu_id', $request->ecu_id)
            ->where('chap_id', $request->chap_id)
            ->max('ordre');

            if ($ordreMax) {
                $ordre = $ordreMax+1;
            }

            $data = [
                'ecu_id' => $request->ecu_id,
                'chap_id' => $request->chap_id,
                'titre' => $request->titre,
                'description' => $request->description,
                'miniature' => $request->miniature,
                'ext' => $request->ext,
                'url' => $request->url,
                'duree_video' => $request->duree_video,
                'ordre' => $ordre,
                'statut' => 'PUBLISHED',
                'downloadable' => $request->downloadable,
                'published_at' => $request->published_at
            ];

            if ($request->sequences) {
                $data['sequences'] = $request->sequences;
            }

            $id = DB::connection('tenant')->table('medias')->insertGetId($data);

            if($id){
                $request['user_id'] = $userId;
                $request['type'] = "MEDIA";
                $request['media_id'] = $id;
                
                // TODO : Make notif process async toward comments !
                // send notif
                $notif = new NotificationController();
                $result = $notif->store_notification($request); 

                return sendResponse([], "DATA_SET_SUCCESSFULLY");
            } else {
                return sendError("DATA_NOT_SET", 400);
            }

        } catch (Exception $e) {
            return sendError("Request failed", $e->getMessage(), 400);
        }
    }

    public function reorder_lesson(Request $request)
    {
        try {
            $media_ids = array_values($request->ordres);

            // get min order of chap medias
            $min_ordre = DB::connection('tenant')->table('medias')
            ->whereIn("id", $media_ids)
            ->min("ordre")
            ;

            // set new order
            $i = 0;
            foreach ($media_ids as $key => $id) {
                DB::connection('tenant')->table('medias')
                ->where('id', $id)
                ->update([
                    'ordre' => $min_ordre + $i
                ]);

                $i++;
            }

            return sendResponse([], "DATA_ORDERED_SUCCESSFULLY");

        } catch (Exception $e) {
            return sendError("Request failed", $e->getMessage(), 400);
        }
    }

    public function update_lesson(Request $request, $id)
    {
        try {
            $newVersion = $request->lesson;
            
            $oldVersion = DB::connection('tenant')->table('medias')
            ->where('id', $id)
            ->first();
            $oldVersion = json_decode(json_encode($oldVersion), true);

            // is media's chapter changing  ?
            if ($oldVersion["chap_id"] != $newVersion["chap_id"]) {
                // Let's assign it its position in new chap
                $ordre = 1;
                
                $chapMaxOrdre = DB::connection('tenant')->table('medias')
                ->where('ecu_id', $newVersion["ecu_id"])
                ->where('chap_id', $newVersion["chap_id"])
                ->max("ordre");

                if ($chapMaxOrdre) {
                    $ordre = $chapMaxOrdre + 1;
                }

                $newVersion["ordre"] = $ordre;
            }
            
            // update the media's data in DB first
            DB::connection('tenant')->table('medias')
            ->where('id', $id)
            ->update($newVersion);

            // As we successfully saved newVersion, let's reoder media's old chap items
            // by decreasing the position of all media that came right after the old position
            // of our current media
            if ($oldVersion["chap_id"] != $newVersion["chap_id"]) {
                $decrease_media_ordre = DB::connection('tenant')->table('medias')
                ->where('ecu_id', $oldVersion["ecu_id"])
                ->where('chap_id', $oldVersion["chap_id"])
                ->where('ordre', '>',$oldVersion["ordre"])
                ->get()
                ;
    
                foreach ($decrease_media_ordre as $key => $m) {
                    DB::connection('tenant')->table('medias')
                    ->where('id', $m->id)
                    ->update([
                        'ordre' => $m->ordre - 1
                    ]);
                }
            }

            // notif 
            // TODO : uncomment this ? only if published_at changed
            // $request['user_id'] = $userId;
            // $request['type'] = "MEDIA";
            // $request['media_id'] = $id;
            // $request['ecu_id'] = $media->ecu_id;

            // $notif = new NotificationController();
            // $result = $notif->store_notification($request);

            return sendResponse([], 'lesson update successfully');
        } catch (Exception $e) {
            return sendError('Error Updating lesson with id '.$id, ' '.$e->getMessage());
        }
    }

    public function delete_lesson(Request $request, $id)
    {
        try {
            $lesson = DB::connection('tenant')->table('medias')->where('id', $id)->delete();
            return sendResponse([], 'lesson deleted well');
        } catch (Exception $e) {
            return sendError('Error deleting lesson with id '.$id, ' '.$e->getMessage());
        }

    }


    // Prendre les quizs

    public function get_quizzes (Request $request, $chap_id) {

        try {

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

            // Verifier si l'utilisateur a deja fait les quizs une fois
            $hadDoneQuiz = DB::connection('tenant')
                ->table('user_chapitres')
                ->where('user_id',$userId)
                ->where('chap_id',$chap_id)
                ->exists();

            if (!$hadDoneQuiz) {

                $server_response = reqGest('GET','v1/chapitres/'.secure_me($chap_id).'/quizs',[],2);
                if($server_response && $server_response['success']){

                    $data = $server_response['data'];

                    if (count($data['qcms']) != 0) {

                        DB::connection('tenant')
                        ->table('user_chapitres')
                        ->insert([
                            'user_id' => $userId,
                            'chap_id' => $chap_id
                        ]);
                    }

                    $data["status"] = true;

                    return sendResponse($data,'DATA_GOT_SUCCESSFULLY');

                } else  {

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

                }

            } else {

                return sendResponse([
                    'status' => false,
                    'qcms' => [],
                    'reponses' => [],
                ],'DATA_GOT_SUCCESSFULLY');

            }

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

    }

 }
