<?php

require_once AF2_INTEGRATION_HANDLER_CLASS;
class HubSpot_Integration extends Af2Integration {

    public function get_credential_fields() {
        return array( 
            array( 'key' => 'api_key', 'option_value' => 'af2_hubspot_key', 'icon' => 'fas fa-key', 'label' => 'Access Token:', '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' => 'email', 'type' => 'contactform'),
            array( 'label' => 'firstname', 'type' => 'contactform'),
            array( 'label' => 'lastname', 'type' => 'contactform'),
            array( 'label' => 'phone', 'type' => 'contactform'),
            array( 'label' => 'company', 'type' => 'contactform'),
            array( 'label' => 'website', 'type' => 'contactform'),
            array( 'label' => 'dealname', 'type' => 'text'),
            array( 'label' => 'pipeline', 'type' => 'field'),
            array( 'label' => 'dealstage', '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' => true, 'type' => 'select', 'value' => 'email' ),
                    array( 'label' => __('First name', 'af2_multilanguage'), 'required' => false, 'type' => 'select', 'value' => 'firstname' ),
                    array( 'label' => __('Last name', 'af2_multilanguage'), 'required' => false, 'type' => 'select', 'value' => 'lastname' ),
                    array( 'label' => __('Website', 'af2_multilanguage'), 'required' => false, 'type' => 'select', 'value' => 'website' ),
                    array( 'label' => __('Company', 'af2_multilanguage'), 'required' => false, 'type' => 'select', 'value' => 'company' ),
                    array( 'label' => __('Phone', 'af2_multilanguage'), 'required' => false, 'type' => 'select', 'value' => 'phone' ),
                ),
            ),
            array(
                'label' => __('Deal details:', 'af2_multilanguage'),
                'fields' => array(
                    array( 'label' => __('Deal name', 'af2_multilanguage'), 'required' => true, 'type' => 'text', 'value' => 'dealname' ),
                    array( 'label' => __('Pipeline', 'af2_multilanguage'), 'required' => true, 'type' => 'select_', 'conditioned' => 'dealstage' , 'type_label' => 'pipeline', 'value' => 'pipeline' ),
                    array( 'label' => __('Deal status', 'af2_multilanguage'), 'required' => true, 'type' => 'select_conditioned', 'conditioned_from' => 'pipeline', 'type_label' => 'dealstage', 'value' => 'dealstage' ),
                ),
            ),
        );
    }

    public function send_to_api() {
        $contact_prop = array(
            'properties' => array(
                array(
                    'property' => 'email',
                    'value' => $this->api_values['email']
                ),
                array(
                    'property' => 'firstname',
                    'value' => $this->api_values['firstname']
                ),
                array(
                    'property' => 'lastname',
                    'value' => $this->api_values['lastname']
                ),
                array(
                    'property' => 'phone',
                    'value' => $this->api_values['phone']
                ),
                array(
                    'property' => 'company',
                    'value' => $this->api_values['company']
                ),
                array(
                    'property' => 'website',
                    'value' => $this->api_values['website']
                ),
            )
        );

        $resp = $this->send_request('/contacts/v1/contact', 'POST', $contact_prop);

        $deal_prop = array(
            array(
                'value' => $this->api_values['dealname'],
                'name' => 'dealname'
            ),
            array(
                'value' => $this->api_values['answer_string'],
                'name' => 'description'
            ),
            array(
                'value' => $this->api_values['dealstage'],
                'name' => 'dealstage'
            ),
            array(
                'value' => $this->api_values['pipeline'],
                'name' => 'pipeline'
            ),
            array(
                'value' => 'newbusiness',
                'name' => 'dealtype'
            ),
        );

        $deal_dat = array(
            'associations' => array(
                'associatedVids' => array(
                    $resp['vid']
                )
            ),
            'properties' => $deal_prop
        );

        $resp = $this->send_request('/deals/v1/deal', 'POST', $deal_dat);
    }

    public function fetch_fields_from_api() { 
        $resp = $this->send_request('/deals/v1/pipelines');
       
        $pipelines = array();
        $stages = array();
        foreach($resp as $field) {
            if (isset($field['pipelineId']) && isset($field['label']) && isset($field['stages']) && is_array($field['stages'])) {
                array_push($pipelines, array('value' => $field['pipelineId'], 'label' => $field['label']));

                $stages[$field['pipelineId']] = array();
                foreach($field['stages'] as $stage) { 
                    if (isset($stage['stageId']) && isset($stage['label'])) {
                        array_push($stages[$field['pipelineId']], array('value' => $stage['stageId'], 'label' => $stage['label']));
                    }
                }
            }
        }

        $return = array(
            'pipeline' => $pipelines,
            'dealstage' => $stages,
        );

        return $return; 
    }

    private function send_request($uri='/', $method = 'GET', $data = '') 
    {
        $baseUri = 'https://api.hubapi.com';

        $credentials = $this->get_credentials();

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

        $requestUri = '';

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

        if( empty($requestUri) ) {
            throw new Exception('Not a valid request url');
        }

        $headers = [
            'Accept: application/json',
            'Content-Type: application/json',
            'Authorization: Bearer ' . $credentials['api_key'],
        ];
        
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        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);

        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 json_decode($result->response, true);      
    }
}
