<?php

namespace App\Http\Controllers\API\v1;

use App\Commentaire;
use App\Http\Controllers\Controller;
use App\Http\Requests\CommentaireStoreRequest;
use App\Http\Requests\CommentaireUpdateRequest;
use App\Image;
use App\Sujet;
use App\User;
use Exception;
use Illuminate\Http\Request;

class CommentaireController 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()
    {
        //
    }

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

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

            //Creation of the commentaire
            $commentaire = new Commentaire('tenant');
            $commentaire->contenu = $request->comment;

            $commentaire->user()->associate($User);

            $sujet_linked = Sujet::on('tenant')
                ->where('id', '=', $request->sujet_id)
                ->where('departement_id', $departement)
                ->get()
                ->where('statut', 'PUBLISHED')
                ->first();

            $commentaire->sujet()->associate($sujet_linked);

            if ($request->commentaire_id != null) {
                $commentaire_linked = Commentaire::on('tenant')
                    ->where('id', '=', $request->commentaire_id)
                    ->where('statut', 'PUBLISHED')
                    ->get()->first();

                $commentaire->commentaire()->associate($commentaire_linked);
            }

            $commentaire->save();

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

            //Store images if provided
            if ($request->image != null) {
                $img = new Image('tenant');
                $img->nom = $request->image;
                $img->url = $request->image;
                $img->commentaire()->associate($commentaire);
                $img->save();

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

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

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

    /**
     * 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:soft,strict'
            ]);

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

            //Get the commentaire
            $commentaire = Commentaire::on('tenant')->findOrFail($id);

            //Verify if the user requesting is the owner of the commentaire
            if ($commentaire->user_matricule == $User->matricule || $User->type_user == 3) {
                //Sauvegarder l'opération
                if ($request->mode && $request->mode == 'strict') {
                    save_log($bd, 'COMMENTAIRE DELETE STRICT', json_encode($commentaire), $User->matricule);
                    $commentaire->delete();

                    return response()->json([
                        'status' => 'success',
                        'message' => 'COMMENTAIRE_DELETE_STRICT'
                    ])->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);
                } else {
                    $commentaire->statut = 'DELETED';
                    $commentaire->update();

                    $sub_comments = Commentaire::on('tenant')->where('commentaire_id', $commentaire->id)->get();

                    foreach (Image::on('tenant')
                        ->where('commentaire_id', $commentaire->id)
                        ->where('statut', '=', 'PUBLISHED')
                        ->get() as $img) {

                        $img->statut = 'DELETED';
                        $img->update();

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

                    foreach ($sub_comments as $sub) {
                        $sub->statut = 'DELETED';
                        $sub->update();

                        save_log($bd, 'COMMENTAIRE DELETE', json_encode($sub), $User->matricule);
                    }

                    save_log($bd, 'COMMENTAIRE DELETE', json_encode($commentaire), $User->matricule);

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

                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
            save_log($bd, 'COMMENTAIRE DELETE', $e->getMessage(), $User->matricule);

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