<?php
/*ini_set("log_errors", 1);
ini_set("error_log", "../logs/error.log");*/

// URL for API https://

class DumpHTTPRequestToFile {
	public function execute($targetFile) {
	    $date = new DateTime();
	    $date->setTimezone(new DateTimeZone("UTC"));

		$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";
		$notificationMessage = file_get_contents('php://input');
		file_put_contents(
			$targetFile,
			$date->format('Y-m-d H:i:s') . "||" . $data . $notificationMessage . "\n\n",
			FILE_APPEND
		);

        // prepare parameters to send to cake
        $fields = array();
        $fields['api_key'] = '5WFzmGlsW9Jz1wJhUSI4Q';
        $fields['conversion_date'] = $date->format('Y-m-d');
        $fields['unpaid_disposition_id'] = '0';

        switch ($_POST['partner']) {
            case 'SEAXO':
                $fields['affiliate_id'] = '14611';
                $fields['campaign_id'] = '302648';
                $fields['sub_affiliate'] = 'directtraffic';
                $fields['creative_id'] = '235573';
                $fields['total_to_insert'] = 1;
                $fields['payout'] = (0.7 / 100) * $_POST['amount'];
                $fields['received'] = (1.0 / 100) * $_POST['amount'];
                $fields['transaction_ids'] = '';
                $fields['note'] = 'Advertiser did not place conversion pixel';

                // check affid 15391 and modify the call
                if (isset($_POST['afid']) && $_POST['afid'] == "15391") {
                    $fields['sub_affiliate'] = '50015391';
                }
                break;
        }

        $url_post = 'https://login.smartresponse-media.com/api/3/track.asmx/MassConversionInsert';

        $this->fireCakeConversion($url_post, $fields);

	}

    /**
     * Send a GET request to a URL.
     *
     * @param string $url
     * @return string
     * @throws Exception If cURL request fails.
     */
	private function fireCakeConversion($url_post, $fields) {
	    $ch = curl_init();
	    curl_setopt($ch, CURLOPT_URL, $url_post);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $result_post = curl_exec($ch);
        $res_curl_errno = curl_errno($ch); //Save error
        curl_close($ch);

        // If no errors, curl_errno will return 0
        $date = new DateTime();
        $date->setTimezone(new DateTimeZone("UTC"));

        if($res_curl_errno){
            file_put_contents(
                './send_report.txt',
                $date->format('Y-m-d H:i:s') . " || URL: " . $url_post . " || FirePixelErrorNum: " . $res_curl_errno . "\n\n",
                FILE_APPEND
            );
        } else {
            file_put_contents(
                './send_report.txt',
                $date->format('Y-m-d H:i:s') . " || URL: " . $url_post . " data: " . http_build_query($fields) . " || Result: " . $result_post . "\n\n",
                FILE_APPEND
            );
        }
        // Close request to clear up some resources
        return $result_post;
	}

	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');

?>