<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;

class managerAuthMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if($this->get_auth()){
            return $next($request);
        } else {
            return Redirect::to('http://manager.stroyprofit.com');
        }
    }

    private function get_auth()
    {
        $user = session('user', false);
//        dd($user);
        if (!isset($user['id'])) {
            if(!isset($_COOKIE['ci_session'])) return false;
            $opts = array(
                'http' => array(
                    'method' => "GET",
                    'header' => "Accept-language: en\r\n" .
                        "Cookie: ci_session=" . $_COOKIE['ci_session'] . "\r\n"
                )
            );

            $context = stream_context_create($opts);
            $response = json_decode(file_get_contents('http://manager.stroyprofit.com/check_auth', false, $context), true);

            if ($response['auth'] != true) {

                return false;
            } else {
                session(['user' => $response['user']]);

            }
        }
        return true;
    }

}
