<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('max_execution_time', 360);
error_reporting(E_ALL);
// documentation is here https://apidocs.getresponse.com/api/1.5.0/Callbacks/get_account_callbacks

$userToUpdateList = array ("xxxxxxx@gmail.com"
                          );

// getting custom fields information

// Only allow ajax requests
/*if( !isset($_SERVER["HTTP_REFERER"]) || !isset($_SERVER["HTTP_X_REQUESTED_WITH"]) || strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) != "xmlhttprequest" ) {

    exit("N - not allowed");

}*/

// test token = aV4d8
/*
4Z4uT y
T8BU8 n
4kj4U n
6jHeY n
6y3Cg n
6saig n
*/

function callDELETECURL($path, $headers)
{
    $url = $path;
    $json = '';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $resp = curl_exec($ch);
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $header = substr($resp, 0, $header_size);
    $body = substr($resp, $header_size);
    curl_close($ch);
    return "response of curl: " . $resp . "<br>Header info: " . $header . "<br>Body info: " . $body;
    //return $resp;
}

function callGETCURL($url, $headers) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $resp = curl_exec($ch);
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $header = substr($resp, 0, $header_size);
    $body = substr($resp, $header_size);
    curl_close($ch);
    //return "response of curl: " . $resp . "<br>Header info: " . $header . "<br>Body info: " . $body;
    return $resp;
}

function callPOSTCURL($dataArray, $headers, $url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($dataArray));
    $resp = curl_exec($ch);
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $header = substr($resp, 0, $header_size);
    $body = substr($resp, $header_size);
    curl_close($ch);
    return "response of curl: " . $resp . "<br>Header info: " . $header . "<br>Body info: " . $body;
}

function getResultFromNewAPI($token, $email, $headers) {

    $apiEndpoint = "https://api3.getresponse360.pl/v3";
    //$url = $apiEndpoint . "/campaigns/" . $token;
    //$url = $apiEndpoint . "/custom-fields";
    //$url = $apiEndpoint . "/contacts?query[campaignId]=".$token."&query[email]=zascia@ukr.net";
    $url = $apiEndpoint . "/campaigns/".$token."/contacts";
    $response = callGETCURL($url, $headers);
    return $response;
}

function getResultFromOldAPI($token, $email, $headers, $page=1) {

    $apiEndpoint = "https://api.getresponse.com/v3";
    //$url = $apiEndpoint . "/campaigns/" . $token;
    $url = $apiEndpoint . "/custom-fields";
    //$url = $apiEndpoint . "/custom-fields?fields=name,createdOn,custom_signup_date";

    // for the custom field update task
    //$url = $apiEndpoint . "/contacts?query[campaignId]=".$token."&query[email]=" . $email;


    ///$url = $apiEndpoint . "/contacts?query[campaignId]=".$token."&fields=name,createdOn,custom_signup_date&sort[createdOn]=desc";

    //$url = $apiEndpoint . "/campaigns/".$token."/contacts?sort[createdOn]=desc&perPage=1000&page=".$page;

    //$url = $apiEndpoint . "/campaigns/statistics/list-size?query[campaignId]=" . $token;

    //$url = $apiEndpoint . "/custom-fields/V?fields=PlDQB";
    //$url = $apiEndpoint . "/custom-fields/V?fields=signup_date";
    $response = callGETCURL($url, $headers);
    return $response;
}

function deleteUserFromNewAPI($contactId) {
    $apiEndpoint = "https://api3.getresponse360.pl/v3/contacts/";
    $path = $apiEndpoint . $contactId;
    $headers = array();
    $headers[] = "x-auth-token: api-key 98e9893f951367413bd5204890473ba0";
    $headers[] = "X-Domain: cepamail.com";
    $headers[] = "Content-Type: application/json";

    $jsondata = callDELETECURL($path, $headers);
    echo "result of delete user $contactId:<br><pre>";
    print_r(json_decode($jsondata));
}

function deleteUserInsideTheList($userToDeleteList) {
    foreach($userToDeleteList as $userItem) {
        $contactId = $userItem['contactId'];
        deleteUserFromNewAPI($contactId);
    }
}

function saveToFile($email, $jsondata) {
    $date = new DateTime();
    $file = 'data.txt';
    $datas = "Email: " . $email . " Response: " . $jsondata;

    file_put_contents($file, "\n".$date->format('Y-m-d H:i:s')." || ".$datas, FILE_APPEND | LOCK_EX);
}

function getContactsNewAPI() {
    $email = "zascia@ukr.net";
    $token = "yiCLG";
    $headers = array();
    $headers[] = "x-auth-token: api-key 98e9893f951367413bd5204890473ba0";
    $headers[] = "X-Domain: cepamail.com";
    $headers[] = "Content-Type: application/json";

    $jsondata = getResultFromNewAPI($token, $email, $headers);

    echo "<pre>";
    print_r(json_decode($jsondata));
}


//saveToFile($email, $jsondata);

// GETRESPONSE DELIVERY
function createUpdateOldAPICallback() {
    $dataArray = array (
    	"url" => "https://zascia.in.ua/api/getresponse/callback/",
    	"actions" => array (
    	    "subscribe" => true,
    		"unsubscribe" => true
    	)
    );

    $headers = array ("X-Auth-Token: api-key 98e9893f951367413bd5204890473ba0", "Content-Type: application/json");
    $url = 'https://api.getresponse.com/v3/accounts/callbacks';

    $responseAfterSetupCallback = callPOSTCURL($dataArray, $headers, $url);

    echo "<pre>";
    print_r($responseAfterSetupCallback);
}

function getAllPages($token, $email, $headers) {
    $page = 1;
    $allContacts = array();

    while ($contacts = getResultFromOldAPI($token, $email, $headers, $page++)) {
        if ($page > 4) return $allContacts;
        $tmpArray = json_decode($contacts);

        $allContacts = array_merge($allContacts, $tmpArray);
        //echo "page = " . $page . "and count = " .count($allContacts). "<br>";
    }
    return $allContacts;
}

function updateCustomField() {
}

//deleteUserInsideTheList($userToDeleteList);

$token = '6y3Cg'; // smartlaanet.dk step1
$headers = array ("X-Auth-Token: api-key 98e9893f951367413bd5204890473ba0", "Content-Type: application/json");


// update leads from contact list from klarfinans and update them with custom field value for signup

/*foreach ($userToUpdateList as $userItemEmail) {
    $userData = json_decode(getResultFromOldAPI($token, $userItemEmail, $headers, 1));
    $contactId = $userData[0]->contactId;
    $createdOn = $userData[0]->createdOn;
    $customSignup = substr($createdOn, 0, 10);

    echo "contactId = " . $contactId . " createdOn = " . $createdOn . " customSignup = " . $customSignup ."<br>";

    continue;


    $dataArray = array (
            'customFieldValues' =>
                array (
                     0 =>
                     array (
                       'customFieldId' => 'PlDQB',
                       'value' =>
                       array (
                         $customSignup
                       ),
                     ),
                ),
        );

        $url = 'https://api.getresponse.com/v3/contacts/' .$contactId. '/custom-fields';

        // call API for update custom field
        $result = callPOSTCURL($dataArray, $headers, $url);
        echo "<pre>Result of curl: <br>";
        print_r($result);


}*/

$result = getResultFromOldAPI($token, $email, $headers);
echo "<pre>";
    print_r(json_decode($result));
?>