<?php

/**
 * @package: EGPS - Easy Sell for Google Photo
 */

 if(!defined('ABSPATH')){
    exit; // Exit if accessed directly
}

class EgpsAuthenticate{

    private $cip_key, $cip_method, $cip_separator;

    function __construct(){
        $this->cip_method = "AES-128-CBC"; // DO NOT MODIFY
        $this->cip_separator = ":"; // DO NOT MODIFY
    }

    public static function egps_auth_variables(){
        if(isset(get_option('egps_options')['google_client_id'])){
            define("EGPS_G_CLIENT", get_option('egps_options')['google_client_id']);
        }else{
            define("EGPS_G_CLIENT", "");
        }

        if(isset(get_option('egps_options')['google_client_secret'])){
            define("EGPS_G_SECRET", get_option('egps_options')['google_client_secret']);
        }else{
            define("EGPS_G_SECRET", "");
        }

        if(isset(get_option('egps_options')['google_access_token'])){
            define("EGPS_G_ACCESS_TOKEN", get_option('egps_options')['google_access_token']);
        }else{
            define("EGPS_G_ACCESS_TOKEN", "");
        }

        if(isset(get_option('egps_options')['google_refresh_token'])){
            define("EGPS_G_REFRESH_TOKEN", get_option('egps_options')['google_refresh_token']);
        }else{
            define("EGPS_G_REFRESH_TOKEN", "");
        }

        if(isset(get_option('egps_options')['expires_in'])){
            define("EGPS_G_TOKEN_EXPIRETIME", get_option('egps_options')['expires_in']);
        }else{
            define("EGPS_G_TOKEN_EXPIRETIME", "");
        }

        define('EGPS_AUTH_URL', 'https://accounts.google.com/o/oauth2/auth?'.EgpsAuthenticate::egps_build_query_auth());

    }
    
    
    public static function count_token_expire_time($token_expires){
        $date = new DateTime();
        
        $date->getTimestamp();

        if($token_expires != null) {
            $date->add(new DateInterval('PT' . $token_expires . 'S')); // adds secs
        }
        return $date->getTimestamp();
    }

    public static function check_token(){
        $date = new DateTime();
        $timenow = $date->getTimestamp();

        $token_expires = EGPS_G_TOKEN_EXPIRETIME;

        ////******** SECS BERORE UPDATE TOKEN **********///
        if($token_expires != null) {
            if (($token_expires - $timenow) <= 100) {
                EgpsAuthenticate::egps_refresh_token();
            }
        }
        
    }

    public static function egps_save_token($token, $type, $token_expire) { //google_access_token, google_refresh_token, expires_in
        $egps_auth = get_option('egps_options');

        if (!isset($egps_auth)) {
            $egps_auth = [];
        }
        $egps_auth[$type] = $token;
        $egps_auth['expires_in'] = EgpsAuthenticate::count_token_expire_time($token_expire);

        update_option('egps_options', $egps_auth);
    }

    public static function egps_build_query_auth() {
        $params = [
            'response_type' => 'code',
            'redirect_uri' => admin_url('admin.php?page=easy-photo-sell_settings&tab=google_api'),
            'client_id' => EGPS_G_CLIENT,
            'scope' => 'https://www.googleapis.com/auth/photoslibrary.readonly',
            'access_type' => 'offline',
            'state' => md5(EGPS_G_SECRET . 'google').'::'.urlencode(admin_url('admin.php?page=easy-photo-sell_settings&tab=google_api')),
            'prompt' => 'consent'
        ];

        $pairs = [];
        foreach ($params as $key => $value) {
            if (is_array($value)) {
                natsort($value);
                foreach ($value as $v2) {
                    $pairs[] = ($v2 == '') ? "$key=0" : "$key=$v2";
                }
            }
            else {
                $pairs[] = ($value == '') ? "$key=0" : "$key=$value";
            }
        }

        $string = implode('&', $pairs);
        return $string;
    }

    public static function egps_get_token($code){
        $params = [
            'code' => $code,
            'grant_type' => 'authorization_code',
            'client_id' => EGPS_G_CLIENT,
            'client_secret' => EGPS_G_SECRET,
            'redirect_uri' => admin_url('admin.php?page=easy-photo-sell_settings'),
        ];

        $curl_args = [
            'user-agent' => null,
            'timeout' => 90,
            'sslverify' => false,
            'headers' => [],
            'method' => 'POST',
            'body' => $params,
            'cookies' => [],
        ];

        $response = wp_remote_request('https://accounts.google.com/o/oauth2/token', $curl_args);
        return $response;
    }

    public static function egps_refresh_token(){
        $params = [
            'client_id' => EGPS_G_CLIENT,
            'client_secret' => EGPS_G_SECRET,
            'refresh_token' => EGPS_G_REFRESH_TOKEN,
            'grant_type' => 'refresh_token'
        ];

        $curl_args = [
            'user-agent' => null,
            'timeout' => 90,
            'sslverify' => false,
            'headers' => array_merge(['Expect:'], []),
            'method' => 'POST',
            'body' => $params,
            'cookies' => [],
        ];

        $response = wp_remote_request('https://accounts.google.com/o/oauth2/token', $curl_args);

        $egps_token_array = json_decode($response['body'], true);

        if(isset($egps_token_array['access_token'])) {
            EgpsAuthenticate::egps_save_token($egps_token_array['access_token'], 'google_access_token', $egps_token_array['expires_in']);
        }
        return;
    }

    // DO NOT MODIFY
    public function egps_decrypt_key($encryption, $api_key){
        $parts = explode($this->cip_separator, base64_decode($encryption));
        if( isset($parts[1]) && strlen($parts[1]) == 16 ){
            $decryption = openssl_decrypt($parts[0], $this->cip_method, $api_key, 0, $parts[1]);
            return explode("#", $decryption);
        }else{
            return array("", "");
        }
    }
    
    public function egps_auth_siteurl(){
        return explode("://", get_site_url())[1];
    }
    

}