<?php

namespace App\Http\Middleware;

use Closure;
use DB;
use Hash;

class MobileAccessMiddleware
{
    /* Defining constants for error messages. */
    const WRONG_PASSWORD = ['failed' => 'password'];
    const WRONG_EMAIL = ['failed' => 'email'];
    const NO_JSON_BODY = ['failed' => 'json'];

    /**
     * Handle an incoming request for access to SkillCourtWeb DB.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $query = 'SELECT * FROM users WHERE email = ?';

        // check for json data
        if ($data = $request->json()->all())
        {
            $result_set = DB::select($query, [$data['email']]);

            // check result from DB
            if (empty($result_set))
            {
                return response(self::WRONG_EMAIL, 200);
            }
            else
            {
                $credentials = $result_set[0];
                
                if (Hash::check($data['password'], $credentials->password))
                {
                    // pass request onto the MobileController
                    return $next($request); 
                }
                
                return response(self::WRONG_PASSWORD, 200); 
            }
        }
        else
        {
            return response(self::NO_JSON_BODY, 200);
        }
    }
}