<?php

namespace app\controller;

use support\Request;
use support\Db;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class OAuth
{
    public function authorize(Request $request)
    {
        $appid=$request->get('client_id','null');
        if($appid=='null'){
            return view('404');
        }
        $appquery= Db::table('App')->where('oauthid', $appid);
        if($appquery->doesntExist()){
            return view('404');
        }
        $app=$appquery->first();
        $provider= Db::table('Provider')->where('ID', $app->provider)->first();
        $redirect=$request->get('redirect_uri','null');
        if($redirect=='null'){
            $redirect=$app->redirect;
        }
        $scope=$request->get('scope','openid');
         $scope=explode("+",$scope);
         $allow_scope=json_decode($app->scope,true);
        $scope=array_intersect($scope,$allow_scope);
        $session = $request->session();
        $session->set($appid.'_oauth_redirect', $redirect);
        $session->set($appid.'_oauth_scope', $scope);

        $redirecturl='https://'.getenv('weburl').'/auth/oauth/back/'.$appid;
        return view('auth', ['app'=>$app,'provider'=>$provider,'redirecturl'=>$redirecturl]);

        #return redirect($redirect.'?code=123456&state='.$request->get('state',''));
        #return view('auth', ['app'=>$app,'provider'=>$provider]);
    }
    public function callback(Request $request,$appid,$gateway)
    {
        $appquery= Db::table('App')->where('oauthid', $appid);
        if($appquery->doesntExist()){
            return view('404');
        }
        $app=$appquery->first();
        $provider= Db::table('Provider')->where('ID', $app->provider)->first();
        $redirecturl='https://'.getenv('weburl').'/auth/oauth/back/'.$appid;

        switch ($gateway) {
            case "qywx":
                $code = $request->input('code','null');
                if($code=='null'){
                    return view('auth', ['app'=>$app,'provider'=>$provider,'special'=>'登陆信息无效','redirecturl'=>$redirecturl]);
                }
                $tokenfile=base_path().'/token/qywx/innerQYWX.token';
                if(file_exists($tokenfile)){
                    $tokencontent=json_decode(file_get_contents($tokenfile));
                    $fulltoken=$tokencontent->token;
                    $ddl=$tokencontent->ddl;
                    if($ddl-time()<180){
                        $reapply=true;
                    }else{
                        $reapply=false;
                    }
                }else{
                    $reapply=true;
                }
                if($reapply==true){
                    $apply=$response = Http::get('https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='.getenv('appid').'&corpsecret='.getenv('token'))->json();
                    $fulltoken=$apply->access_token;
                        $ddl=time()+$apply->expires_in;
                        $file=fopen($tokenfile,"w");
                        fwrite($file, json_encode(array('token'=>$fulltoken,'ddl'=>$ddl)));
                        fclose($file);
                }
                $lookup= Http::get('https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token='.$fulltoken.'&code='.$code)->json();
                if($lookup->errcode!=0){
                    return view('auth', ['app'=>$app,'provider'=>$provider,'special'=>'登陆信息无效','redirecturl'=>$redirecturl]);
                }
                $userid=$lookup->userid;
                $userinfo=Http::get('https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token='.$fulltoken.'&userid='.$userid)->json();
                $username=$userinfo->name;
                $userposition=$userinfo->position;
                $WT=json_encode(['id'=>$userid,'name'=>$username,'position'=>$userposition,'time'=>time()]);
                $key = getenv('aeskey');
                $iv = getenv('aesiv');
                $WT = encryptAES($WT, $key, $iv);  
                $dest=$app->redirect;
                return view('success', ['app'=>$app,'provider'=>$provider,'dest'=>$dest,'userinfo'=>$userinfo])->cookie('WT', $WT,time()+9600,'/','.laysense.cn');
                break;
            default:
                return view('auth', ['app'=>$app,'provider'=>$provider,'special'=>'验证方式无效或不存在','redirecturl'=>$redirecturl]);
        }
    }

    public function configfile(Request $request)
    {

        return json([
            "issuer" => 'https://'.getenv('weburl').'/',
            "authorization_endpoint" => 'https://'.getenv('weburl').'/auth/oauth/authorize',
            "token_endpoint" => 'https://'.getenv('weburl').'/auth/oauth/token',
            "userinfo_endpoint" => 'https://'.getenv('weburl').'/auth/oauth/userinfo',
            "response_types_supported" => ["code"],
            "subject_types_supported" => ["public"],
            "id_token_signing_alg_values_supported" => ["RS256"],
            "scopes_supported" => ["openid", "profile", "email", "phone", "avatar","basic","detail","everything"],
            "token_endpoint_auth_methods_supported" => ["client_secret_basic"],
            "claims_supported" => ["sub", "iss", "name", "email", "phone","LaysenseRole","avatar","phone","address","age","sex","birthday"],
            "code_challenge_methods_supported" => ["plain", "S256"],
            "grant_types_supported" => ["authorization_code"],
        ]);
    }

    public function token(Request $request)
    {
        $key = 'b662c3012510ef3105e557b7b1db0805fb012911';
        $payload = [
            'iss' => 'https://auth.laysense.cn/',
            'aud' => 'laysensegit',
            'sub' => 'ywnsya',
            'iat' => time(),
            'nbf' => time()+7200,
            'exp' => time()+7200,
        ];
        $jwt = JWT::encode($payload, $key, 'HS256');

            return json([
            "access_token" => 'x48KsWYMGBNU3RVSs2vBkjFKTZQZF5vTMiMmyTUiZ0dvXTuodZzWUXIAt2CllbGKHob_ALaE',
            "id_token" => $jwt,
            "token_type" => 'Bearer',
            "expires_in" => 7200,
            "scope"=>"openid profile email photo"
            ])->withHeaders([
                'Cache-Control' => 'no-store',
                'Pragma' => 'no-cache',
            ]);
        
    }
    public function userinfo(Request $request)
    {
        return json([
            "sub" => 'ywnsya',
            'iss' => 'https://auth.laysense.cn/',
            "name" => 'LaySense',
            "email" => 'ywnsya@126.com',
            "phone" => '18018526850',
            "LaysenseRole" => 'Member',
            ]);
    }

}
