<?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;
        }
        return redirect($redirect.'?code=123456&state='.$request->get('state',''));
        #return view('auth', ['app'=>$app,'provider'=>$provider]);
    }

    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"],
            "token_endpoint_auth_methods_supported" => ["client_secret_basic"],
            "claims_supported" => ["sub", "iss", "name", "email", "phone"],
            "code_challenge_methods_supported" => ["plain", "S256"],
            "grant_types_supported" => ["authorization_code", "refresh_token"],
        ]);
    }

    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,
            'LaysenseRole' => 'Member',
        ];
        $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',
            "name" => 'LaySense',
            "email" => 'ywnsya@126.com',
            "phone" => '18018526850',
            "LaysenseRole" => 'Member',
            ]);
    }

}
