<?php

require_once ('vn/web/json-request.php');

use Vn\Lib;

class Sms extends Vn\Web\JsonRequest
{
	function run ()
	{
		$db = $this->login ();
	
		$params = [
			 'text'
			,'to'
		];

		if (!$this->checkParams ($_REQUEST, $params))
			throw new Lib\UserException  (s('Missing parameters'), 'missingParams');

		$smsConfig = $db->getRow ('SELECT uri, user, password, title FROM sms_config');

		$sClient = new SoapClient ($smsConfig['uri']);
		$xmlString = $sClient->sendSMS (
			 $smsConfig['user']
			,$smsConfig['password']
			,$smsConfig['title']
			,$_GET['to']
			,$_GET['text']
		);
		$xmlResponse = new SimpleXMLElement ($xmlString);

		$customer = empty ($_GET['customer']) ? NULL : $_GET['customer'];

		try {
			$sms = $xmlResponse->sms;
			$db->query (
				'INSERT INTO vn2008.sms (Id_trabajador, `text`, `to`, `from`, sent, response, Id_Cliente)
					VALUES (account.user_get_id(), #, #, #, #, #, #)',
				[
					 $_GET['text']
					,$_GET['to']
					,$_GET['to']
					,$sms->codigo
					,$sms->descripcion
					,$customer
				]
			);
		}
		catch (Exception $e)
		{
			trigger_error ($e->getMessage (), E_USER_WARNING);
		}

		return TRUE;
	}
}

?>