<?php

namespace App\Http\Controllers\API\v1;

use App\Article;
use App\Attachement;
use App\Http\Controllers\Controller;
use App\Http\Requests\ArticleDestroyRequest;
use App\Http\Requests\ArticleStoreRequest;
use App\Http\Requests\ArticleUpdateRequest;
use App\Image;
use App\Log;
use App\Paragraphe;
use App\Section;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;


class ArticleController extends Controller
{

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

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

            // return response()->json(Article::on($key->bd)->where('user_id', '=', $user->id)->get());

            // SELECT `sections`.`titre`, `paragraphes`.`contenu` FROM `paragraphes` INNER JOIN `sections` ON `sections`.`id` = `paragraphes`.`section_id` GROUP BY `paragraphes`.`section_id`
            $SchoolDepInfo= $request->get('SchoolDep');
            $departement = $SchoolDepInfo['departement_id'];
            $bd = $SchoolDepInfo['etablissement_id']."_".$departement;

            $articles = DB::connection('tenant')->table('articles')
                 ->select('articles.*', 'paragraphes.*', 'articles.titre as titre_article', 'articles.statut as stat')
                 ->join('sections', 'articles.id', '=', 'sections.article_id')
                 ->leftJoin('paragraphes', 'sections.id', '=', 'paragraphes.section_id')
                 ->get()
                 ->groupBy(['stat', 'titre_article']);


         return response()->json([
             'status' =>  'success',
             'data' => $articles,
             'message' => 'ARTICLES_GOT_SUCCESSFULLY'
         ], 200);
         } catch (Exception $e) {
             return response()->json([
                 'status' =>  'error',
                 'message' => $e->getMessage()
             ], 400);
         }
    }


    public function article_filtered(Request $request, $statut=null)
    {
        try {
            $User= $request->get('User');
            $statut = $statut != null ? $statut : 'PUBLISHED';

            if ($request->type == "RECENT_ACTIVITY"){

                $articles = DB::connection('tenant')->table('articles')
                    ->select('articles.*', 'paragraphes.contenu', 'articles.titre as titre_article', 'articles.statut as stat')
                    ->join('sections', 'articles.id', '=', 'sections.article_id')
                    ->leftJoin('paragraphes', 'sections.id', '=', 'paragraphes.section_id')
                    ->where('articles.statut', '=', $statut)
                    ->where('articles.type', '=', "RECENT_ACTIVITY")
                    ->orderByDesc('articles.created_at')
                    ->offset($request->offset)
                    ->limit($request->perPage)
                    ->get()
                    ->groupBy(['titre_article']);

                $total = DB::connection('tenant')->table('articles')
                    ->where('statut', '=', $statut)
                    ->where('articles.type', '=', "RECENT_ACTIVITY")
                    ->count();

            } else{

                $articles = DB::connection('tenant')->table('articles')
                    ->select('articles.*', 'paragraphes.contenu', 'articles.titre as titre_article', 'articles.statut as stat')
                    ->join('sections', 'articles.id', '=', 'sections.article_id')
                    ->leftJoin('paragraphes', 'sections.id', '=', 'paragraphes.section_id')
                    ->where('articles.statut', '=', $statut)
                    ->where('articles.type', '=', "BLOG")
                    ->orderByDesc('articles.created_at')
                    ->offset($request->offset)
                    ->limit($request->perPage)
                    ->get()
                    ->groupBy(['titre_article']);

                $total = DB::connection('tenant')->table('articles')
                        ->where('statut', '=', $statut)
                        ->where('articles.type', '=', "BLOG")
                        ->count();

            }

            return response()->json([
                'status' =>  'success',
                'data' => $articles,
                'total' => $total,
                'message' => 'ARTICLES_GOT_SUCCESSFULLY'
            ], 200);

        } catch (Exception $e) {
            return response()->json([
                'status' =>  'error',
                'message' => $e->getMessage()
            ], 400);
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(ArticleStoreRequest $request)
    {
        try {

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

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

            $oldArticle = Article::on('tenant')
            ->where('titre','=', $request->titre)->first();

            if($oldArticle){
                return response()->json([
                    'status' => 'error',
                    'message' => "Another article has already this title."
                ], 403)->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }

            //Creation of the article
            $article = new Article('tenant');
            $article->type = $request->type;
            $article->titre = $request->titre;
            $article->miniature = $request->miniature;
            $article->departement_id = $departement;
            $article->user_matricule = $User->matricule;
            // $article->statut = 'PENDING';
            $article->statut = 'PUBLISHED';
            $article->save();

            //Sauvegarder l'opération
            $log = new Log();
            $log->bd = $bd;
            $log->operation = 'ARTICLE STORE';
            $log->description = json_encode($article);
            $log->user_matricule = $User->matricule;
            $log->save();

            //Creation des sections
            foreach ($request->sections as $section) {
                $sect = new Section('tenant');
                $sect->titre = $section['titre'];
                $sect->article()->associate($article);
                $sect->save();

                //Sauvegarder l'opération
                $log = new Log();
                $log->bd = $bd;
                $log->operation = 'SECTION STORE';
                $log->description = json_encode($sect);
                $log->user_matricule = $User->matricule;
                $log->save();

                //Creation des paragraphes
                foreach ($section['paragraphes'] as $paragraphe) {
                    $parag = new Paragraphe('tenant');
                    $parag->contenu = $paragraphe;
                    $parag->section()->associate($sect);
                    $parag->save();

                    //Sauvegarder l'opération
                    $log = new Log();
                    $log->bd = $bd;
                    $log->operation = 'PARAGRAPHE STORE';
                    $log->description = json_encode($parag);
                    $log->user_matricule = $User->matricule;
                    $log->save();
                }

                //Store image if provided
                if (isset($section['image'])) {
                    $img = new Image('tenant');
                    $img->nom = $section['image']['nom'];
                    $img->url = $section['image']['url'];
                    $img->section()->associate($sect);
                    $img->save();

                    //Sauvegarder l'opération
                    $log = new Log();
                    $log->bd = $bd;
                    $log->operation = 'IMAGE STORE';
                    $log->description = json_encode($img);
                    $log->user_matricule = $User->matricule;
                    $log->save();
                }
            }

            //Store attachements if provided
            if ($request->attachements != null) {
                foreach ($request->attachements as $attach) {
                    $att = new Attachement('tenant');
                    $att->nom = $attach['nom'];
                    $att->url = $attach['url'];
                    $att->article()->associate($article);
                    $att->save();

                    //Sauvegarder l'opération
                    $log = new Log();
                    $log->bd = $bd;
                    $log->operation = 'ATTACHEMENT STORE';
                    $log->description = json_encode($att);
                    $log->user_matricule = $User->matricule;
                    $log->save();
                }
            }

            return response()->json([
                'status' => 'success',
                'article' => $article
            ])->withHeaders([
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ]);
        } catch (Exception $e) {
            //Sauvegarder l'opération
            $log = new Log();
            $log->bd = $bd;
            $log->operation = 'ARTICLE STORE';
            $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'
            ]);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request ,$id)
    {
        try {
            //$User= $request->get('User');

            if ($request->type == "RECENT_ACTIVITY"){
                $article = DB::connection('tenant')->table('articles')
                    ->select('articles.*', 'paragraphes.contenu', 'articles.titre as titre_article', 'articles.statut as stat')
                    ->join('sections', 'articles.id', '=', 'sections.article_id')
                    ->leftJoin('paragraphes', 'sections.id', '=', 'paragraphes.section_id')
                    ->where('articles.id', '=', $id)
                    ->where('articles.type', '=', "RECENT_ACTIVITY")
                    ->get()->first();
            }else{
                $article = DB::connection('tenant')->table('articles')
                    ->select('articles.*', 'paragraphes.contenu', 'articles.titre as titre_article', 'articles.statut as stat')
                    ->join('sections', 'articles.id', '=', 'sections.article_id')
                    ->leftJoin('paragraphes', 'sections.id', '=', 'paragraphes.section_id')

                    ->where('articles.id', '=', $id)->get()->first();
            }

            if($article){

                $type_user = DB::connection('tenant')
                    ->table('users')
                    ->where('matricule','=',$article->user_matricule)
                    ->select('type_user')
                    ->first()->type_user;

                if($type_user == 0){

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

                }
                else{
                    $server_response = getFromGest('api/v1/users/'.$article->user_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'];
                    return response()->json([
                        'status' =>  'success',
                        'data' => [
                            'article' => $article,
                            'profil' => $profil_gest,
                            'type_user' => $type_user,
                        ],
                        'message' => 'ARTICLES_GOT_SUCCESSFULLY'
                    ], 200);
                }
                else{

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

            }
            else{

                return response()->json([
                    'status' =>  'error',
                    'message' => 'ARTICLE_NOT_FOUND'
                ], 400);
            }

        } catch (Exception $e) {
            return response()->json([
                'status' =>  'error',
                'message' => $e->getMessage()
            ], 400);
        }
    }

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


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

            $imgToDelete = []; // Array des images à supprimer du dossier upload sur le site
            $j = 0;

            $article = Article::on('tenant')->findOrFail($id);

            if (isset($request->statut)){

                if ($article->user_matricule == $User->matricule  || $User->type_user == 4 || $User->type_user == 6 || $User->type_user == 3) {
                    $article->statut = $request->statut;
                }
                else{

                    //Sauvegarder l'opération
                    $log = new Log();
                    $log->bd = $bd;
                    $log->operation = 'ARTICLE STORE';
                    $log->description = 'PERMISSIONS NOT GRANTED';
                    $log->user_matricule = $User->matricule;
                    $log->save();

                    return response()->json([
                        'status' => 'error',
                        'message' => "Permissions not granted"
                    ], 403)->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);
                }
            }

            if (isset($request->titre)){

                $oldArticle = Article::on('tenant')->where('titre','=', $request->titre)
                ->where('id','!=', $id)->first();


                if($oldArticle){
                    return response()->json([
                        'status' => 'error',
                        'message' => "Another article has already this title."
                    ], 403)->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);
                }

                if ($article->user_matricule == $User->matricule ) {
                    $article->titre = $request->titre;
                }
                else{

                    //Sauvegarder l'opération
                    $log = new Log();
                    $log->bd = $bd;
                    $log->operation = 'ARTICLE STORE';
                    $log->description = 'PERMISSIONS NOT GRANTED';
                    $log->user_matricule = $User->matricule;
                    $log->save();

                    return response()->json([
                        'status' => 'error',
                        'message' => "Permissions not granted. You must be author of this article"
                    ], 403)->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);
                }
            }

            if (isset($request->miniature)) {
                if($article->miniature != $request->miniature) {
                    if($article->miniature != "no-image.jpg") {
                        // supprimer l'ancienne image du dossier upload/articles
                        $imgToDelete[$j] = $article->miniature;
                        $j++;
                    }
                    $article->miniature = $request->miniature;
                    $newImg = true;  // C'est une nouvelle image qui a été uploader par l'utilisateur
                }
            } else {
                if($article->miniature != "no-image.jpg") {
                    // supprimer cette miniature du serveur car elle a été supprimé par l'auteur
                    $imgToDelete[$j] = $article->miniature;
                    $j++;
                    $article->miniature = "no-image.jpg";
                }
            }

            $modifiedImgContent = array();
            $i = 0;
            $modifiedSection = $request->sections;

            $oldSection = Section::on('tenant')->where('article_id', '=', $article->id)->first();
            $oldSection->titre = $modifiedSection['titre'];
            $oldSection->update();

            $htmlString = $modifiedSection['paragraphes'];
            $htmlDom = new \DOMDocument;
            $htmlDom->loadHTML($htmlString);

            $imageTags = $htmlDom->getElementsByTagName('img');
            foreach($imageTags as $imageTag) {
                // Add the image details to our $modifiedImgContent array.
                $src = $imageTag->getAttribute('src');
                $index =  strrpos($src,"/")+1;
                $src = substr($src,$index);
                $modifiedImgContent[$i] = $src;
                $i++;
            }

            $oldParagraphe = Paragraphe::on('tenant')->where('section_id', '=', $oldSection->id)->first();
            $htmlString = $oldParagraphe->contenu;
            $htmlDom = new \DOMDocument;
            $htmlDom->loadHTML($htmlString);

            $imageTags = $htmlDom->getElementsByTagName('img');
            foreach($imageTags as $imageTag){
                $src = $imageTag->getAttribute('src');
                $index =  strrpos($src,"/")+1;
                $src = substr($src,$index);
                if(array_search($src,$modifiedImgContent) == FALSE) {
                    // supprimer donc cette img du dossier upload
                    $imgToDelete[$j] = $src;
                    $j++;
                }
            }

            $oldParagraphe->contenu = $modifiedSection['paragraphes'];
            $oldParagraphe->update();

            //Sauvegarder l'opération
            $log = new Log();
            $log->bd = $bd;
            $log->operation = 'ARTICLE UPDATE';
            $log->description = json_encode($article);
            $log->user_matricule = $User->matricule;
            $log->save();

            $article->update();

            return response()->json([
                'status' => 'success',
                'newImg' => $newImg,
                'imgToDelete' => $imgToDelete,
                'message' => "ARTICLE_UPDATED_SUCCESSFULLY"
            ])->withHeaders([
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ]);

        } catch (Exception $e) {
            //Sauvegarder l'opération
            $log = new Log();
            $log->bd = $bd;
            $log->operation = 'ARTICLE UPDATE';
            $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'
            ]);
        }
    }

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


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

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

            //Get the article and it sections
            $article = Article::on('tenant')->findOrFail($id);
            $sections = Section::on('tenant')->where('article_id', '=', $article->id)->get();
            $attachements = Attachement::on('tenant')->where('article_id', '=', $article->id)->get();

            //Verify if the user requesting is the owner of the article
            if ($article->user_matricule == $User->matricule) {
                //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
                    $log = new Log();
                    $log->bd = $bd;
                    $log->operation = 'ARTICLE DELETE STRICT';
                    $log->description = json_encode($article);

                    $miniature = $article->miniature;

                   /* if($miniature != "no-image.jpg"){
                        Storage::disk('public')->delete('upload/articles/'.$miniature);
                    }*/
                    $extractedImages = array();
                    $i = 0;

                    foreach ($sections as $section) {

                        $paragraphes = Paragraphe::on('tenant')->where('section_id', '=', $section->id)->get();
                        foreach ($paragraphes as $paragraphe) {

                            $htmlString = $paragraphe->contenu;
                            $htmlDom = new \DOMDocument;
                            $htmlDom->loadHTML($htmlString);

                            $imageTags = $htmlDom->getElementsByTagName('img');


                            foreach($imageTags as $imageTag){

                                //Get the src attribute of the image.
                                $imgSrc = $imageTag->getAttribute('src');
                                $index =  strrpos($imgSrc,"/")+1;
                                $imgSrc = substr($imgSrc,$index);

                                //Storage::disk('public')->delete('upload/articles/'.$imgSrc);

                                //Get the alt text of the image.
                                //$altText = $imageTag->getAttribute('alt');

                                //Get the title text of the image, if it exists.
                                //$titleText = $imageTag->getAttribute('title');

                                //Add the image details to our $extractedImages array.
                                $extractedImages[$i] = $imgSrc;
                                $i++;
                            }
                        }
                    }

                    if($miniature != "no-image.jpg"){
                        $extractedImages[$i] = $miniature;
                    }
                    $article->delete();

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

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

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

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

                        //Set statut of related paragraphes to DELETED
                        $paragraphes = Paragraphe::on('tenant')->where('section_id', '=', $section->id)->get();
                        foreach ($paragraphes as $paragraphe) {
                            $paragraphe->statut = 'DELETED';
                            $paragraphe->update();

                            //Sauvegarder l'opération
                            $log = new Log();
                            $log->bd = $bd;
                            $log->operation = 'PARAGRAPHE DELETE';
                            $log->description = json_encode($paragraphe);
                            $log->user_matricule = $User->matricule;
                            $log->save();
                        }

                        //Set statut of related images
                        $images = Image::on('tenant')->where('section_id', '=', $section->id)->get();
                        foreach ($images as $image) {
                            $image->statut = 'DELETED';
                            $image->update();

                            //Sauvegarder l'opération
                            $log = new Log();
                            $log->bd = $bd;
                            $log->operation = 'IMAGE DELETE';
                            $log->description = json_encode($image);
                            $log->user_matricule = $User->matricule;
                            $log->save();
                        }
                    }

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

                        //Sauvegarder l'opération
                        $log = new Log();
                        $log->bd = $bd;
                        $log->operation = 'ATTACHEMENT DELETE';
                        $log->description = json_encode($attachement);
                        $log->user_matricule = $User->matricule;
                        $log->save();
                    }

                    $article->update();

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

                    return response()->json([
                        'status' => 'success',
                        'message' => 'ARTICLE_DELETE',
                        'imgToDelete' => []
                    ])->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);
                }
            } else {
                //Sauvegarder l'opération
                $log = new Log();
                $log->bd = $bd;
                $log->operation = 'ARTICLE DELETE';
                $log->description = 'PERMISSIONS NOT GRANTED';
                $log->user_matricule = $User->matricule;
                $log->save();

                return response()->json([
                    'status' => 'error',
                    'message' => "Permissions not granted"
                ], 403)->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }
        } catch (Exception $e) {
            //Sauvegarder l'opération
            $log = new Log();
            $log->bd = $bd;
            $log->operation = 'ARTICLE DELETE';
            $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 article_data(Request $request){

        try {


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

            //Articles en attente de validation
            $articles_att = DB::connection('tenant')
                ->table('articles')
                ->where('departement_id','=',$departement)
                ->where('statut','=','PENDING')
                ->get()
                ->toArray();

            if ($articles_att){

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

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

                if ($server_response['success']){

                    $etudiants = $server_response['data'];

                    return response()->json([
                        'status' => 'success',
                        'articles' => $articles_att,
                        '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',
                    'articles' => [],
                    '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'
            ]);
        }
    }

}
