<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\DocumentStoreRequest;
use App\Http\Requests\DocumentUpdateRequest;
use App\Http\Requests\DocumentDeleteRequest;
use App\Categorie;
use App\Document;
use App\User;
use App\Key;
use Exception;
use Illuminate\Support\Facades\DB;


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

            $SchoolDepInfo= $request->get('SchoolDep');
            $departement = $SchoolDepInfo['departement_id'];
            if($departement != 1000000) {
		          $documents = DB::connection('tenant')->table('documents')
		          ->where('departement_id','=',$departement)
		          ->orderBy('categorie_id')
		          ->get();

            } else {
		          $documents = DB::connection('tenant')->table('documents')
		          ->orderBy('categorie_id')
		          ->get();
            }

            return response()->json([
                'status' =>  'success',
                'documents' => $documents,
                'message' => 'DOCUMENTS_GOT_SUCCESSFULLY'
            ], 200);

        } catch (Exception $e) {

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

        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

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

        try {

            //$key = Key::all()->where('api_key', '=', $request->header('Authorization'))->first();

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

            //On vérifie si le nom du document existe
            if (Categorie::on('tenant')->where('id', '=', $request->categorie)->first()) {

                $categorie = Categorie::on('tenant')->where('id', '=', $request->categorie)->first();

                //Création du document
                $new_document = new Document('tenant');
                $new_document->categorie()->associate($categorie);
                //$new_document->user()->associate($User);
                $new_document->nom = $request->nom;
                $new_document->description = $request->description;
                $new_document->url = $request->url;
                $new_document->user_matricule = $User->matricule;
                $new_document->departement_id = $departement;
                if($request->theme_id)
                {
                    $new_document->theme_id = $request->theme_id;
                }
                $new_document->save();

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

                return response()->json([
                    'status' => 'error',
                    'message' => 'This categorie does not exist.'
                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }
        } catch (Exception $e) {

            return response()->json([
                'status' => 'error',
                'message' => $e->getTrace()
            ], 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 {

            $SchoolDepInfo= $request->get('SchoolDep');
            $departement = $SchoolDepInfo['departement_id'];
            if($departement != 1000000) {
		          $document = DB::connection('tenant')->table('documents')
		          ->where('departement_id','=',$departement)
		          ->where('id','=',$id)
		          ->orderBy('categorie_id')
		          ->get();

            } else {
		          $document = DB::connection('tenant')->table('documents')
                  ->where('id','=',$id)
		          ->orderBy('categorie_id')
		          ->get();
            }

            return response()->json([
                'status' =>  'success',
                'document' => $document,
                'message' => 'DOCUMENTS_GOT_SUCCESSFULLY'
            ], 200);

        } catch (Exception $e) {

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

        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

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

        try {

            //$key = Key::all()->where('api_key', '=', $request->header('Authorization'))->first();

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

            //Verifier si l'utilisateur est autorisé à modifier ce document
            if (Document::on('tenant')->findOrFail($id)->get()->first()->user_matricule == $User->matricule) {

                //On vérifie si le nom de la categorie existe
                // if (Categorie::on('tenant')->where('nom', '=', $request->nom_categorie)->first()) {

                    $categorie = Categorie::on('tenant')->where('id', '=', $request->categorie_id)->first();

                    //On vérifie si le statut de la requete est valide
                    $statut_array = ['PUBLISHED', 'BLOCKED', 'PENDING', 'SIGNALED'];
                    foreach ($statut_array as $statut) {

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

                            $document = Document::on('tenant')->findOrFail($id);
                            $document->user_matricule = $User->matricule;
                            $document->categorie()->associate($categorie);
                            $document->statut = $request->statut;
                            $document->description = $request->description;
                            $document->nom = $request->nom;
                            $document->url = $request->url;
                            $document->update();

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

                    return response()->json([
                        'status' => 'error',
                        'message' => 'This statut does not exist.'
                    ])->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);
                // } else {

                //     return response()->json([
                //         'status' => 'error',
                //         'message' => 'This categorie name does not exist.'
                //     ])->withHeaders([
                //         'Accept' => 'application/json',
                //         'Content-Type' => 'application/json'
                //     ]);
                // }
            }

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

            return response()->json([
                'status' => 'error',
                'message' => $e->getTrace()
            ], 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(DocumentDeleteRequest $request, $id)
    {

        try {

            //$key = Key::all()->where('api_key', '=', $request->header('Authorization'))->first();

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

            //On récupère le document
            $document = Document::on('tenant')->findOrFail($id);

            //Verifier si l'utilisateur est autorisé à supprimer ce document
            if (Document::on('tenant')->findOrFail($id)->get()->first()->user_matricule == $User->matricule) {

                if ($request->mode == "soft") {

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

                    return response()->json([
                        'status' => 'success',
                        'document' => 'SOFT_DELETE_DONE'
                    ])->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);
                } else if ($request->mode == "strict") {

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

                    return response()->json([
                        'status' => 'error',
                        'message' => 'This mode does not exist.'
                    ])->withHeaders([
                        'Accept' => 'application/json',
                        'Content-Type' => 'application/json'
                    ]);
                }
            }

            return response()->json([
                'status' => 'error',
                'message' => "Permissions not granted"
            ])->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'
            ]);
        }
    }
}
