<?php

namespace App\Http\Controllers\API\v1;

use App\Departement;
use App\Http\Controllers\Controller;
use App\Http\Requests\DepartementStoreRequest;
use App\Key;
use App\Log;
use App\User;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DepartementController extends Controller
{
    // public function __construct()
    // {
    //     $this->middleware('verify_user_is_admin', ['only' => ['destroy', 'update']]);
    // }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        try {
            $server_response = getFromGest('api/v1/ecole/departements')->json();

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(DepartementStoreRequest $request)
    {
        try {
            //New key for the department
            $random_key = gen_api_key();

            //Recupérer les informations sur l'école et sur le département depuis GestApi
            $etablissement = getFromGest('api/v1/etablissement/' . $request->idEtablissement)->json();

            if ($etablissement['data'] != null) {
                $departement = getFromGest('api/v1/etablissement/departement/' . $request->idDepartement, [
                    'bd' => $etablissement['data']['namebase']
                ])->json();

                if ($departement['data'] != null) {
                    //Creation of the department
                    DB::disconnect('tenant');
                    if(changeEnv(['DB_DATABASE_SECOND'   => 'site_' . $etablissement['data']['namebase']])){
                        $dep = new Departement('tenant');
                        $dep->api_key = $random_key;
                        $dep->gest_id = $departement['data']['idDepartement'];
                        $dep->save();


                        //Add key generated in main keys table to link department to university
                        $key = new Key();
                        $key->api_key = $random_key;
                        $key->etablissement_id = $etablissement['data']['idEtablissement'];
                        $key->departement_id = $dep->id;
                        $key->bd = 'site_' . $etablissement['data']['namebase'];
                        $key->save();
                    } else {
                        return response()->json([
                            'message' => 'impossible de balancer la connection',
                        ]);
                    }


                }
            }

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

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

    /**
     * Verify an API key
     */
    public function authenticate(Request $request){

        try {

            /*$request->validate([
                'api_key' => 'required',
            ]);*/

            if(Key::where('api_key','=',$request->bearerToken())->first()){

                $api_key = Key::where('api_key','=',$request->bearerToken())->first();

                return response()->json([
                    'status' => 'success',
                    'api_key' => [
                        'bd' => hackKey(true,$api_key->bd),
                        'departement_id' => $api_key->departement_id !== null ? hackKey(true,$api_key->departement_id) : $api_key->departement_id
                    ]
                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            }
            else{
                return response()->json([
                    'status' => 'error',
                    'message' => 'KEY_NOT_FOUND'
                ], 404)->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'
            ]);
        }

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, $id)
    {
        $request->validate([
            'mode' => ['nullable', 'in:soft,strict']
        ]);
        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');

            //Update of the departement
            $departement = Departement::on('tenant')->findOrFail($id);

            //Verify if the user requesting is the owner of the article
            if ($request->mode != null && $request->mode == 'strict') {

                //Save the operation
                $log = new Log();

                $departement->delete();

                $log->bd = $bd;
                $log->operation = 'DEPARTEMENT DELETE STRICT';
                $log->description = json_encode($departement);
                $log->user_matricule = $User->matricule;
                $log->save();

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

                //Sauvegarder l'opération
                $log = new Log();
                $log->bd = $bd;
                $log->operation = 'DEPARTEMENT DELETE';
                $log->description = json_encode($departement);
                $log->user_matricule = $User->matricule;
                $log->save();

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