<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Http\Requests\ThemeStoreRequest;
use App\Http\Requests\ThemeUpdateRequest;
use App\Http\Requests\ThemeUserDestroyRequest;
//use App\Key;
use App\Departement;
use App\Lien;
use App\Log;
use App\Theme;
use App\User;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ThemeController extends Controller
{
    /**
     * Instantiate a new PostController instance.
     *
     * @return void
     */
   /* public function __construct()
    {
        $this->middleware('verify_can_validate_theme', ['only' => ['destroy']]);
    }*/

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        try {

            $request->validate([
                'theme_statut' => 'required',
            ]);

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

            $themes = Theme::on('tenant')
                ->where('statut','=',$request->theme_statut)
                ->orderBy('niveau')
                ->get()
                ->toArray();

            if ($themes){

                $matricules  = array_unique(array_column($themes,'user_matricule'));

                $server_response = getFromGest('api/v1/users/data', ['bd' => substr(hackKey(false,$request->bd), 5),'matricules_array' => $matricules])->json();
                if ($server_response['success']){

                    $profs = $server_response['data'];

                    return response()->json([
                        'status' => 'success',
                        'themes' => $themes,
                        'profs' => $profs
                    ])->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);
                }else{

                    return response()->json([
                        'status' => 'error',
                        'message' => $server_response['message']
                    ])->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);
                }
            }
            else{

                return response()->json([
                    'status' => 'success',
                    'themes' => array(),
                    'profs' => array()
                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }

            /*

            $statut_array = ['SOUTENU','PUBLISHED','PENDING','SIGNALED'];

            $themes_array = array();

            foreach($statut_array as $statut){
                $themes = DB::connection('tenant')->table('themes')->where('statut','=',$statut)->where('departement_id','=',hackKey(false, $request->departement))->get();
                $themes = $themes->toArray();

                $matricules = array_unique(array_column($themes,'user_matricule'));

                $server_response = getFromGest('api/v1/users/data', ['bd' => substr(hackKey(false,$request->bd), 5),'matricules_array' => $matricules])->json();
                if ($server_response['success']){

                    $profs = $server_response['data'];

                    foreach($themes as $index => $theme)
                    {
                        $theme = json_decode(json_encode($theme), true);

                        $theme["prof"] = $profs[$theme['user_matricule']];
                        $themes[$index] = $theme;

                    }
                }

                $themes_array[$statut] = $themes;

            }

            return response()->json([
                'status' => 'success',
                'themes' => $themes_array,
            ])->withHeaders([
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ]);
            */

        } catch (Exception $e) {

            return response()->json([
                'status' => 'error',
                'message' => $e->getMessage()
            ], 404)->withHeaders([
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ]);

        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(ThemeStoreRequest $request)
    {
        try {
            
            $SchoolDepInfo= $request->get('SchoolDep');
            $departement = $SchoolDepInfo['departement_id'];
            $bd = $SchoolDepInfo['etablissement_id']."_".$departement;
            $User= $request->get('User');


            //Creation of the theme
            $theme = new Theme('tenant');
            $theme->titre = $request->titre;
            $theme->objectif = $request->objectif;
            $theme->departement_id = $departement;
            $theme->filiere_id = $request->filiere_id;
            $theme->description = $request->description;
            $theme->niveau = $request->niveau;
            $theme->user_matricule = $User->matricule;
            $theme->statut = 'PENDING';
            $theme->save();

            //Sauvegarder l'opération
            save_log($bd, 'THEME CREATE', json_encode($theme), $User->matricule);

            //Store links if provided
            if ($request->liens) {
                foreach ($request->liens as $lien) {
                    $li = new Lien('tenant');
                    $li->url = $lien;
                    $li->theme()->associate($theme);
                    $li->statut = 'PENDING';
                    $li->save();

                    //Sauvegarder l'opération
                    save_log($bd, 'LIEN CREATE', json_encode($li), $User->matricule);
                }
            }

            return response()->json([
                'status' => 'success',
                'theme' => 'THEME_CREATED'
            ])->withHeaders([
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ]);
        } catch (Exception $e) {
            //Sauvegarder l'opération
            save_log($bd, 'THEME CREATE', $e->getMessage(), $User->matricule);

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

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request,$id)
    {
        try {

            $theme = DB::connection('tenant')->table('themes')
            ->where('themes.id','=',$id)
            ->get();


            $liens = DB::connection('tenant')->table('themes')
            ->where('themes.id','=',$id)
            ->join('liens','themes.id','=','liens.theme_id')
            ->select('liens.*')
            ->get()
            ->toArray()
            ;

            return response()->json([
                'status' => 'success',
                'theme' => $theme,
                'liens' => $liens,
            ])->withHeaders([
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ]);

        } catch (Exception $e) {

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

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(ThemeUpdateRequest $request, $id)
    {
        try {

            $SchoolDepInfo= $request->get('SchoolDep');
            $departement = $SchoolDepInfo['departement_id'];
            $bd = $SchoolDepInfo['etablissement_id']."_".$departement;
            $User= $request->get('User');


            //Update of the theme
            $theme = Theme::on('tenant')->findOrFail($id);

            //Verify if the user requesting is the owner of the theme bound
            if ($theme->user_matricule == $User->matricule || $User->type_user == 6) {
                if (isset($request->titre)) {
                    $theme->titre = $request->titre;
                }

                if (isset($request->objectif)) {
                    $theme->objectif = $request->objectif;
                }

                if (isset($request->description)) {
                    $theme->description = $request->description;
                }

                if (isset($request->statut)){
                    $theme->statut = $request->statut;
                }

                if (isset($request->niveau)){
                    $theme->niveau = $request->niveau;
                }

                if (isset($request->filiere_id)){
                    $theme->filiere_id = $request->filiere_id;
                }

                $theme->update();

                //Sauvegarder l'opération
                save_log($bd, 'THEME UPDATE', json_encode($theme),  $User->matricule);

                return response()->json([
                    'status' => 'success',
                    'theme' => $theme
                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            } else {
                //Sauvegarder l'opération
                save_log($bd, 'THEME UPDATE', 'PERMISSIONS NOT GRANTED', $User->matricule);

                return response()->json([
                    'status' => 'error',
                    'message' => 'Permissions not granted'
                ], 404)->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }
        } catch (Exception $e) {
            //Sauvegarder l'opération
            save_log($bd, 'THEME UPDATE', $e->getMessage(),  $User->matricule);

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, $id)
    {
        try {


           // $departement = hackKey(false, $request->departement);
            //$User= $request->get('User');
            $User= $request->get('User');

            //Get the theme and it liens
            $theme = Theme::on('tenant')->findOrFail($id);
            $liens = Lien::on('tenant')->where('theme_id', '=', $theme->id)->get();
            $theme_users = DB::connection('tenant')->table('theme_user')->where('theme_id', '=', $theme->id)->get();

            //Verify if the user requesting is the owner of the theme
            if ($theme->user_matricule == $User->matricule || $User->type_user == 6) {

                //Verify if the mode of deletion is provided and is set to strict to remove article and its sections
                if ($request->mode != null && $request->mode == 'strict') {
                    //Sauvegarder l'opération
                   // save_log($bd, 'THEME DELETE STRICT', json_encode($theme), $request->matricule);

                    $theme->delete();

                    return response()->json([
                        'status' => 'success',
                        'message' => 'THEME_DELETE_STRICT'
                    ])->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);
                } else {
                    //Verify if the theme is already deleted
                    if ($theme->statut == 'DELETED') {
                        //Sauvegarder l'opération
                       // save_log($bd, 'THEME DELETE', 'THEME ALREADY DELETED', $request->matricule);

                        return response()->json([
                            'status' => 'success',
                            'message' => 'THEME_ALREADY_DELETED'
                        ], 404)->withHeaders([
                            'Accept' => 'application/json',
                            'Content-Type' => 'application/json'
                        ]);
                    }

                    //Set statut of the theme to DELETED
                    $theme->statut = 'DELETED';

                    //Set statut of related links to DELETED
                    foreach ($liens as $lien) {
                        $lien->statut = 'DELETED';
                        $lien->update();

                        //Sauvegarder l'opération
                       // save_log($bd, 'LIEN DELETE', json_encode($lien), $request->matricule);
                    }

                    //Set statut of related theme_user to DELETED
                    foreach ($theme_users as $theme_user) {
                        DB::connection('tenant')
                            ->table('theme_user')
                            ->where('id', $theme_user->id)
                            ->update([
                                'statut' => 'DELETED'
                            ]);

                        //Sauvegarder l'opération
                      //  save_log($bd, 'THEME_USERS DELETE', json_encode(DB::connection('tenant')->table('theme_user')->where('id', $theme_user->id)->first()), $User->matricule);
                    }

                    $theme->update();

                    //Sauvegarder l'opération
                  //  save_log($bd, 'THEME DELETE', json_encode($theme), $request->matricule);

                    return response()->json([
                        'status' => 'success',
                        'message' => 'THEME_DELETE'
                    ])->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);
                }
            } else {
                //Sauvegarder l'opération
               // save_log($bd, 'THEME DELETE', 'PERMISSIONS NOT GRANTED', $request->matricule);

                return response()->json([
                    'status' => 'error',
                    'message' => "Permissions not granted"
                ], 404)->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }
        } catch (Exception $e) {
            //Sauvegarder l'opération
           // save_log($bd, 'THEME DELETE', $e->getMessage(), $request->matricule);

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

    public function valider_theme(Request $request, $id)
    {
        try {
            
            $User= $request->get('User');

            $theme = Theme::on('tenant')->findOrFail($id);
            $liens = Lien::on('tenant')->where('theme_id', '=', $theme->id)->get();

            $theme->statut = 'PUBLISHED';
            $theme->validated_by = $User->matricule;

            //Set statut of related links to DELETED
            foreach ($liens as $lien) {
                $lien->statut = 'PUBLISHED';
                $lien->update();

                //Sauvegarder l'opération
              //  save_log($bd, 'VALIDER THEME LIENS', json_encode($lien), $User->matricule);
            }

            $theme->update();

            //Sauvegarder l'opération
           // save_log($bd, 'VALIDER THEME', json_encode($theme), $User->matricule);

            return response()->json([
                'status' => 'success',
                'message' => 'VALIDER_THEME_DONE'
            ])->withHeaders([
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ]);
        } catch (Exception $e) {
            //Sauvegarder l'opération
           // save_log($bd, 'VALIDER THEME', $e->getMessage(), $User->matricule);

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

    public function choisir_theme(Request $request, $id)
    {
        try {
            
            $SchoolDepInfo= $request->get('SchoolDep');
            $departement = $SchoolDepInfo['departement_id'];
            $bd = $SchoolDepInfo['etablissement_id']."_".$departement;
            $User= $request->get('User');

            //Get the theme and it liens
            $theme = Theme::on('tenant')->findOrFail($id);

            if ($theme->statut != 'PUBLISHED') {
                //Sauvegarder l'opération
                save_log($bd, 'CHOISIR THEME', 'THEME NON VALIDE', $User->matricule);

                return response()->json([
                    'status' => 'error',
                    'message' => 'THEME_NON_VALIDE'
                ], 404)->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }

            if (
                DB::connection('tenant')
                ->table('theme_user')
                ->where('theme_id', '=', $theme->id)
                ->where('user_matricule', '=', $User->matricule)
                ->get()
                ->count() > 0
            ) {
                //Sauvegarder l'opération
                save_log($bd, 'CHOISIR THEME', 'THEME ALREADY TAKEN', $User->matricule);

                return response()->json([
                    'status' => 'error',
                    'message' => 'THEME_ALREADY_TAKEN'
                ], 404)->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            } else {
                DB::connection('tenant')->table('theme_user')->insert([
                    'theme_id' => $theme->id,
                    'user_matricule' => $User->matricule,
                    'statut' => '1'
                ]);

                //Sauvegarder l'opération
                save_log($bd, 'CHOISIR THEME', 'THEME CHOOSE DONE', $User->matricule);

                return response()->json([
                    'status' => 'success',
                    'message' => 'THEME_CHOOSE_DONE'
                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }
        } catch (Exception $e) {
            save_log($bd, 'CHOISIR THEME', $e->getMessage(), $User->matricule);

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

    public function attribution_theme(Request $request, $id)
    {
        try {
            $User= $request->get('User');

            $theme = Theme::on('tenant')->findOrFail($id);

            if($request->action == "valider")
            {
                DB::connection('tenant')
                ->table('theme_user')
                ->where('theme_id', '=', $theme->id)
                ->where('user_matricule', '=', $request->matricule)
                ->update([
                    'statut' => 'ACTIVATED'
                ]);

                $theme->statut = "TAKEN";
                $theme->update();

            }
            elseif($request->action == "rejeter")
            {
                DB::connection('tenant')
                ->table('theme_user')
                ->where('theme_id', '=', $theme->id)
                ->where('user_matricule', '=', $request->matricule)
                ->update([
                    'statut' => 'REJECTED'
                ]);
                $theme->statut = "PUBLISHED";
                $theme->update();
            }
            elseif($request->action == "attribuer")
            {
                DB::connection('tenant')
                ->table('theme_user')
                ->insert(['theme_id' => $theme->id, 'user_matricule' => $request->matricule, 'statut' => 'ACTIVATED']);

                $theme->statut = "TAKEN";
                $theme->update();
            }
            elseif($request->action == "soutenu")
            {
                DB::connection('tenant')
                ->table('theme_user')
                ->where('theme_id', '=', $theme->id)
                ->where('user_matricule', '=', $request->matricule)
                ->update([
                    'statut' => 'TAKEN'
                ]);

                $theme->statut = "SOUTENU";
                $theme->update();
            }
            else
            {
                return response()->json([
                    'status' => 'error',
                    'message' => "Action désirée non existante"
                ], 400)->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }

            return response()->json([
                'status' => 'success',
                'message' => "Action completed successfully"
            ], 400)->withHeaders([
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ]);

            //$user = User::on('tenant')->where('token', '=', $request->header('UserToken'))->get()->first();

            //Get the theme and it liens
            /*
            $theme = Theme::on('tenant')->findOrFail($id);
            $theme_user = DB::connection('tenant')
                ->table('theme_user')
                ->where('theme_id', '=', $theme->id)
                ->where('user_matricule', '=', $request->matricule)
                ->get()->first();

            if ($theme_user == null) {
                //Sauvegarder l'opération
                //save_log($bd, 'VALIDER CHOIX', 'CHOICE NOT FOUND', $User->matricule);


                return response()->json([
                    'status' => 'error',
                    'message' => 'CHOICE_NOT_FOUND'
                ], 404)->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }

            if ($theme_user->statut != 'ACTIVATED') {
                DB::connection('tenant')
                    ->table('theme_user')
                    ->where('theme_id', '=', $theme->id)
                    ->where('user_matricule', '=', $User->matricule)
                    ->update([
                        'statut' => 'ACTIVATED'
                    ]);

                    $theme->statut = "TAKEN";
                    $theme->update();

                //Sauvegarder l'opération
                save_log($bd, 'VALIDER CHOIX', 'CHOICE ACTIVATED', $User->matricule);

                return response()->json([
                    'status' => 'success',
                    'message' => 'CHOICE_ACTIVATED'
                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            } else {
                //Sauvegarder l'opération
                save_log($bd, 'VALIDER CHOIX', 'CHOICE ALREADY VALIDATED', $User->matricule);

                return response()->json([
                    'status' => 'error',
                    'message' => 'CHOICE_ALREADY_VALIDATED'
                ], 404)->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }
            */
        } catch (Exception $e) {
            //Sauvegarder l'opération
            //save_log($bd, 'VALIDER CHOIX', $e->getMessage(), $User->matricule);

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

    public function rejeter_choix(Request $request, $id)
    {
        try {
            
            $SchoolDepInfo= $request->get('SchoolDep');
            $departement = $SchoolDepInfo['departement_id'];
            $bd = $SchoolDepInfo['etablissement_id']."_".$departement;
            $User= $request->get('User');


            //Get the theme and it liens
            $theme = Theme::on('tenant')->findOrFail($id);
            $theme_user = DB::connection('tenant')
                ->table('theme_user')
                ->where('theme_id', '=', $theme->id)
                ->where('user_matricule', '=', $User->matricule)
                ->get()->first();

            if ($theme_user == null) {
                //Sauvegarder l'opération
                save_log($bd, 'REJETER CHOIX', 'CHOICE NOT FOUND', $User->matricule);

                return response()->json([
                    'status' => 'error',
                    'message' => 'CHOICE_NOT_FOUND'
                ], 404)->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }

            if ($theme_user->statut != 'REJECTED') {
                DB::connection('tenant')
                    ->table('theme_user')
                    ->where('theme_id', '=', $theme->id)
                    ->where('user_matricule', '=', $User->matricule)
                    ->update([
                        'statut' => 'REJECTED'
                    ]);

                //Sauvegarder l'opération
                $log = new Log();
                $log->bd = $bd;
                $log->operation = 'REJETER CHOIX';
                $log->description = 'CHOICE REJECTED';
                $log->user_matricule = $User->matricule;
                $log->save();

                return response()->json([
                    'status' => 'success',
                    'message' => 'CHOICE_REJECTED'
                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            } else {
                //Sauvegarder l'opération
                $log = new Log();
                $log->bd = $bd;
                $log->operation = 'REJETER CHOIX';
                $log->description = 'CHOICE ALREADY REJECTED';
                $log->user_matricule = $User->matricule;
                $log->save();

                return response()->json([
                    'status' => 'error',
                    'message' => 'CHOICE_ALREADY_REJECTED'
                ], 404)->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }
        } catch (Exception $e) {
            //Sauvegarder l'opération
            $log = new Log();
            $log->bd = $bd;
            $log->operation = 'REJETER CHOIX';
            $log->description = $e->getMessage();
            $log->user_matricule = $User->matricule;
            $log->save();

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

    public function soutenu(Request $request, $id)
    {
        try {
            
            $SchoolDepInfo= $request->get('SchoolDep');
            $departement = $SchoolDepInfo['departement_id'];
            $bd = $SchoolDepInfo['etablissement_id']."_".$departement;
            $User= $request->get('User');

            //Get the theme and it liens
            $theme = Theme::on('tenant')->findOrFail($id);
            $theme_user = DB::connection('tenant')
                ->table('theme_user')
                ->where('theme_id', '=', $theme->id)
                ->where('user_matricule', '=', $User->matricule)
                ->get()->first();

            if ($theme_user == null) {
                //Sauvegarder l'opération
                $log = new Log();
                $log->bd = $bd;
                $log->operation = 'SOUTENU';
                $log->description = 'CHOICE NOT FOUND';
                $log->user_matricule = $User->matricule;
                $log->save();

                return response()->json([
                    'status' => 'error',
                    'message' => 'CHOICE_NOT_FOUND'
                ], 404)->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }

            if ($theme_user->statut != 'TAKEN') {
                DB::connection('tenant')
                    ->table('theme_user')
                    ->where('theme_id', '=', $theme->id)
                    ->where('user_matricule', '=', $User->matricule)
                    ->update([
                        'statut' => 'TAKEN'
                    ]);

                //Sauvegarder l'opération
                $log = new Log();
                $log->bd = $bd;
                $log->operation = 'SOUTENU';
                $log->description = 'CHOICE TAKEN';
                $log->user_matricule = $User->matricule;
                $log->save();

                return response()->json([
                    'status' => 'success',
                    'message' => 'CHOICE_TAKEN'
                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            } else {
                //Sauvegarder l'opération
                $log = new Log();
                $log->bd = $bd;
                $log->operation = 'SOUTENU';
                $log->description = 'CHOICE ALREADY TAKEN';
                $log->user_matricule = $User->matricule;
                $log->save();

                return response()->json([
                    'status' => 'error',
                    'message' => 'CHOICE_ALREADY_TAKEN'
                ], 404)->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }
        } catch (Exception $e) {
            //Sauvegarder l'opération
            $log = new Log();
            $log->bd = $bd;
            $log->operation = 'SOUTENU';
            $log->description = $e->getMessage();
            $log->user_matricule = $User->matricule;
            $log->save();

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

    public function supprimer_choix(ThemeUserDestroyRequest $request, $id)
    {
        try {
            
            $SchoolDepInfo= $request->get('SchoolDep');
            $departement = $SchoolDepInfo['departement_id'];
            $bd = $SchoolDepInfo['etablissement_id']."_".$departement;

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

            //Get the theme and it liens
            $theme = Theme::on('tenant')->findOrFail($id);
            $theme_user = DB::connection('tenant')
                ->table('theme_user')
                ->where('theme_id', '=', $theme->id)
                ->where('user_matricule', '=', $User->matricule)
                ->get()->first();

            if ($theme_user == null) {
                //Sauvegarder l'opération
                $log = new Log();
                $log->bd = $bd;
                $log->operation = 'SUPPRIMER CHOIX';
                $log->description = 'CHOICE NOT FOUND';
                $log->user_matricule = $User->matricule;
                $log->save();

                return response()->json([
                    'status' => 'error',
                    'message' => 'CHOICE_NOT_FOUND'
                ], 404)->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }

            if ($theme_user->statut != 'DELETED') {
                if ($request->mode != null && $request->mode == 'strict') {
                    //Sauvegarder l'opération
                    $log = new Log();
                    $log->bd = $bd;
                    $log->operation = 'SUPPRIMER CHOIX';
                    $log->description = json_encode($theme);

                    DB::connection('tenant')
                        ->table('theme_user')
                        ->where('theme_id', '=', $theme->id)
                        ->where('user_matricule', '=', $User->matricule)
                        ->delete();

                    $log->user_matricule = $User->matricule;
                    $log->save();

                    return response()->json([
                        'status' => 'success',
                        'message' => 'CHOICE_DELETE_STRICT'
                    ])->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);
                } else {
                    DB::connection('tenant')
                        ->table('theme_user')
                        ->where('theme_id', '=', $theme->id)
                        ->where('user_matricule', '=', $User->matricule)
                        ->update([
                            'statut' => 'DELETED'
                        ]);

                    //Sauvegarder l'opération
                    $log = new Log();
                    $log->bd = $bd;
                    $log->operation = 'SUPPRIMER CHOIX';
                    $log->description = 'CHOICE DELETE';
                    $log->user_matricule = $User->matricule;
                    $log->save();

                    return response()->json([
                        'status' => 'success',
                        'message' => 'CHOICE_DELETE'
                    ])->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);
                }
            } else {
                //Sauvegarder l'opération
                $log = new Log();
                $log->bd = $bd;
                $log->operation = 'SUPPRIMER CHOIX';
                $log->description = 'CHOICE ALREADY DELETED';
                $log->user_matricule = $User->matricule;
                $log->save();

                return response()->json([
                    'status' => 'error',
                    'message' => 'CHOICE_ALREADY_DELETED'
                ], 404)->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }
        } catch (Exception $e) {
            //Sauvegarder l'opération
            $log = new Log();
            $log->bd = $bd;
            $log->operation = 'SUPPRIMER CHOIX';
            $log->description = $e->getMessage();
            $log->user_matricule = $User->matricule;
            $log->save();

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

    public function etudiants_theme(Request $request){

        try {

            $request->validate([
                'statut' => 'required'
            ]);

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

            //$departement = hackKey(false, $request->departement);

            /*$data = DB::connection('tenant')->table('theme_user')
                ->select('theme_id','user_matricule')
                ->where('statut','=',$request->statut)
                ->get()
                //->groupBy('user_matricule')
                ->toArray();*/

            $data = DB::connection('tenant')->table('theme_user')
                ->where('theme_user.statut','=',$request->statut)
                ->join('themes','theme_user.theme_id','=','themes.id')
                ->select('themes.*','theme_user.user_matricule as matricule_etudiant','themes.user_matricule as matricule_prof')
                ->orderBy('themes.niveau')
                ->get()
                ->toArray()
                ;

            if($data){

                $matricules_etudiants = array_column($data,'matricule_etudiant');
                $server_response_1 = getFromGest('api/v1/users_student/data', ['bd' => substr(hackKey(false,$request->bd), 5),'matricules_array' => $matricules_etudiants])->json();

                if ($server_response_1['success']){

                    $etudiants = $server_response_1['data'];

                    $matricules_profs = array_column($data,'matricule_prof');
                    $server_response_2 = getFromGest('api/v1/users/data', ['bd' => substr(hackKey(false,$request->bd), 5),'matricules_array' => $matricules_profs])->json();

                    if ($server_response_2['success']){

                        $profs = $server_response_2['data'];

                        return response()->json([
                            'status' => 'success',
                            'themes' => $data,
                            'etudiants' => $etudiants,
                            'profs' => $profs
                        ])->withHeaders([
                            'Accept' => 'application/json',
                            'Content-Type' => 'application/json'
                        ]);

                    }else{

                        return response()->json([
                            'status' => 'error',
                            'message' => $server_response_2['message']
                        ])->withHeaders([
                            'Accept' => 'application/json',
                            'Content-Type' => 'application/json'
                        ]);
                    }

                }
                else{

                    return response()->json([
                        'status' => 'error',
                        'message' => $server_response_1['message']
                    ])->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);
                }

            }
            else{

                return response()->json([
                    'status' => 'success',
                    'themes' => array(),
                    'etudiants' => array(),
                    'profs' => array()
                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }

           /* if ($data){

                $matricules_etudiants = array_column($data,'user_matricule');

                $server_response = getFromGest('api/v1/users_student/data', ['bd' => substr(hackKey(false,$request->bd), 5),'matricules_array' => $matricules_etudiants])->json();

                if ($server_response['success']){

                    $etudiants = $server_response['data'];

                    return response()->json([
                        'status' => 'success',
                        'theme_user' => $data,
                        'etudiants' => $etudiants
                    ])->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);

                }else{

                    return response()->json([
                        'status' => 'error',
                        'message' => $server_response['message']
                    ])->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);
                }
            }else{

                return response()->json([
                    'status' => 'success',
                    'theme_user' => array(),
                    'etudiants' => array()
                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }*/

        } catch (Exception $e) {

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


    public function etudiants_sans_theme(Request $request){

        try {

            $SchoolDepInfo= $request->get('SchoolDep');
            $departement = $SchoolDepInfo['departement_id'];
            $User= $request->get('User');

            $data = DB::connection('tenant')->table('theme_user')
                ->select('user_matricule')
                ->where('statut','=','PENDING')
                ->orWhere('statut','=','ACTIVATED')
                ->orWhere('statut','=','TAKEN')
                ->get()
                ->toArray();

            //$departement = Departement::on('tenant')->findOrFail($departement);

            $server_response = getFromGest('api/v1/departements/'.$departement.'/sans_theme', ['bd' => substr(hackKey(false,$request->bd), 5),'data' => $data])->json();

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

                $etudiants_data = $server_response['data'];

                if($etudiants_data)
                {
                    //Matricules des etudiants n'ayant pas de theme
                    $matricules = array_column($etudiants_data,'matricule');

                    $server_response = getFromGest('api/v1/users_student/data', ['bd' => substr(hackKey(false,$request->bd), 5),'matricules_array' => $matricules])->json();

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

                        $etudiants = $server_response['data'];
                        return response()->json([
                            'status' => 'success',
                            'etudiants_data' => $etudiants_data,
                            'etudiants' => $etudiants,
                        ])->withHeaders([
                            'Accept' => 'application/json',
                            'Content-Type' => 'application/json'
                        ]);
                    }
                    else{

                        return response()->json([
                            'status' => 'error',
                            'message' => $server_response['message']
                        ])->withHeaders([
                            'Accept' => 'application/json',
                            'Content-Type' => 'application/json'
                        ]);

                    }
                }else{
                    return response()->json([
                        'status' => 'success',
                        'etudiants_data' => [],
                        'etudiants' => [],
                    ])->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);
                }

            }else{

                return response()->json([
                    'status' => 'error',
                    'message' => $server_response['message']
                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }


        } catch (Exception $e) {

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

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

        try {
            
            $liens = DB::connection('tenant')->table('themes')
            ->where('themes.id','=',$id)
            ->join('liens','themes.id','=','liens.theme_id')
            ->where('liens.statut','!=','DELETED')
            ->select('liens.*')
            ->get()
            ->toArray()
            ;

            if($liens){
                return response()->json([
                    'status' => 'success',
                    'liens' => array_column($liens,'url')
                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }
            else{
                return response()->json([
                    'status' => 'success',
                    'liens' => array()
                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }

        } catch (Exception $e) {

            return response()->json([
                'status' => 'error',
                'message' => $e->getMessage()
            ], 404)->withHeaders([
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ]);

        }
    }

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

        try {

            $theme = Theme::on('tenant')->findOrFail($id);
            $theme->statut = 'PENDING';
            $theme->update();

            $liens = Lien::on('tenant')
            ->where('theme_id','=',$id)
            ->get();

            foreach($liens as $lien){

                $lien->statut = 'PENDING';
                $lien->update();
            }

            return response()->json([
                'status' => 'success',
                'message' => 'THEME_RESTORED'
            ])->withHeaders([
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ]);

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

    /************RUBRIQUE PROF**********/

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

        try {

            $SchoolDepInfo= $request->get('SchoolDep');
            $departement = $SchoolDepInfo['departement_id'];

            $themes_dispo = DB::connection('tenant')
                ->table('themes')
                ->where([['departement_id','=',$departement],['user_matricule','=',$id]])
                ->where('statut','=','PUBLISHED')
                ->get();

            $themes_att = DB::connection('tenant')
                ->table('themes')
                ->where([['departement_id','=',$departement],['user_matricule','=',$id]])
                ->where('statut','=','PENDING')
                ->get();

            $themes_en_etude = DB::connection('tenant')
                ->table('themes')
                ->where([['departement_id','=',$departement],['themes.user_matricule','=',$id]])
                ->where('themes.statut','=','TAKEN')
                ->join('theme_user','themes.id','=','theme_user.theme_id')
                ->where('theme_user.statut','=','ACTIVATED')
                ->select('themes.*','theme_user.user_matricule as etudiant_matricule')
                ->get()
                ->toArray();


            $matricules = array_column($themes_en_etude,'etudiant_matricule');


            $themes_soutenus = DB::connection('tenant')
                ->table('themes')
                ->where([['departement_id','=',$departement],['themes.user_matricule','=',$id]])
                ->where('themes.statut','=','SOUTENU')
                ->join('theme_user','themes.id','=','theme_user.theme_id')
                ->where('theme_user.statut','=','TAKEN')
                ->select('themes.*','theme_user.user_matricule as etudiant_matricule')
                ->get()
                ->toArray();


            $matricules = array_merge($matricules,array_column($themes_soutenus,'etudiant_matricule'));


            $themes_deleted = DB::connection('tenant')
                ->table('themes')
                ->where([['departement_id','=',$departement],['user_matricule','=',$id]])
                ->where('statut','=','DELETED')
                ->get();

           /* $matricules = DB::connection('tenant')->table('themes')
                ->where([['departement_id','=',$departement],['themes.user_matricule','=',$request->matricule]])
                ->select('user_matricule')
                ->where('statut','=','ACTIVATED')
                ->orWhere('statut','=','TAKEN')
                ->get()
                ->toArray();*/
            if($matricules){

                $server_response = getFromGest('api/v1/users_student/data', ['bd' => substr(hackKey(false,$request->bd), 5),'matricules_array' => $matricules])->json();

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

                    $etudiants = $server_response['data'];
                }
                else{

                    return response()->json([
                        'status' => 'error',
                        'message' => $server_response['message']
                    ])->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);
                }
            }
            else{
                $etudiants = [];
            }

            return response()->json([
                'status' => 'success',
                'themes_dispo' => $themes_dispo,
                'themes_pending' => $themes_att,
                'themes_en_etude' => $themes_en_etude,
                'themes_soutenus' => $themes_soutenus,
                'themes_deleted' => $themes_deleted,
                'etudiants' => $etudiants,
            ])->withHeaders([
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ]);

        } catch (Exception $e) {

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


    public function themes_filiere(Request $request)
    {
        try {
            $User= $request->get('User');

            $SchoolDepInfo= $request->get('SchoolDep');
            $departement = $SchoolDepInfo['departement_id'];
            $bd = $SchoolDepInfo['etablissement_id']."_".$departement;
            $now = Carbon::now()->year();

            $server_response = getFromGest('api/v1/userStudents/'.$User->matricule.'/state', ['bd' => substr($bd, 5)])->json();

            if(array_key_exists('success', $server_response) && $server_response['success']){

                $now = Carbon::now()->year;
                $data = $server_response['data'];
                $soutenant = $server_response['soutenant'];

                $themes = Theme::on('tenant')
                ->where('filiere_id', '=', $data[$now][0]['idFiliere'])
                ->where('niveau', '=', $data[$now][0]['niveauFormation'])->get();

                foreach ($themes as $key => $theme) {
                    $liens = Lien::on('tenant')->get()
                    ->where('theme_id', '=', $theme->id);
                    $themes[$key]['urls'] = $liens;
                }




/*


$themes = DB::connection('tenant')->table('themes')
                        ->joinSub($liens, 'liens', function ($join) {
                            $join->on('themes.id', '=', 'liens.theme_id');
                        })->get()
                ->where('niveau', '=', $data[$now][0]['niveauFormation'])
                ;


                $liens = DB::connection('tenant')->table('liens')
                   ->groupBy('theme_id')
                   ;

                $themes = DB::connection('tenant')->table('themes')
                        ->joinSub($liens, 'liens', function ($join) {
                            $join->on('themes.id', '=', 'liens.theme_id');
                        })->get()
                ->where('niveau', '=', $data[$now][0]['niveauFormation'])
                ;



                $themes = DB::connection('tenant')->table('liens')
                ->select('themes.*', 'liens.url', 'themes.titre as titre_article', 'themes.statut as stat')
                ->join('themes', 'liens.theme_id', '=', 'themes.id')
                ->get()
                ->where('filiere_id', '=', $data[$now][0]['idFiliere'])
                ->where('niveau', '=', $data[$now][0]['niveauFormation'])
                ->groupBy(['stat', 'titre_article']);
*/

                //Verifier si l'etudiant est soutenant. Si oui,verifier s'il a deja choisi un theme de soutenance

                $has_theme = false;

                if($soutenant){

                    $has_theme = DB::connection('tenant')->table('theme_user')
                    ->where([['user_matricule','=',$User->matricule],['statut','=','PENDING']])
                    ->orWhere([['user_matricule','=',$User->matricule],['statut','=','ACTIVATED']])
                    ->orWhere([['user_matricule','=',$User->matricule],['statut','=','TAKEN']])
                    ->get()->first();

                    if($has_theme){
                        $has_theme = true;
                    }
                }

                return response()->json([
                    'status' =>  'success',
                    'data' => $themes,
                    'soutenant' => $soutenant,
                    'has_theme' => $has_theme,
                    'message' => 'DATA_GOT_SUCCESSFULLY'
                ], 200);


            }
            else{

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

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

        try {

            $theme = DB::connection('tenant')->table('themes')
            ->where('themes.id','=',$id)
            ->get()->first();

            $data = DB::connection('tenant')->table('themes')
            ->where('themes.id','=',$id)
            ->join('theme_user','themes.id','=','theme_user.theme_id')
            ->select('themes.user_matricule as matricule_prof','theme_user.user_matricule as matricule_etudiant')
            ->get()->first();

            $matricule_etudiant = $data->matricule_etudiant;
            $matricule_prof = $data->matricule_prof;

            $profil_prof = getFromGest('api/v1/users/'.$matricule_prof.'/profile', ['bd' => substr(hackKey(false,$request->bd), 5)])->json();

            $profil_etudiant = getFromGest('api/v1/userStudents/'.$matricule_etudiant.'/profile', ['bd' => substr(hackKey(false,$request->bd), 5)])->json();

            return response()->json([
                'status' =>  'success',
                'theme' => $theme,
                'profil_prof' => $profil_prof['data']['profil'],
                'profil_etudiant' => $profil_etudiant['data']['profil'],
                'filiere' => $profil_etudiant['data']['filiere'],
                'message' => 'DATA_GOT_SUCCESSFULLY'
            ], 200);
        } catch (Exception $e) {

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

}

