<?php

namespace app\service;

use GuzzleHttp\Client;
use think\facade\Db as ThinkDb;

class GoogleOAuthService
{
    public function getAuthUrl()
    {
        $clientId     = getenv('GOOGLE_CLIENT_ID');
        $redirectUri  = getenv('GOOGLE_REDIRECT_URI');
        $scope        = 'https://www.googleapis.com/auth/adwords';
        $responseType = 'code';
        $accessType   = 'offline';

//        $state        = 'state_parameter_passthrough_value'; // 可选,保护防止CSRF
        // 生成随机的state参数,防止CSRF攻击
//        $state = bin2hex(random_bytes(16)); // 生成一个随机字符串
        // 将state保存到会话或数据库中,稍后验证
//        $_SESSION['oauth_state'] = $state;  // 使用PHP会话来保存state

//        $authUrl = "https://accounts.google.com/o/oauth2/v2/auth?client_id=$clientId&redirect_uri=$redirectUri&scope=$scope&response_type=$responseType&state=$state";
        $authUrl = "https://accounts.google.com/o/oauth2/v2/auth?client_id=$clientId&redirect_uri=$redirectUri&scope=$scope&response_type=$responseType&access_type=$accessType";

        return $authUrl;
    }


    public function getRefreshToken($authCode)
    {
        $client   = new Client();
        $response = $client->post('https://oauth2.googleapis.com/token', [
            'form_params' => [
                'code' => $authCode,
                'client_id' => getenv('GOOGLE_CLIENT_ID'),
                'client_secret' => getenv('GOOGLE_CLIENT_SECRET'),
                'redirect_uri' => getenv('GOOGLE_REDIRECT_URI'),
                'grant_type' => 'authorization_code',
            ],
        ]);

        return json_decode($response->getBody(), true);
    }

    public function saveRefreshToken($refreshToken, $accessToken)
    {
        // 使用ThinkORM保存数据到bps_third_user表
//        $thirdUser               = new \App\Models\ThirdUser();
//        $thirdUser->access_token = $accessToken;
//        $thirdUser->is_default   = true;
//        $thirdUser->random_code  = bin2hex(random_bytes(16)); // 生成随机码
//        $thirdUser->third_type   = 'google';
//        $thirdUser->user_id      = $userId;
//        $thirdUser->save();
        $data = [
            'access_token' => $refreshToken,
            'is_default' => 't',
            'third_type' => 'google',
            ];
        $tableName = 'bps_third_user';
        $tableName = getenv('DB_PG_SCHEMA') ? getenv('DB_PG_SCHEMA') . '.' . $tableName : 'bps' . $tableName;

        $sql = "
                    INSERT INTO {$tableName}
                    (access_token, is_default,  third_type)
                    VALUES (:access_token, :is_default,  :third_type)
                    ON CONFLICT (user_id) 
                    DO UPDATE SET
                        access_token = EXCLUDED.access_token,
                        is_default = EXCLUDED.is_default,
                ";
//        $sql = "
//                    INSERT INTO {$tableName}
//                    (access_token, is_default, random_code, third_type, user_id, facebook_user_id)
//                    VALUES (:access_token, :is_default, :random_code, :third_type, :user_id, :facebook_user_id)
//                    ON CONFLICT (user_id)
//                    DO UPDATE SET
//                        access_token = EXCLUDED.access_token,
//                        is_default = EXCLUDED.is_default,
//                        random_code = EXCLUDED.random_code,
//                        third_type = EXCLUDED.third_type,
//                ";

        ThinkDb::execute($sql, $data);
    }


    public function revokeToken($accessToken)
    {
        $client = new Client();
        $client->post('https://oauth2.googleapis.com/revoke', [
            'form_params' => [
                'token' => $accessToken,
            ],
        ]);

        // 在数据库中删除或标记该`refresh_token`为无效
//        \App\Models\ThirdUser::where('access_token', $refreshToken)->delete();
    }

    public function useRefreshToken($refreshToken)
    {
        $client   = new Client();
        $response = $client->post('https://oauth2.googleapis.com/token', [
            'form_params' => [
                'refresh_token' => $refreshToken,
                'client_id' => getenv('GOOGLE_CLIENT_ID'),
                'client_secret' => getenv('GOOGLE_CLIENT_SECRET'),
                'grant_type' => 'refresh_token',
            ],
        ]);

        $data = json_decode($response->getBody(), true);
        return $data['access_token'];
    }


}