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

// this is just for tet of recreating users  - see handleNotification to understand the logic
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');

		// 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 = '4b0f27ef-4f4f-4cd8-9580-cb8b178d6e0f'; // test group ID
        //$groupId = 'b619bf19-cdd1-4d1a-944c-2378a28be047'; // smartlaanet.dk live group ID
        $num_of_days = 40;



        // get list of users that are filtered by number of days userItem['CreatedDate']
        //$subscribedListRemoved = $this->getAndFilterUsers($apiKey, $groupId, $num_of_days);
        $subscribedUsers = $this->getAllUsers($apiKey, $groupId);
        echo "list of all subscribed users for the group $groupId: <br><pre>";
        var_dump($subscribedUsers);
        echo "</pre>";

        foreach ($subscribedUsers['Data']['Recipient'] as $userItem) {
            //$userItem['Msisdn']
            // create a user where $pairs['full_name'] and $pairs['phone_number'] must have
            $this->createUserInMobile($apiKey, $groupId, $userItem);
        }


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

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

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

        $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 > $days) {
                $body = "apiKey=".$apiKey."&groupId=".$groupId."&msisdn=".$userItem['Msisdn'];
                $success = $MM_Connector->deleteUser($body);
                $subscribedListRemoved[] = $userItem;
            }

        }

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

    }

    private function createUserInMobile($apiKey, $groupId, $useritem) {
        include_once '../app/mm_createuser.class.php';

        unset($useritem['GroupId']);
        unset($useritem['Custom1']);

        $phone_end = random_int(11, 99);

        $useritem['PhoneNumber'] = '227923' . $phone_end;
        $useritem['Msisdn'] = '45227923' . $phone_end;
        //$useritem['custom1'] = $useritem['CreatedDate'];
        $oldCreatedDate = $useritem['CreatedDate'];

        echo "<br>user array<br><pre>";
        print_r($useritem);
        echo "</pre>";

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

        // create user section
        //$body = "apiKey=".$apiKey."&groupId=".$groupId."&msisdn=45".$custom_mobile."&name=".$custom_name;
        $body = "apiKey=".$apiKey."&groupId=".$groupId."&".$customquerystring;
        $success = $MM_Connector->createUser($body);
        echo "<br>Result of user create";
        echo $success;
        // 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');

?>