<?php

/**
 * This script allows to get additional data of contact from SALESmanago system
 * before sending email via campaigns module
 *
 * @author Wojciech Niestolik <wniestolik@betasoft.pl>
 * @version 1.0
 */



/**
 * SALESmanago API client
 */
class SalesManagoApiClient {

    /** Api server end point */
    private $endpoint = 'http://sales-manago-endpoint';

    /** Api client identifier */
    private $apiClient = 'api-client';

    /** Api secret value */
    private $apiSecret = 'api-secret';

    /** API key */
    private $apiKey = 'some-api-key';

    /** Proxy server (host:port) */
    private $proxy;

    /** Timeout for requests */
    private $timeout = 5;

    /** API SHA (automaticaly generated) */
    private $apiSha;



    /**
     * Call API method
     */
    public function call($method, $params) {
        $data = array(
            'apiKey' => $this->apiKey,
            'clientId' => $this->apiClient,
            'sha' => sha1($this->apiKey.$this->apiClient.$this->apiSecret),
            'requestTime' => time(),
        );
        $data = array_merge($data, $params);

        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $this->endpoint.$method);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json, application/json', 'Content-Type: application/json;charset=UTF-8'));
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($curl, CURLOPT_TIMEOUT, $this->timeout);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);

        if(!empty($this->proxy)) {
            curl_setopt($curl, CURLOPT_PROXY, $this->proxy);
        }

        $hres = curl_exec($curl);

        $res = json_decode($hres);

        if(isset($res->success)) {
            if(!$res->success) {
                $msg = isset($res->message) && !empty($res->message) ? implode(';', $res->message) : 'API method execution failure';
                throw new Exception($msg);
            }
        } else {
            error_log($res);
            throw new Exception('SALESmanago API service is not available');
        }

        return $res;
    }
}



/**
 * SALESmanago API service
 */
class SalesManagoApiService {

    /** Last message */
    private $lastMessage;



    /**
     * Set last message
     */
    private function setLastMessage($msg = null) {
        $this->lastMessage = strlen($msg) ? $msg : null;
    }



    /**
     * Get last message
     */
    public function getLastMessage() {
        return $this->lastMessage;
    }



    /**
     * Get contact id by email
     */
    public function getContactIdByEmail($email) {
        $contactId = null;

        $this->setLastMessage();

        $apiClient = new SalesManagoApiClient();

        $params = array(
            'email' => $email,
            'owner' => 'aneta.kepka@isl.pl',
        );

        try {
            $res = $apiClient->call('contact/hasContact', $params);

            if(isset($res->contactId) && !empty($res->contactId)) {
                $contactId = $res->contactId;
            }
        } catch(Exception $e) {
            $this->setLastMessage($e->getMessage());
        }

        return $contactId;
    }

}



// Check if container object exists
if(!isset($args['container']) || !is_a($args['container'], 'FlexyTemplatePage')) {
    throw new Exception(__CLASS__.':'.__LINE__.': '.sprintf('Brak obiektu %s', 'container'));
}

// Check if email param exists
if(!isset($args['email']) || !strlen($args['email'])) {
    throw new Exception(__CLASS__.':'.__LINE__.': '.sprintf('Brak parametru %s', 'email'));
}

// Add object salesmanago to obj
$args['container']->salesmanago = new stdClass();

$api = new SalesManagoApiService();

// Get contactId from SALESmanago and pass it to external object
$contactId = $api->getContactIdByEmail($args['email']);
$args['container']->salesmanago->contactId = $contactId ? $contactId : null;

?>