<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\DB;

class CheckSchool
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //hackKey(false, $request->idEtablissement)
         $idEtablissement = $request->route('etablissement') ? $request->route('etablissement') : $request->idEtablissement;
         if (
            DB::table('etablissement')->where('idEtablissement', $idEtablissement)
            ->get()
            ->count() == 1
        ) {
            $school = DB::table('etablissement')->where('idEtablissement', $idEtablissement)->first();

            $schoolData['bd'] = $school->namebase;
            $schoolData['idEtablissement'] = $school->idEtablissement;
            $request['School'] = $schoolData;

            return $next($request);
        } else {
            return response()->json([
                'results' => 'School not exist',
            ]);
        }
    }
}
