<?php

namespace App\Http\Controllers;

use App\Services\AccessToken;
use App\Services\CookieService;
use App\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Laravel\Lumen\Routing\Controller as BaseController;

class Controller extends BaseController
{
    protected $userId;
    protected $activityId;
    protected $corpId;
    protected $user;
    public function __construct(Request $request)
    {
        try{
            $this->activityId = $request->get("activity_id");
            $userData = CookieService::getBsAuthUser();
            Log::info($userData);
            if ($userData){
                $user = UserService::getInstance()->getUser($userData["user_id"]);
                if($user){
                    if($this->activityId==$userData["activity_id"]){
                        if(AccessToken::getInstance()->getAccessToken($user["user_id"])!=CookieService::getBsAccessToken()){
                            $accessToken = AccessToken::getInstance()->create($user);
                            setcookie("bs_access_token", $accessToken,null,"/",env("COOKIE_DOMAIN"));
                        }
                        $this->userId = $userData["user_id"];
                        $this->user = $user;
                        $this->corpId = $user["corp_id"];

                    }else{

                        Log::info("activity_id not correct");
                        die(json_encode(["error"=>302,"message"=>config("errMsg.not_oauth"),"redirect"=>env("WEB_URL")."/frontend?activity_id=".$this->activityId]));
                    }
                }else{
                    Log::info("user not found");
                    die(json_encode(["error"=>302,"message"=>config("errMsg.not_oauth"),"redirect"=>env("WEB_URL")."/frontend?activity_id=".$this->activityId]));
                }
            }else{
                Log::info("not auth");
                die(json_encode(["error"=>302,"message"=>config("errMsg.not_oauth"),"redirect"=>env("WEB_URL")."/frontend?activity_id=".$this->activityId]));
            }
        }catch (\Exception $exception){
            Log::info($exception->getTraceAsString());
            die(json_encode(["error"=>302,"message"=>config("errMsg.not_oauth"),"redirect"=>env("WEB_URL")."/frontend?activity_id=".$this->activityId]));
        }
    }
}
