<?php
//ini_set('display_errors', E_ALL);
//error_reporting(E_ALL);
define('SABLE_SITE_DEBUGGING', true);

include(__DIR__.'/../../includes/sysinit.php');
require_once(SABLE_CLASS_PATH.'panacea_api.php');
require_once(SABLE_CLASS_PATH.'sable_push.php');

$api = new PanaceaApi();
$api->setUsername(PANACEA_USERNAME);
$api->setPassword(PANACEA_PASSWORD);
$lastID = $sableDB->getValue('select MAX(sms_reply_id) from sms_message__reply');
$messages = $api->messages_get(PANACEA_USERNAME, PANACEA_PASSWORD, $lastID ?? 0);

unset($api);

$c = 0;
$d = '';
$qry = '';
$res = 0;
if (is_array($messages['details']) && !empty($messages['details']))
{
	$c = 0;
	$d = '';
	$sql = 'insert ignore into sms_message__reply (sms_reply_id, sms_id, sms_message, sms_timestamp) 
			values ';
	foreach($messages['details'] as $msg)
	{
		$qry = 'select sms_id from sms_message where sms_key = "'.$msg['reply_msg_uuid'].'"';
		$smsId = $sableDB->getValue($qry);
		if ($smsId)
		{
			$d = $c ? ',' : '';
			$sql .= $d.'('.$msg['id'].', '.$smsId.', "'.addslashes($msg['data']).'", "'.$msg['created'].'")';
			$c++;
		}
	}
	$res = $sableDB->updateQuery($sql);
}

if ($res)
{
	$sablePush = new SablePush;

	$word = ($res > 1) ? 'replies' : 'reply';
	$sablePush->msg  = 'You have '.$res.' '.$word.' to SMS messages.';
	$sablePush->title = "SMS Messages Received";
	$sablePush->repeatCount = 2; //repeat twice?
	$sablePush->repeatInterval = 1; //repeat every 5 minutes?
	$sablePush->userCode = 2; //Sylvester
	$sablePush->url = '/sms_message/';
	
	$sablePush->saveNotification($msg, $time, $repeatCount, $repeatInterval, $userCode, $url);
}