<?php

require_once AF2_INTEGRATION_HANDLER_CLASS;
class GetResponse_Integration extends Af2Integration {

	private $auth_type = 'Basic';
	private $baseUri = 'https://api.getresponse.com/v3';

    public function get_credential_fields() {
        return array( 
            array( 'key' => 'api_key', 'option_value' => 'af2_getresponse_api_key',  'icon' => 'fas fa-key', 'label' => 'API Key:', 'type' => 'password'  ),
        );
    }

    public function is_active() { 
        $credentials = $this->get_credentials();

        if(!isset($credentials) || empty($credentials)) return false;
        if(!isset($credentials['api_key']) || empty($credentials['api_key'])) return false;

        return true;
    }

    public function get_api_values() { 
        return array(
            array( 'label' => 'mail', 'type' => 'contactform'),
            array( 'label' => 'name', 'type' => 'contactform'),
            array( 'label' => 'liste', 'type' => 'field'),
        ); 
    }

    public function get_api_draw_fields() { 
        return array(
            array(
                'label' => __('Contact information:', 'af2_multilanguage'),
                'fields' => array(
                    array( 'label' => __('E-mail', 'af2_multilanguage'), 'required' => false, 'type' => 'select', 'value' => 'mail' ),
                    array( 'label' => __('Name', 'af2_multilanguage'), 'required' => false, 'type' => 'select', 'value' => 'name' ),
                ),
            ),
            array(
                'label' => __('List data:', 'af2_multilanguage'),
                'fields' => array(
                    array( 'label' => __('List', 'af2_multilanguage'), 'required' => true, 'type' => 'select_', 'type_label' => 'list', 'value' => 'liste' ),
                ),
            ),
        );
    }

    public function send_to_api() {
        $credentials = $this->get_credentials();

        $dat = array(
            'email'     => $this->api_values['mail'],
            'name' => $this->api_values['name'],
            'campaign'  => array( 'campaignId' => $this->api_values['liste'] ),
        );
        if (isset($_SERVER['REMOTE_ADDR'])) {
            $dat['ipAddress'] = $_SERVER['REMOTE_ADDR'];
        }
        $resp = $this->add_contact($dat);
    }

    public function fetch_fields_from_api() { 
        $credentials = $this->get_credentials();

        $campaigns = $this->get_campaigns();
       
        $final = array();
        foreach($campaigns as $field) {
            if (isset($field['campaignId']))
                array_push($final, array('value' => $field['campaignId'], 'label' => $field['name']));
        }

        return array(
            'list' => $final,
        );
    }

    private 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.
     * */
    private 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()
    {
        $credentials = $this->get_credentials();
        return 'X-Auth-Token: api-key ' . $credentials['api_key'];
    }

    /**
     * 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
     * */

    private function send_request($uri='/', $method = 'GET', $data = '') 
    {

        $header = array(
            'Content-Type: application/json',
            'Accept: application/json'
        );

        $credentials = $this->get_credentials();
        if( $credentials['api_key'] ) 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;      
    }
}