<?php

namespace App\Http\Controllers\API\v1;

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

class DocUtileController extends Controller
{

    public function index(Request $request)
    {
        try {

            if (request('type')){
                $category = DB::connection('tenant')->table('categories_docs_utiles')
                    ->where('nom', '=', request('type'))
                    ->first();
            }

            $SchoolDepInfo= $request->get('SchoolDep');
            $departement = $SchoolDepInfo['departement_id'];
            if($departement != 1000000) {

                if (request('type')){
                    $documents = DB::connection('tenant')->table('docs_utiles')
                        ->where('departement_id','=',$departement)
                        ->where('categorie_id', '=', $category->id)
                        ->orderBy('categorie_id')
                        ->get();
                }else{

                    $documents = DB::connection('tenant')->table('docs_utiles')
                        ->where('departement_id','=',$departement)
                        ->orderBy('categorie_id')
                        ->get();
                }

            } else {
                if (request('type')){
                    $documents = DB::connection('tenant')->table('docs_utiles')
                    ->where('categorie_id', '=', $category->id)
                    ->orderBy('categorie_id')
                    ->get();
                }else{
                    $documents = DB::connection('tenant')->table('docs_utiles')
                    ->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'
            ]);

        }
    }

    public function store(Request $request)
    {
        try {

            $categorie = DB::connection('tenant')->table('categories_docs_utiles')->where('id', '=', $request->categorie)->first();

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

            $inputData = [
                'nom'           => $request->nom,
                'description'   => $request->description,
                'url'           => $request->url,
                'user_matricule'=> $User->matricule,
                'categorie_id'  => $categorie->id,
                'departement_id'=> $departement
            ];

            $result = DB::connection('tenant')->table('docs_utiles')->insert($inputData);

            return response()->json([
                'status' => 'success',
            ])->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 show(Request $request ,$id)
    {
        try {

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

            } else {
		          $document = DB::connection('tenant')->table('docs_utiles')
                  ->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'
            ]);

        }
    }

    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 (DB::connection('tenant')->table('docs_utiles')->where('id',$id)->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 = DB::connection('tenant')->table('categories_docs_utiles')->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) {



                            $result = DB::connection('tenant')->table('docs_utiles')->where('id','=',$id)->update(
                                [
                                    'user_matricule' => $User->matricule,
                                    'statut' =>  $request->statut,
                                    'description' => $request->description,
                                    'nom' => $request->nom,
                                    'url' => $request->url
                                ]
                            );

                            // $document = DB::connection('tenant')->table('docs_utiles')->findOrFail($id);
                            // $document->user_matricule = $User->matricule;
                            // $document->statut = $request->statut;
                            // $document->description = $request->description;
                            // $document->nom = $request->nom;
                            // $document->url = $request->url;
                            // $document->update();

                            return response()->json([
                                'status' => 'success',
                                'message' => 'Updated succesfully.'
                            ])->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'
            ]);
        }
    }

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

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

            //On récupère le document
            $document = DB::connection('tenant')->table('docs_utiles')->where('id','=',$id)->first();

            //Verifier si l'utilisateur est autorisé à supprimer ce document

            $doc_name = $document->url;
            DB::connection('tenant')->table('docs_utiles')->where('id','=',$id)->delete();
            // $document->delete();
            return response()->json([
                'status' => 'success',
                'document' => $doc_name
            ])->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'
            ]);
        }
    }
}
