<?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;

// documentation https://docs.inmobile.dk/#get-single-recipients-in-a-group
// 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="") {
        // all the logic to work with users
        $apiKey = 'ecf213c6-a80e-416c-ac9a-97575b62f24a'; // Found at the top of the documentation page
        $groupId = 'd93a24cc-3b62-4631-b98f-a8894d1dbb05'; // real Norwegian group ID
        $testGroupId = '4b0f27ef-4f4f-4cd8-9580-cb8b178d6e0f'; // test group ID
        $num_of_days = 40;



        // get list of users that are filtered by number of days
        $subscribedListRemoved = $this->getOldFilteredUsers($apiKey, $groupId, $num_of_days);

        echo "<br><br>list of all users to be deleted and subscribed again in the group $groupId: <br><pre>";
        var_dump($subscribedListRemoved);
        echo "</pre>";

        // create deleted users again
        $this->createUserInMobile($apiKey, $testGroupId, $subscribedListRemoved);


        /*$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
        );*/

	}

	// get users and delete old ones
	private function getOldFilteredUsers($apiKey, $groupId, $days) {
        include_once '../app/mm_apiclient.class.php';

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

        // get list of users subscribed inmobile
        $subscribedUsers = $this->getAllUsers($apiKey, $groupId);

        $todayDateTime = new DateTime("now");

        $subscribedListRemoved = array();
        foreach ($subscribedUsers['Data']['Recipient'] as $key=>$userItem) {
            // unsubscribe old users
            $datetimeSubscribed = new DateTime(substr($userItem['CreatedDate'],0,10));
            $interval = $datetimeSubscribed->diff($todayDateTime);
            echo "days interval " . $interval_days = $interval->format('%a')."<br><pre>";

            if ($interval_days > $days) {
                echo "<br>delete old user branch:<br>";
                /*$body = "apiKey=".$apiKey."&groupId=".$groupId."&msisdn=".$userItem['Msisdn'];
                $success = $MM_Connector->deleteUser($body);*/

                // add externalCreated date as custom1 param for users that don't have it

                if ( isset($userItem['Custom1']) && !empty($userItem['Custom1']) ) {
                    //$userItem['custom1'] = $userItem['Custom1'];
                } else {
                    $userItem['Custom1'] = $userItem['CreatedDate'];
                }
                //unset($userItem['Custom1']);
                $subscribedListRemoved[] = $userItem;

            } else {
                echo "<br>enter new user branch :<br>";

                // update with custom1 only those empty users that are not old
                if (!$userItem['Custom1']) {
                    echo "<br>enter into absent Custom1:<br>";
                    $userItem['Custom1'] = $userItem['CreatedDate'];
                    /*$updateDateBody = "apiKey=".$apiKey."&groupId=".$groupId."&msisdn=".$userItem['Msisdn']."&custom1=".$userItem['Custom1'];
                    $this->updateUserInMobile($apiKey, $groupId, $updateDateBody)*/;
                }

            }

        }

        // here we keep list of users that were old and deleted
        return $subscribedListRemoved;

    }

    // get users and delete old ones
    private function getAllUsers($apiKey, $groupId) {
        include_once '../app/mm_apiclient.class.php';

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

        // prepare data section
        $body = "apiKey=".$apiKey."&groupId=".$groupId;

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

    }

    // creates or updates user if exists already
    private function createUserInMobile($apiKey, $groupId, $subscribedListRemoved) {
        include_once '../app/mm_createuser.class.php';

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

        foreach ($subscribedListRemoved as $userItem) {
            unset($userItem['GroupId']);
            unset($useritem['CreatedDate']);
            $customquerystring = http_build_query($userItem);

            // create user section
            $body = "apiKey=".$apiKey."&groupId=".$groupId."&".$customquerystring;
            $success = $MM_Connector->createUser($body);
            echo "<br>Result of user create";
            echo $success;
            // eo create user section
        }

    }

    // creates or updates user if exists already
    private function updateUserInMobile($apiKey, $groupId, $updateDateBody) {
        include_once '../app/mm_createuser.class.php';

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

        $updateDateBodySuccess = $MM_Connector->createUser($updateDateBody);
        echo "<br>Result of user update";
        echo $updateDateBodySuccess;
        // eo create user section

    }



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

?>