<?php

namespace App\Http\Controllers\API\v1;

use App\Commentaire;
use App\Http\Controllers\Controller;
use App\Http\Requests\MainRequest;
use App\Http\Requests\SujetStoreRequest;
use App\Http\Requests\SujetUpdateRequest;
use App\Image;
use App\Sujet;
use App\User;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SujetController extends Controller
{
    public function __construct()
    {
        $this->middleware('verify_user_token', ['except' => ['index', 'show']]);
    }

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

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

            $sujets = DB::connection('tenant')->table('sujets')
                ->select(['sujets.*', 'users.matricule as matricule', 'users.token as access_token'])
                ->join('users', 'sujets.user_matricule', '=', 'users.matricule')
                ->get()
                ->where('departement_id', $departement)
                ->where('statut', 'PUBLISHED')
                ->sortByDesc('created_at');

            $output = [];

            $i = 0;
            foreach ($sujets as $sujet) {
                $output[$i] = $sujet;
                $output[$i]->total = Commentaire::on('tenant')
                    ->where('sujet_id', $sujet->id)
                    ->where('statut', 'PUBLISHED')
                    ->get()
                    ->count();

                $output[$i]->images = Image::on('tenant')
                    ->where('sujet_id', $sujet->id)
                    ->where('statut', 'PUBLISHED')
                    ->get();

                $commentaires = Commentaire::on('tenant')
                    ->where('statut', 'PUBLISHED')
                    ->where('sujet_id', $sujet->id)
                    ->get();

                $j = 0;
                foreach ($commentaires as $commentaire) {
                    $output[$i]->commentaires[$j] = $commentaire;
                }
                $i++;
            }

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

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

            $sujets = DB::connection('tenant')->table('sujets')
                ->select(['sujets.*', 'users.matricule as matricule', 'users.token as access_token'])
                ->join('users', 'sujets.user_matricule', '=', 'users.matricule')
                ->get()
                ->where('departement_id', $departement)
                ->where('statut', 'PUBLISHED')
                ->where('user_matricule', $User->matricule)
                ->sortByDesc('created_at');

            $output = [];

            $i = 0;
            foreach ($sujets as $sujet) {
                $output[$i] = $sujet;
                $output[$i]->total = Commentaire::on('tenant')
                    ->where('sujet_id', $sujet->id)
                    ->where('statut', 'PUBLISHED')
                    ->get()
                    ->count();

                $output[$i]->images = Image::on('tenant')
                    ->where('sujet_id', $sujet->id)
                    ->where('statut', 'PUBLISHED')
                    ->get();

                $commentaires = Commentaire::on('tenant')
                    ->where('statut', 'PUBLISHED')
                    ->where('sujet_id', $sujet->id)
                    ->get();

                $j = 0;
                foreach ($commentaires as $commentaire) {
                    $output[$i]->commentaires[$j] = $commentaire;
                }
                $i++;
            }

            return response()->json([
                'status' => 'success',
                'sujets' => $output
            ]);
        } 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(SujetStoreRequest $request)
    {
        try {
            $SchoolDepInfo= $request->get('SchoolDep');
            $departement = $SchoolDepInfo['departement_id'];
            $bd = $SchoolDepInfo['etablissement_id']."_".$departement;
            $User= $request->get('User');


            //Creation du sujet
            $sujet = new Sujet('tenant');
            $sujet->titre = $request->titre;
            $sujet->contenu = $request->contenu;
            $sujet->departement_id = $departement;
            $sujet->user_matricule = $User->matricule;
            $sujet->save();

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

            //Creation des images reliées au sujet
            if ($request->image != null) {
                $img = new Image('tenant');
                $img->nom = $request->image;
                $img->url = $request->image;
                $img->sujet()->associate($sujet);
                $img->save();

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

            return response()->json([
                'status' => 'success',
                'sujet' => $sujet
            ])->withHeaders([
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ]);
        } catch (Exception $e) {
            //Sauvegarder l'opération
            save_log($bd, 'SUJET 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(MainRequest $request, $id)
    {
        try {
            $SchoolDepInfo= $request->get('SchoolDep');
            $departement = $SchoolDepInfo['departement_id'];
            $bd = $SchoolDepInfo['etablissement_id']."_".$departement;
            //$User= $request->get('User');

            $sujet = DB::connection('tenant')->table('sujets')
                ->select(['sujets.*', 'users.matricule as matricule', 'users.type_user as type_user', 'users.token as access_token'])
                ->join('users', 'sujets.user_matricule', '=', 'users.matricule')
                ->get()
                ->where('departement_id', $departement)
                ->where('statut', 'PUBLISHED')
                ->where('id', $id)
                ->first();

            $output = $sujet;
            $output->total = Commentaire::on('tenant')
                ->where('sujet_id', $sujet->id)
                ->where('statut', 'PUBLISHED')
                ->get()
                ->count();

            $output->images = Image::on('tenant')
                ->where('statut', 'PUBLISHED')
                ->where('sujet_id', $output->id)
                ->get();

            $commentaires = DB::connection('tenant')->table('commentaires')
                ->select(['commentaires.*', 'users.matricule as matricule', 'users.token as access_token'])
                ->join('users', 'commentaires.user_matricule', 'users.matricule')
                ->get()
                ->where('sujet_id', $output->id)
                ->where('commentaire_id', null)
                ->where('statut', 'PUBLISHED')
                ->sortBy('created_at');

            $matricules = array_unique(array_column($commentaires->toArray(),"matricule"));

            //Selectionner les matricules d'etudiants à part
            $matricules_etudiants = DB::connection('tenant')->table('users')
            //->whereIn('matricule',$matricules)
            //->where('type_user',0)
            ->select('matricule')
            ->get();

            $matricules_etudiants = array_column($matricules_etudiants->toArray(),"matricule");
            $server_response_1 = reqGest('POST', 'v1/users_student/data', ['matricules_array' => $matricules_etudiants], 2);
            // $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 = DB::connection('tenant')->table('users')
                    ->whereIn('matricule',$matricules)
                    ->where('type_user','!=',0)
                    ->select('matricule')
                    ->get();

                $matricules_profs = array_column($matricules_profs->toArray(),"matricule");
                
                $server_response_2 = reqGest('POST', 'v1/users/data', ['matricules_array' => $matricules_profs], 2);

                if ($server_response_2['success']){
                    $profs = $server_response_2['data'];

                    array_push($etudiants,$profs);
                    //$data =

                    $j = 0;

                    foreach ($commentaires as $commentaire) {
                        $output->commentaires[$j] = $commentaire;

                        $output->commentaires[$j]->images = Image::on('tenant')
                            ->where('statut', 'PUBLISHED')
                            ->where('commentaire_id', $commentaire->id)
                            ->get();

                        $comments = DB::connection('tenant')->table('commentaires')
                            ->select(['commentaires.*', 'users.matricule as matricule', 'users.token as access_token'])
                            ->join('users', 'commentaires.user_matricule', 'users.matricule')
                            ->get()
                            ->where('sujet_id', $output->id)
                            ->where('commentaire_id', '=', $commentaire->id)
                            ->where('statut', 'PUBLISHED')
                            ->sortBy('created_at');

                        $output->commentaires[$j]->commentaires = $comments;
                        $j++;
                    }

                    if($sujet->type_user == 0){

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

                        if(array_key_exists('success', $server_response) && $server_response['success'] == true){
                            $profil_gest = $server_response['data'];
                        }
                        else{

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

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

                        if(array_key_exists('success', $server_response) && $server_response['success'] == true){
                            $profil_gest = $server_response['data'];
                        }
                        else{

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

                    return response()->json([
                        'status' => 'success',
                        'sujet' => $output,
                        'profile' =>$profil_gest,
                        'data' =>  $etudiants,
                        'profs' => $profs,
                    ]);

                }
                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'
                ]);
            }

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

    // public function show(MainRequest $request, $id)
    // {
    //     try {

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

    //         $sujet = DB::connection('tenant')->table('sujets')
    //             ->select(['sujets.*', 'users.matricule as matricule', 'users.type_user as type_user', 'users.token as access_token'])
    //             ->join('users', 'sujets.user_matricule', '=', 'users.matricule')
    //             ->get()
    //             ->where('departement_id', $departement)
    //             ->where('statut', 'PUBLISHED')
    //             ->where('id', $id)
    //             ->first();

    //         $output = $sujet;
    //         $output->total = Commentaire::on('tenant')
    //             ->where('sujet_id', $sujet->id)
    //             ->where('statut', 'PUBLISHED')
    //             ->get()
    //             ->count();

    //         $output->images = Image::on('tenant')
    //             ->where('statut', 'PUBLISHED')
    //             ->where('sujet_id', $output->id)
    //             ->get();

    //         $commentaires = DB::connection('tenant')->table('commentaires')
    //             ->select(['commentaires.*', 'users.matricule as matricule', 'users.token as access_token'])
    //             ->join('users', 'commentaires.user_matricule', 'users.matricule')
    //             ->get()
    //             ->where('sujet_id', $output->id)
    //             ->where('commentaire_id', null)
    //             ->where('statut', 'PUBLISHED')
    //             ->sortBy('created_at');

    //         $j = 0;

    //         foreach ($commentaires as $commentaire) {
    //             $output->commentaires[$j] = $commentaire;

    //             $output->commentaires[$j]->images = Image::on('tenant')
    //                 ->where('statut', 'PUBLISHED')
    //                 ->where('commentaire_id', $commentaire->id)
    //                 ->get();

    //             $comments = DB::connection('tenant')->table('commentaires')
    //                 ->select(['commentaires.*', 'users.matricule as matricule', 'users.token as access_token'])
    //                 ->join('users', 'commentaires.user_matricule', 'users.matricule')
    //                 ->get()
    //                 ->where('sujet_id', $output->id)
    //                 ->where('commentaire_id', '=', $commentaire->id)
    //                 ->where('statut', 'PUBLISHED')
    //                 ->sortBy('created_at');

    //             $output->commentaires[$j]->commentaires = $comments;
    //             $j++;
    //         }

    //         if($sujet->type_user == 0){

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

    //             if(array_key_exists('success', $server_response) && $server_response['success'] == true){
    //                 $profil_gest = $server_response['data'];
    //             }
    //             else{

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

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

    //             if(array_key_exists('success', $server_response) && $server_response['success'] == true){
    //                 $profil_gest = $server_response['data'];
    //             }
    //             else{

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

    //         return response()->json([
    //             'status' => 'success',
    //             'sujet' => $output,
    //             'profile' =>$profil_gest
    //         ]);
    //     } 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(SujetUpdateRequest $request, $id)
    {
        try {

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

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

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

            //Verify if the user requesting is the owner of the sujet
            if ($sujet->user_matricule == $User->matricule) {
                if ($request->titre != null) {
                    $sujet->titre = $request->titre;
                }

                if ($request->contenu != null) {
                    $sujet->contenu = $request->contenu;
                }

                if ($request->image && $request->image == 'DELETED') {
                    //Remove the image
                    $image = Image::on('tenant')
                        ->where('sujet_id', $sujet->id)
                        ->where('statut', 'PUBLISHED')
                        ->get()
                        ->first();

                    save_log($bd, 'IMAGE DELETE', json_encode($image), $User->matricule);

                    $image->statut = 'DELETED';
                    $image->update();
                } else if ($request->image != null) {
                    $image = Image::on('tenant')
                        ->where('sujet_id', $sujet->id)
                        ->where('statut', 'PUBLISHED')
                        ->get()->first();

                    if ($image) {
                        $image->nom = $request->image;
                        $image->url = $request->image;
                        $image->update();

                        save_log($bd, 'IMAGE UPDATE', json_encode($image), $User->matricule);
                    } else {
                        $new_image = new Image('tenant');
                        $new_image->nom = $request->image;
                        $new_image->url = $request->image;
                        $new_image->sujet()->associate($sujet);
                        $new_image->save();

                        save_log($bd, 'IMAGE STORE', json_encode($image), $User->matricule);
                    }
                }

                $sujet->update();

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

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

                return response()->json([
                    'status' => 'error',
                    'message' => "Permissions not granted"
                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }
        } catch (Exception $e) {
            //Sauvegarder l'opération
            save_log($bd, 'SUJET 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 {
            $request->validate([
                'mode' => ['nullable', 'in:strict,soft']
            ]);

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

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

            //Get the sujet and it images
            $sujet = Sujet::on('tenant')->findOrFail($id);
            $images = Image::on('tenant')->where('sujet_id', '=', $sujet->id)->get();
            $commentaires = Commentaire::on('tenant')->where('sujet_id', '=', $sujet->id)->get();

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

                //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, 'SUJET DELETE STRICT', json_encode($sujet), $User->matricule);

                    $sujet->delete();

                    return response()->json([
                        'status' => 'success',
                        'message' => 'SUJET_DELETE_STRICT'
                    ])->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);
                } else {
                    //Set statut of the sujet to DELETED
                    $sujet->statut = 'DELETED';

                    //Set statut of related images to DELETED
                    foreach ($images as $img) {
                        $img->statut = 'DELETED';
                        $img->update();

                        //Sauvegarder l'opération
                        save_log($bd, 'IMAGE DELETE', json_encode($img), $User->matricule);
                    }

                    //Set statut of related commentaires to DELETED
                    foreach ($commentaires as $commentaire) {
                        $commentaire->statut = 'DELETED';
                        $commentaire->update();

                        //Sauvegarder l'opération
                        save_log($bd, 'COMMENTAIRE DELETE', json_encode($commentaire), $User->matricule);
                    }

                    $sujet->update();

                    //Sauvegarder l'opération
                    save_log($bd, 'SUJET DELET', json_encode($sujet), $User->matricule);

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

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

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