<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Http\Requests\CategorieStoreRequest;
use App\Http\Requests\CategorieUpdateRequest;
use App\Http\Requests\CategorieDeleteRequest;
use App\Categorie;
use App\Document;
//use App\Key;
use Exception;
use Illuminate\Support\Facades\DB;

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

            $categories = DB::connection('tenant')->table('categories')
            ->select('*')
            ->orderBy('nom')
            ->get();

            return response()->json([
                'status' =>  'success',
                'categories' => $categories,
                'message' => 'CATEGORIES_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(CategorieStoreRequest $request)
    {
        try {

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

            $User= $request->get('User');
            //On vérifie si le nom de la categorie existe déjà
            if(!(Categorie::on('tenant')->where('nom',$request->nom)->first())){

                //Creation d'une nouvelle categorie
                $categorie = new Categorie('tenant');

                $categorie->nom = $request->nom;
                $categorie->slug = Str::slug($request->nom, '_');
                $categorie->user_matricule = $User->matricule;
                $categorie->save();

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

            }else{

                return response()->json([
                    'status' => 'error',
                    'message' => 'This categorie name exists. Enter another categorie name.'
                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);

            }
        } catch (Exception $e) {

            return response()->json([
                'status' => 'error',
                'message' => "Line ".$e->getLine(). " msg: ".$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)
    {

    }

    /**
     * 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(CategorieUpdateRequest $request, $id)
    {
        try {

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


            $SchoolDepInfo= $request->get('SchoolDep');
            $departement = $SchoolDepInfo['departement_id'];
            $bd = $SchoolDepInfo['etablissement_id']."_".$departement;
            //On vérifie si le nom de la categorie existe déjà au niveau des autres noms de categorie
            if(!(Categorie::on('tenant')->where('id','!=',$id)->where('nom','=',$request->nom))->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){

                        //Modification de la categorie
                        $categorie = Categorie::on('tenant')->findOrFail($id);

                        $categorie->nom = $request->nom;
                        $categorie->statut = $request->statut;
                        $categorie->update();

                        return response()->json([
                            'status' => 'success',
                            'categorie' => $categorie
                        ])->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 already exists.'
                ])->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(CategorieDeleteRequest $request, $id)
    {
        try {

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

            //Obtenir la categorie
            $categorie = Categorie::on('tenant')->findOrFail($id);

            //Suppression de la categorie selon le mode
            if($request->mode == "soft"){

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

                if(Document::on('tenant')->where('categorie_id', '=', $categorie->id)->get()){

                    $documents = Document::on('tenant')->where('categorie_id', '=', $categorie->id)->get();

                    foreach($documents as $document){

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

                }

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

            }else if($request->mode == "strict"){

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

        } catch (Exception $e) {

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

        }
    }
}
