<?php

namespace App\Http\Middleware;

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

class VerifySuperAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->header('Authorization')) {
            $key = $request->header('Authorization');
            $valid_keys = ['2131566549', '147893256', '4565931586'];

            // We check API key and UserToken in database
            if ($key != null && in_array($key, $valid_keys)) {
                if (
                    $request->bd != null &&
                    $request->matricule != null &&
                    (
                        (DB::connection($request->bd)
                            ->table('users')
                            ->where('matricule', $request->matricule)
                            ->count() == 1 &&
                            DB::connection($request->bd)
                            ->table('users')
                            ->where('matricule', $request->matricule)
                            ->first()
                            ->type_user == 3) ||
                        (DB::connection($request->bd)
                            ->table('users_student')
                            ->where('matricule', $request->matricule)
                            ->count() == 1 &&
                            DB::connection($request->bd)
                            ->table('users_student')
                            ->where('matricule', $request->matricule)
                            ->first()
                            ->type_user == 3))
                ) {
                    return $next($request);
                } else {
                    return response()->json([
                        'results' => 'USER_PERMISSIONS_NOT_GRANTED'
                    ], 401);
                }
            } else {
                return response()->json([
                    'results' => 'PERMISSIONS_NOT_GRANTED'
                ], 401);
            }
        }

        return response()->json([
            'results' => 'Authorization failed',
        ]);
    }
}
