<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Http\Requests\DepartementStoreRequest;
use App\Key;
use Illuminate\Http\Request;
use Exception;

class KeyController extends Controller
{
    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
            $schoolData = $request->get('School');
            // Check if has school already exist
            $schoolExist = Key::where('etablissement_id', $schoolData['idEtablissement'])
            ->where('projet', $request->projet)
            ->get()->count();
            //Add key generated in main keys table to link department to university
            if (Key::where('etablissement_id', $schoolData['idEtablissement'])
            ->where('departement_id', $request->idDepartement)
            ->where('projet', $request->projet)
            ->get()->count() == 1
            ) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Une cle existe deja pour ce projet'

                ])->withHeaders([
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ]);
            } else {

                $key = new Key();
                $key->api_key = $random_key;
                $key->etablissement_id = $schoolData['idEtablissement'];
                if ($request->idDepartement) {
                    $key->departement_id = $request->idDepartement;
                }
                $key->projet = $request->projet;
                //$key->departement_id = hackKey(false, $request->idDepartement);
                $key->bd = 'site_' . $schoolData['bd'];
                $key->save();

                return response()->json([
                    'status' => 'success',
                    'data' => [
                        'api_key' => $key->api_key,
                        'bd' => $key->bd,
                        'schoolExist' => $schoolExist,
                    ],
                    'message' => 'KEY_GENERATED'

                ])->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'
            ]);
        }
    }

}
