<?php
ini_set("log_errors", 1);
ini_set("error_log", "../logs/error.log");
// 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_default_timezone_set( 'UTC' );
	    $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";

        // save is temporary into two different sources to see which is better
		$notificationMessage = file_get_contents('php://input');
		$input = json_decode(file_get_contents('php://input'), true);
		error_log(print_r($input, true));

		// save raw request details to dumprequest.txt
		file_put_contents(
			$targetFile,
			$date->format('Y-m-d H:i:s') . "||" . $data . $notificationMessage . "\n\n",
			FILE_APPEND
		);

        // handle request details
        $this->handleNotification($notificationMessage);

	}

	private function handleNotification($notificationMessage="") {
	    date_default_timezone_set( 'UTC' );
	    $dataToSave = '';
	    $date = new DateTime();

        // check for the first verification request from facebook
        if ($_SERVER['REQUEST_METHOD'] == 'GET') {

            foreach ($_REQUEST as $name => $value) {
                $dataToSave .= $name . ': ' . $value . "\n";
            }

            $hub_mode = $_REQUEST['hub_mode'];
            $hub_challenge = $_REQUEST['hub_challenge'];
            $hub_verify_token = $_REQUEST['hub_verify_token'];

            if ($hub_verify_token === 'a1b2c3d4e5=11') {
                echo $hub_challenge;
            }


            /*$phone = urlencode($_REQUEST["phone"]);
            $hashedEmailData = hash('sha256', $_REQUEST["email"]);
            $hashedMobileNumber = hash('sha256', $phone);*/

        }

        /*$dataToSave .= $_SERVER['QUERY_STRING'] . "\n";
        $dataToSave .= $trackingFacebook . "\n";

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

	}

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

?>