<?php 
/**
 * GetResponse_integration Class
 * WP Options af2_getresponse_enable, af2_getresponse_api_key
 * @author WDT 
 * @author Shubham Jain
 * @since  Class available since Release 
 * */

class GetResponse_integration
{
    private $auth_credentials = '';
	private $auth_type = 'Basic';
	private $baseUri = 'https://api.getresponse.com/v3';
    
	/**
	 * Class constructor 
	 * */
	function __construct()
	{
        if( function_exists('get_option') )
        {
            $this->auth_credentials = get_option('af2_getresponse_api_key');
        }
	}

    /**
     * Send curl request to verify API key
     * @param string $api_key
     * @return Array : blank array if connection fail
     * */
    public function verify_api_key($api_key){
        $this->auth_credentials = $api_key;
        $accounts = $this->send_request('/accounts');
        $account_response = json_decode($accounts->response, true);
        if( $accounts->code == 200 || $accounts->code == '200' ){
            if ( ! isset( $account_response['accountId'] ) ) {
                return [];
            }
            return $account_response;
        }else{
            return[];
        }
    }

    /**
     * Send curl request to get all campaigns ( Contact lists )
     * @return Array | Exception on any error thrown
     * */
    public function get_campaigns(){
        $campaigns = $this->send_request('/campaigns');
        if( $campaigns->code == 200 || $campaigns->code == '200' ){
            return json_decode($campaigns->response, true);
        }else {
            return [];
        }
    }

    // add contact to list
    /**
     * Send curl request to get all campaigns ( Contact lists )
     * @return string ('added') | Exception on any error thrown | any other string if not added.
     * */
    public function add_contact($contact){
        try {
            $response = $this->send_request('/contacts', 'POST', $contact);
            if( $response->code === 202 || $response->code === '202' )
            {
                return 'added';
            }
            else
            {
                $result = json_decode( $response->response, true );
                if( isset( $result['detail'] ) ) return $result['detail'];
                else return $result['message'];
                // return json_decode( $response->response, true )['detail'];
            }
        } catch (\Throwable $th) {
            return $th;
        }
    }

    private function get_auth_string()
    {
        return 'X-Auth-Token: api-key ' . $this->auth_credentials;
    }

    /**
     * Send curl request to the given url
     * @param $uri string optional - use if you want to break the url in to base url and action path 
     * @param $method string default GET 
     * @param $data array|string (json string)
     * @return object | Error Exception on success full hit response object with response, code and meta
     * */

    public function send_request($uri='/', $method = 'GET', $data = '') 
    {
        $header = array(
            'Content-Type: application/json',
            'Accept: application/json'
        );

        if( $this->auth_credentials) array_push( $header, $this->get_auth_string());

        $method = strtoupper($method);
        $data = is_array($data) ? json_encode($data) : $data;

        $requestUri = '';
        if( $uri )
        {
            $requestUri = $this->baseUri . $uri;
        }
        else
        {
            throw new Exception('Not a valid request url');
        }

        if( empty($requestUri) ) throw new Exception('Not a valid request url');
        
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $requestUri);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false); // optional
        curl_setopt($curl, CURLOPT_MAXREDIRS, 1);  // optional 
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        
        // use if normal username password authentication is required.
        // curl_setopt($curl, CURLOPT_USERPWD, $username . ':' . $password); 
        
        if($method == 'POST'){
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        else if ($method == 'PUT'){
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        else if($method != 'GET'){
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        }
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // optional if debug
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // optional if debug
        // curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        $result = new StdClass();

        $result->response = curl_exec($curl);
        $result->code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $result->meta = curl_getinfo($curl);
        
        $curl_error = ($result->code > 0 ? null : curl_error($curl) . ' (' . curl_errno($curl) . ')');
        curl_close($curl);
        
        if ($curl_error) {
            throw new Exception('An error occurred while connecting to endpoint: ' . $curl_error);
        }
        return $result;      
    }

}
