<?php
declare (strict_types = 1);

namespace asc\line;

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

class LineLogin
{
    private $channelId;
    private $channelSecret;

    public function __construct($channelId, $channelSecret)
    {
        $this->channelId = $channelId;
        $this->channelSecret = $channelSecret;
    }

    public function getLoginUrl($site_code)
    {
        $url = 'https://access.line.me/oauth2/v2.1/authorize?';
        $url .= 'response_type=code';
        $url .= '&client_id='.$this->channelId;
        $url .= '&redirect_uri=https://'.$_SERVER['HTTP_HOST'].'/login/linecallback/vip/'.$site_code;
        $url .= '&state='.$_SERVER['REQUEST_URI'];
        $url .= '&bot_prompt=aggressive';
        $url .= '&scope=openid%20profile';

        return $url;    	
    }

    public function getLineToken($code)
    {
		$client = new Client();

        $response = $client->request('POST', 'https://api.line.me/oauth2/v2.1/token', [
            'form_params' => [
                'grant_type' => 'authorization_code',
                'code' => $code,
                'redirect_uri' => 'https://c3d3-220-129-67-224.jp.ngrok.io/m/login',
                'client_id' => $this->channelId,
                'client_secret' => $this->channelSecret
            ]
        ]);

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

    public function getUserProfile($token)
    {
        $client = new Client();
        $headers = [
            'Authorization' => 'Bearer ' . $token,
            'Accept'        => 'application/json',
        ];
        $response = $client->request('GET', 'https://api.line.me/v2/profile', [
            'headers' => $headers
        ]);
        return json_decode($response->getBody()->getContents(), true);    	
    }

    public function verifyToken($token)
    {
        $client = new Client();
        $response = $client->request('GET', 'https://api.line.me/oauth2/v2.1/verify', [
            'query' => [
            	'access_token' => $token
            ]
        ]);
        return json_decode($response->getBody()->getContents(), true);    	
    }

    /**
     * 驗證 id token
     */
    public static function verifyIdToken($client_id, $id_token)
    {
        try{
            $client = new Client();
            $response = $client->request('POST', 'https://api.line.me/oauth2/v2.1/verify', [
                'form_params' => [
                    'id_token' => $id_token,
                    'client_id'=> $client_id    
                ]
            ]);    
            // print_r($response);
            $body = $response->getBody()->getContents();

            return json_decode($body, true);

    	} catch (\Exception $e) {
            return false;   
        }    

    }    
}
