<?php

namespace App\Http\Middleware;

use Closure;

class CheckUserOperatingSystem
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $userAgent = $request->userAgent();
        $clientOS = 'WIN';

        $operatingSystems  = [
            '/windows nt 10/i'      =>  'WIN',
            '/windows nt 6.3/i'     =>  'WIN',
            '/windows nt 6.2/i'     =>  'WIN',
            '/windows nt 6.1/i'     =>  'WIN',
            '/windows nt 6.0/i'     =>  'WIN',
            '/windows nt 5.2/i'     =>  'WIN',
            '/windows nt 5.1/i'     =>  'WIN',
            '/windows xp/i'         =>  'WIN',
            '/windows nt 5.0/i'     =>  'WIN',
            '/windows me/i'         =>  'WIN',
            '/win98/i'              =>  'WIN',
            '/win95/i'              =>  'WIN',
            '/win16/i'              =>  'WIN',
            '/macintosh|mac os x/i' =>  'APPLE',
            '/mac_powerpc/i'        =>  'APPLE',
            '/linux/i'              =>  'LINUX',
            '/ubuntu/i'             =>  'LINUX',
            '/iphone/i'             =>  'APPLE',
            '/ipod/i'               =>  'APPLE',
            '/ipad/i'               =>  'APPLE',
            '/android/i'            =>  'ANDROID',
            '/blackberry/i'         =>  'BLACKBERRY',
            '/webos/i'              =>  'MOBILE'
        ];

        foreach ($operatingSystems as $regex => $value){
            if (preg_match($regex, $userAgent)){
                $clientOS = $value;
            }
        }

        $request->merge(['operating_system' => $clientOS]);
        return $next($request);
    }
}
