<?php
ini_set("log_errors", 1);
ini_set("error_log", "./error_log");
// API key that comes from bank in each psh message to verify sender d7846c24-73d6-452e-ad05-804a4ef3a501;

// change $hub_verify_token and $access_token
// endpoint https://clubsmart.dk/api/fb/index.php
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="") {


        /*$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 createUserInMobile($pairs) {
	    include_once '../app/mm_createuser.class.php';

	    $custom_name = $pairs['full_name'];
	    //$custom_email = $pairs['email'];
	    $custom_mobile = $pairs['phone_number'];
        $custom_title = 'Lead User subscribed';
        // &sendername=SENDERNAME&text=Hello world

        $apiKey = 'ecf213c6-a80e-416c-ac9a-97575b62f24a'; // Found at the top of the documentation page
        $groupId = '4b0f27ef-4f4f-4cd8-9580-cb8b178d6e0f';

        $MM_Connector = new MM_ConnectorCreate(
            $apiKey,
            'https://mm.inmobile.dk', // Server root address
            'https://clubsmart.dk/api/callback/inmobile/' // Optional for status callbacks
        );

        // create user section
        $body = "apiKey=".$apiKey."&groupId=".$groupId."&msisdn=45".$custom_mobile."&name=".$custom_name;
        $success = $MM_Connector->createUser($body);
        // eo create user section

	}

	private function sendSMStoUser($MM_Connector, $phone) {
        include_once __DIR__ . '/mm_apiclient.class.php';

        // Instantiate an API client object
        $MM_Connector = new MM_Connector(
            $apiKey,
            'https://mm.inmobile.dk', // Server root address
            'https://smartlaanet.dk/api/callback/inmobile/' // Optional for status callbacks
        );

        // prepare data section
        $apiKey = 'ecf213c6-a80e-416c-ac9a-97575b62f24a';
        $groupId = 'b619bf19-cdd1-4d1a-944c-2378a28be047';
        $body = "apiKey=".$apiKey."&groupId=".$groupId;

        // get list of users subscribed inmobile
        $subscribedListArray = $MM_Connector->getUserList($body);

        $todayDateTime = new DateTime();
        $subscribedListFiltered = array();
        foreach ($subscribedListArray['Data']['Recipient'] as $userItem) {

            // unsubscribe old users
            $datetimeSubscribed = new DateTime($userItem['CreatedDate']);
            $interval = $datetimeSubscribed->diff($todayDateTime);

            if ($interval->d > 30) {
                $body = "apiKey=".$apiKey."&groupId=".$groupId."&msisdn=".$userItem['Msisdn'];
                $success = $MM_Connector->deleteUser($body);
                continue;
            }

            $subscribedListFiltered[] = $userItem;

        }

        $subscribedListString = json_encode($subscribedListFiltered);

        // Found at the top of the documentation page
        if (strlen($phone) === 8) {
            $phone = '45'.$phone;
        }

        /*
        Prepare some messages to be sent. You can repeat this step multiple times
        to send multiple messages in a single http call
        */
        $msg = new MM_Message(
        'Tak for din ansøgning. Ekspressbank har modtaget den. Du mangler at underskrive med NemId for at den kan endelig godkendes her:',
        array($phone), // Msisdn (phonenumber with countrycode) for the receiver
        'Smartlånet'); // The sendername. This could be a phonenumber or your company name

        $MM_Connector->addMessage($msg);

        /* Send the payload */
        $success = $MM_Connector->send();
        if($success)
        {
            /* Read the message ids */
            $messageIds = $MM_Connector->getMessageIds();

            print_r($messageIds);
            echo 'Success!<br>';
        }
        else
        {
            /*
            This function returns the remote error code
            */
            print_r($MM_Connector->getError());
            echo 'Error!';
        }
    }

	private function sendCURLGET($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close ($ch);
        return $response;
	}

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

?>