<?php

require_once AF2_INTEGRATION_HANDLER_CLASS;
class ActiveCampaign_Integration extends Af2Integration {

    public function get_credential_fields() {
        return array( 
            array( 'key' => 'api_url', 'option_value' => 'af2_ac_url', 'icon' => 'fas fa-link', 'label' => 'API URL:', 'type' => 'text' ),
            array( 'key' => 'api_key', 'option_value' => 'af2_ac_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_url']) || empty($credentials['api_url'])) return false;
        if(!isset($credentials['api_key']) || empty($credentials['api_key'])) return false;

        return true;
    }

    public function get_api_values() { 
        return array(
            array( 'label' => 'vorname', 'type' => 'contactform'),
            array( 'label' => 'name', 'type' => 'contactform'),
            array( 'label' => 'telefon', 'type' => 'contactform'),
            array( 'label' => 'mail', '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' => __('First name', 'af2_multilanguage'), 'required' => false, 'type' => 'select', 'value' => 'vorname' ),
                    array( 'label' => __('Last name', 'af2_multilanguage'), 'required' => false, 'type' => 'select', 'value' => 'name' ),
                    array( 'label' => __('Phone', 'af2_multilanguage'), 'required' => false, 'type' => 'select', 'value' => 'telefon' ),
                    array( 'label' => __('E-mail', 'af2_multilanguage'), 'required' => false, 'type' => 'select', 'value' => 'mail' ),
                ),
            ),
            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'],
            'first_name' => $this->api_values['vorname'],
            'last_name' => $this->api_values['name'],
            'phone' => $this->api_values['telefon'],
            'orgname' => '',
            'tags' => '',
            'p[' . $this->api_values['liste'] . ']' => $this->api_values['liste'], // example list ID (REPLACE '123' WITH ACTUAL LIST ID, IE: p[5] = 5)
            'status[123]' => 1, 
            'instantresponders[123]' => 0, 
        );
        $resp = $this->ac_curl_wrap('contact_add', $dat);
    }

    private function ac_curl_wrap($action, $dat) {
        $credentials = $this->get_credentials();
        // By default, this sample code is designed to get the result from your ActiveCampaign installation and print out the result
        $url = $credentials['api_url'];
    
    
        $params = array(
            // the API Key can be found on the "Your Settings" page under the "API" tab.
            // replace this with your API Key
            'api_key' => $credentials['api_key'],
            'api_action' => $action,
            'api_output' => 'serialize',
        );
    
        // here we define the data we are posting in order to perform an update
        $post = $dat;
    
        // This section takes the input fields and converts them to the proper format
        $query = "";
        foreach ($params as $key => $value) $query .= urlencode($key) . '=' . urlencode($value) . '&';
        $query = rtrim($query, '& ');
    
        // This section takes the input data and converts it to the proper format
        $data = "";
        foreach ($post as $key => $value) $data .= urlencode($key) . '=' . urlencode($value) . '&';
        $data = rtrim($data, '& ');
    
        // clean up the url
        $url = rtrim($url, '/ ');
    
        // This sample code uses the CURL library for php to establish a connection,
        // submit your request, and show (print out) the response.
        /*     * if ( !function_exists('curl_init') ) die('CURL not supported. (introduced in PHP 4.0.2)');
    
          // If JSON is used, check if json_decode is present (PHP 5.2.0+)
          if ( $params['api_output'] == 'json' && !function_exists('json_decode') ) {
          die('JSON not supported. (introduced in PHP 5.2.0)');
          }* */
    
        // define a final API request - GET
        $api = $url . '/admin/api.php?' . $query;
    
        $request = curl_init($api); // initiate curl object
        curl_setopt($request, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from response
        curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
        curl_setopt($request, CURLOPT_POSTFIELDS, $data); // use HTTP POST to send form data
        //curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment if you get no gateway response and are using HTTPS
        curl_setopt($request, CURLOPT_FOLLOWLOCATION, true);
    
        $response = (string) curl_exec($request); // execute curl post and store results in $response
        // additional options may be required depending upon your server configuration
        // you can find documentation on curl options at http://www.php.net/curl_setopt
        curl_close($request); // close curl object
    
        if (!$response) {
            return 'EIN FEHLER KAM RAUS';
        }
    
        // This line takes the response and breaks it into an array using:
        // JSON decoder
        //$result = json_decode($response);
        // unserializer
        $result = unserialize($response);
        // XML parser...
        // ...
    
        $res = '';
        // Result info that is always returned
        $res .= 'Result: ' . ( $result['result_code'] ? 'SUCCESS' : 'FAILED' ) . '<br />';
        $res .= 'Message: ' . $result['result_message'] . '<br />';
    
        // The entire result printed out
        $res .= 'The entire result printed out:<br />';
        $res .= '<pre>';
        //print_r($result);
        $res .= '</pre>';
    
        // Raw response printed out
        $res .= 'Raw response printed out:<br />';
        $res .= '<pre>';
        //print_r($response);
        $res .= '</pre>';
    
        // API URL that returned the result
        $res .= 'API URL that returned the result:<br />';
        $res .= $api;
    
        $res .= '<br /><br />POST params:<br />';
        $res .= '<pre>';
        //print_r($post);
        $res .= '</pre>';
    
        return $res;
    }

    public function fetch_fields_from_api() { 
        $credentials = $this->get_credentials();
       
        return array(
            'list' => $this->get_list_fields($credentials),
        );
    }

    private function get_list_fields($credentials) {
        $url = $credentials['api_url'];


        $params = array(
            'api_key' => $credentials['api_key'],
            'api_action' => 'list_list',
            'api_output' => 'json',
            'ids' => 'all',
            'full' => 1,
        );
    
        // This section takes the input fields and converts them to the proper format
        $query = "";
        foreach ($params as $key => $value) $query .= urlencode($key) . '=' . urlencode($value) . '&';
        $query = rtrim($query, '& ');
    
        // clean up the url
        $url = rtrim($url, '/ ');
    
        // This sample code uses the CURL library for php to establish a connection,
        // submit your request, and show (print out) the response.
        if (!function_exists('curl_init'))
            return array(); //'CURL not supported. (introduced in PHP 4.0.2)';
    
        // If JSON is used, check if json_decode is present (PHP 5.2.0+)
        if ($params['api_output'] == 'json' && !function_exists('json_decode')) {
            return array(); //'JSON not supported. (introduced in PHP 5.2.0)');
        }
    
        // define a final API request - GET
        $api = $url . '/admin/api.php?' . $query;
    
        $request = curl_init($api); // initiate curl object
        curl_setopt($request, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from response
        curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
        //curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment if you get no gateway response and are using HTTPS
        curl_setopt($request, CURLOPT_FOLLOWLOCATION, true);
    
        $response = (string) curl_exec($request); // execute curl fetch and store results in $response
        curl_close($request); // close curl object
    
        if (!$response) {
            return array();// 'ERROR';
        }
    
        $result = json_decode($response, true);
    
    
        // Result info that is always returned
        if ($result['result_code']) {
            
        } else {
            return array();
        }

        $final = array();

        foreach($result as $field) {
            if (isset($field['id']))
                array_push($final, array('value' => $field['id'], 'label' => $field['name']));
        }
    
        // The entire result printed out
        return $final;
    }
}