<?php
// https://gist.github.com/magnetikonline/650e30e485c0f91f2f40

class DumpHTTPRequestToFile {

	public function execute($targetFile) {

		$data = sprintf(
			"%s %s %s\n\nHTTP headers:\n",
			$_SERVER['REQUEST_METHOD'],
			$_SERVER['REQUEST_URI'],
			$_SERVER['SERVER_PROTOCOL']
		);

		foreach ($this->getHeaderList() as $name => $value) {
			$data .= $name . ': ' . $value . "\n";
		}

		$data .= "\nRequest body:\n";

		file_put_contents(
			$targetFile,
			$data . file_get_contents('php://input') . "\n",
			FILE_APPEND | LOCK_EX
		);

		// extract user action and user contactId and delete user if there is need
		if (isset($_GET['action']) && $_GET['action'] === 'unsubscribe') {
            if (isset($_GET['CONTACT_ID'])) {
                try {
                    $this->deleteUserFromNewAPI($_GET['CONTACT_ID']);
                } catch(Exception $e) {
                    error_log(date("Y-m-d H:i:s") ."\n". $e ."\n", 3, "error_log");
                }
            }
		}

	}

	private function deleteUserFromNewAPI($contactId) {
        $apiEndpoint = "https://api.getresponse.com/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 = $this->callDELETECURL($path, $headers);
        $this->saveToFile($contactId, $jsondata);
        /*echo "result of delete user:<br><pre>";
        print_r(json_decode($jsondata));*/
	}

	private 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;
	}

	private function saveToFile($contactId, $jsondata) {
        $date = new DateTime();
        $file = './delete_report_old.txt';
        $datas = "ContactId: " . $contactId . " Response: " . $jsondata;

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

	private function getHeaderList() {

		$headerList = [];
		foreach ($_SERVER as $name => $value) {
			if (preg_match('/^HTTP_/',$name)) {
				// convert HTTP_HEADER_NAME to Header-Name
				$name = strtr(substr($name,5),'_',' ');
				$name = ucwords(strtolower($name));
				$name = strtr($name,' ','-');

				// add to list
				$headerList[$name] = $value;
			}
		}

		return $headerList;
	}
}


(new DumpHTTPRequestToFile)->execute('./dumprequest.txt');
