<?php

namespace App\Http\Middleware;

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

use Session;

class LoadTenant
{
    /**
     * 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)
    {
        try {
            config(['app.user_agent'=> $request->userAgent()]);
            $domain = request()->getHost();
            
            if($domain == 'localhost' || $domain == '127.0.0.1') {
                $domain = "epac.eservices.geststudent.net";
            }
            else if ($domain == "iut.eservices.up-university.bj") {
                $domain = "iut-parakou.eservices.africawebstudent.org";
            }
            
            $a = explode(".", $domain);

            $tenant = [];
            $tenant['identifier'] = $a[0];
            unset($a[0]);
            $tenant['domain'] = implode('.', $a);

            // if (!Cookie::get('client_key') || !session()->has('school_info') ) {
            if (!(Cookie::get('client_key') && session()->has('school_info'))) {
                config(['session.lifetime'=> 3600*24*5 ]);// set timeout to 5 days
                # here make request to take client id
                $data = [];
                $data['tenant'] = $tenant;
                $req = reqGest('POST', 'api/v1/eservices/load', $data, 1, $tenant['domain']);

                if ($req && $req['success']) {
                    // Now store it in cookies (encrypted)
                    config(['app.client_key'=> $req['data']['client_id']]);
                    //Store school info in session
                    $school_info = $req['data']['school_info'];

                    Session::forget('school_info');
                    Session::put('school_info', $school_info);
                    Session::save();

                    // Add customer identifer
                    $request['identifier'] = $tenant['identifier'];
                    $request['domain'] = $tenant['domain'];
                    return $next($request)->withCookie(cookie('client_key', $req['data']['client_id'], 0));
                } else {
                    return response()->view('errors.500');
                }
            }

            config(['app.client_key'=> Cookie::get('client_key')]);

            // Add customer identifer
            $request['identifier'] = $tenant['identifier'];
            $request['domain'] = $tenant['domain'];
            return $next($request);

        } catch (Exception $e) {
            // TO DO
        }
    }
}
