<?php

use Vn\Lib;

class Sms extends Vn\Web\JsonRequest
{
	const PARAMS = [
		 'destination'
		,'message'
	];

	const OK_STATES = [
		0,   // Ok
		200  // Processing
	];

	function run ($db)
	{
		$smsConfig = $db->getObject ('SELECT uri, user, password, title FROM vn.smsConfig');

		$sClient = new SoapClient ($smsConfig->uri);
		$xmlString = $sClient->sendSMS (
			 $smsConfig->user
			,$smsConfig->password
			,$smsConfig->title
			,$_REQUEST['destination']
			,$_REQUEST['message']
		);
		$xmlResponse = new SimpleXMLElement ($xmlString);
		$res = $xmlResponse->sms;

		$db->query (
			'INSERT INTO vn.sms SET
				`senderFk` = account.myUserGetId(),
				`destinationFk` = #,
				`destination` = #,
				`message` = #,
				`statusCode` = #,
				`status` = #',
			[
				 empty ($_REQUEST['destinationId']) ? NULL : $_REQUEST['destinationId']
				,$_REQUEST['destination']
				,$_REQUEST['message']
				,$res->codigo
				,$res->descripcion
			]
		);

		if (!in_array ((int) $res->codigo, self::OK_STATES))
			throw new Lib\UserException ($res->descripcion);

		return TRUE;
	}
}
