<?php
// API key that comes from bank in each psh message to verify sender d7846c24-73d6-452e-ad05-804a4ef3a501;
class DumpHTTPRequestToFile {
	public function execute($targetFile) {

	    $date = new DateTime();
		$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
		);

        $this->parseNotification($notificationMessage);

	}

	private function parseNotification($notificationMessage) {
	    $notificationObject = json_decode($notificationMessage, true);

	    $dataToSave = "applicationStatus: ". $notificationObject["applicationStatus"] . " applicationID: ". $notificationObject["applicationID"] . " reqid: ". $notificationObject["partnerMainKey"] . " approvedAmount: " . $notificationObject["offer"]["approvedAmount"];

	    $date = new DateTime();

	    file_put_contents(
            './status.txt',
            $date->format('Y-m-d H:i:s') . "|| " . $dataToSave . "\n\n",
            FILE_APPEND
        );


        $this->handleRequest($notificationObject["applicationStatus"], $notificationObject["applicationGuid"]);

        if ($notificationObject["applicationStatus"] === "Disbursed") {
            $trackingSource = 'https://secure.smartresponse-media.com/p.ashx?o=121777&e=560&f=pb&r=' . $notificationObject["partnerMainKey"] . '&p=' . $notificationObject["offer"]["approvedAmount"];

            $this->firePixel($trackingSource);
        }

	}


	/**
     * Handle status with DB.
     *
     *
     *
     *
     */
     private function handleRequest($status, $guid) {
        //DB Test server section
        $dbHost = 'localhost';
        $dbUsername = 'h4053_smartUser1';
        $dbPassword = 'Denmark92';
        $dbName = 'h4053_smartresponsesites';

        //Create connection and select DB
        $conn = mysqli_connect($dbHost, $dbUsername, $dbPassword, $dbName);

        if (mysqli_connect_errno()) {
            die("Unable to connect database: " . mysqli_connect_errno());
        }

        if (!mysqli_set_charset($conn, "utf8")) {
            printf("Encoding error utf8: %s\n", mysqli_error($conn));
            exit();
        }

        // values preparation
        $applicationDate = date("Y-m-d H:i:s");
        $partnerID = 'DKEBA';
        $guid = $guid;
        $status = $status;


        $result = mysqli_query($conn, "SELECT `userGuid` FROM `reminders` WHERE `userGuid` = '$guid'") or die();

        if (mysqli_num_rows($result) == 0) {
            $sql = "INSERT INTO `reminders` (`statusDate`, `partnerID`, `userGuid`, `statusValue`) VALUES ('" . $applicationDate . "','" . $partnerID . "','" . $guid . "','" . $status . "')";
            mysqli_query($conn, $sql);
        } else {
            $sql = "UPDATE `reminders` SET `statusDate` = '$applicationDate', `statusValue` = '$status' WHERE `userGuid` = '$guid'";
            mysqli_query($conn, $sql);
        }

        mysqli_close($conn);

     }


    /**
     * Send a GET request to a URL.
     *
     * @param string $url
     * @return string
     * @throws Exception If cURL request fails.
     */
	private function firePixel($url) {
	    $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);

        // If no errors, curl_errno will return 0
        if(curl_errno($ch)){
            $date = new DateTime();

            file_put_contents(
                './status.txt',
                $date->format('Y-m-d H:i:s') . " || URL: " . $url . " || FirePixelErrorNum: " . curl_errno($ch) . "\n\n",
                FILE_APPEND
            );
        }
        // Close request to clear up some resources
        curl_close($ch);
        return $result;
	}

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

?>