<?php

require_once AF2_INTEGRATION_HANDLER_CLASS;
class PipeDrive_Integration extends Af2Integration {

    public function get_credential_fields() {
        return array( 
            array( 'key' => 'api_url', 'option_value' => 'af2_pipedrive_api_url', 'icon' => 'fas fa-link', 'label' => 'API URL:', 'type' => 'text' ),
            array( 'key' => 'api_key', 'option_value' => 'af2_pipedrive_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_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' => 'name', 'type' => 'contactform'),
            array( 'label' => 'telefon', 'type' => 'contactform'),
            array( 'label' => 'mail', 'type' => 'contactform'),
        ); 
    }

    public function get_api_draw_fields() { 
        return array(
            array(
                'label' => __('Contact information:', 'af2_multilanguage'),
                'fields' => array(
                    array( 'label' => __('Name', 'af2_multilanguage'), 'required' => true, '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' ),
                ),
            ),
        );
    }

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

        $dat = array(
            'name' => $this->api_values['name'],
            'phone' => $this->api_values['telefon'],
            'email' => $this->api_values['mail'],
        );
        $resp = $this->add_contact($dat);
        $resp = json_decode($resp->response);
        $contact_id = $resp->data->id;

        $notedat = array(
            'content' => $this->api_values['answer_string'],
            'person_id' => intval($contact_id),
        );
        $resp = $this->add_note($notedat);
    }

    
    private function add_note($data)
    {
        try {
            $response = $this->request('notes', 'POST', $data);
            return $response;
        } catch (\Throwable $th) {
            return $th;
        }
    }
    private function add_deal($data)
    {
        try {
            $response = $this->request('deals', 'POST', $data);
            return $response;
        } catch (\Throwable $th) {
            return $th;
        }
    }
    /**
     * Send curl request to add Person or contact in pipedrive
     * @param Array $data array( "name" => "James Bond", "email" => array("james@example.com"), "phone" => array("123-456-7890") );
     * @return Object | with response and http code, Exception on any error thrown
     * */
    private function add_contact($data)
    {
        try {
            $response = $this->request('persons', 'POST', $data);
            return $response;
        } catch (\Throwable $th) {
            return $th;
        }
    }

    private function get_request_url($path, $queryArrg = [])
    {
        $credentials = $this->get_credentials();

        $urlString = $credentials['api_url'].'/api/v1/'.$path;
        
        $queryParam = array('api_token' => $credentials['api_key']);
        $paramString = http_build_query( array_merge($queryParam, $queryArrg) );
        return $urlString.'?'.$paramString;
    }

    /**
     * Send curl request to the given url
     * @param String $uri string optional - use if you want to break the url in to base url and action path 
     * @param String $method string default GET 
     * @param Array $data array|string (json string)
     * @param Array Additional query parameter
     * @return object | Error Exception on success full hit response object with response, code and meta
     * */
    private function request($uri='/', $method = 'GET', $data = '', $queryArrg=[]) {
        $header = array(
            'Content-Type: application/json',
            'Accept: application/json',
            'cache-control: no-cache'
        );

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

        $requestUri = $this->get_request_url($uri, $queryArrg);
        
        if( empty($requestUri) ) throw new Exception('Not a valid request url');
        // echo $requestUri; print_r($data);die;
        $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;      
    }
}