<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;

class CategorieDocController extends Controller
{
    public function index(Request $request)
    {
        try {

            $categories = DB::connection('tenant')->table('categories_docs_utiles')
            ->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'
            ]);

        }

    }

    public function store(Request $request)
    {
        try {

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

            $User= $request->get('User');
            $result = DB::connection('tenant')->table('categories_docs_utiles')->where('nom',$request->nom)->first();
            //On vérifie si le nom de la categorie existe déjà

            if(empty($result)){

                $inputData = [
                    'nom' => $request->nom,
                    'slug' => Str::slug($request->nom, '_'),
                    'user_matricule' => $User->matricule,
                ];

                DB::connection('tenant')->table('categories_docs_utiles')->insert($inputData);

                return response()->json([
                    'status' => 'success',
                    'message' => 'Category created successfully'
                ])->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'
            ]);

        }
    }

    public function update(Request $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(!(DB::connection('tenant')->table('categories_docs_utiles')->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){

                        DB::connection('tenant')->table('categories_docs_utiles')->where('id','=',$id)->update(
                            [
                                'nom' => $request->nom,
                                'statut' =>  $request->statut,
                            ]
                        );

                        return response()->json([
                            'status' => 'success',
                            'message' => 'Category created successfully'
                        ])->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'
            ]);

        }
    }

    public function destroy(Request $request, $id)
    {
        try {

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

            //Obtenir la categorie
            $result = DB::connection('tenant')->table('categories_docs_utiles')->where('id','=',$id)->delete();

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

        }
    }
}
