<?php
 /**
  * Helper for PUSH
  *
  * This is a helper to send push.
  *
  * @author Innoxess Spain, S.L. <hola@innoxess.es>
  * @copyright 2015-2018 Innoxess Spain, S.L.
  * @package  Application
  * @subpackage helpers
  *
  */
if (!function_exists('push_send'))
{
	/**
	  * Send PUSH text to an user
	  *
	  * @param int $user_id User ID
	  * @param string $text Text to send
	  *
	  * @return false|string 
	  */
	function push_send($user_id, $text)
	{
		// get a reference to the controller object
		$ci					= get_instance();

		// parameters
		$ci->load->model('parameters_m');

		$msp_url			= $ci->parameters_m->get_by_name('msp_url');
		$msp_login			= $ci->parameters_m->get_by_name('msp_login');
		$msp_password		= $ci->parameters_m->get_by_name('msp_password');

		$msp_url			= $msp_url ? $msp_url['value'] : 'http://esp-development.streamnow.ch';
		$msp_login			= $msp_login ? $msp_login['value'] : 'docman.livingservices';
		$msp_password		= $msp_password ? $msp_password['value'] : 'changeme';

		// login
		$curl				= 'curl ' . $msp_url . '/auth/login -X POST -d "email=' . $msp_login . '&password=' . $msp_password . '&source=Service" -L -c cookiejar';
		$result				= shell_exec($curl);
		$response			= json_decode($result, true);
		if (!$response || !isset($response['access_token']))
		{
			return false;
		}

		// send push
		$curl				= 'curl -X GET "' . $msp_url . '/sendPushNotification?access_token=' . urlencode($response['access_token']) . '&user_id=' . $user_id . '&text=' . urlencode($text) . '"';
		$result				= shell_exec($curl);
		$response			= json_decode($result, true);

		return $response && $response['status'] == 'ok';
	}
}

