<?php

/**
 *
 * @copyright  2016 izend.org
 * @version    1
 * @link       http://www.izend.org
 */

define('ROOT_DIR', dirname(__FILE__));

set_include_path(get_include_path() . PATH_SEPARATOR . ROOT_DIR . DIRECTORY_SEPARATOR . 'library');
set_include_path(get_include_path() . PATH_SEPARATOR . ROOT_DIR . DIRECTORY_SEPARATOR . 'includes');

define('USAGE', 'php -f %s name | info | send telnum msgtext | pending | cancel smsid');

function abort($msg, $code=1) {
	echo $msg, PHP_EOL;
	exit($code);
}

function usage() {
	global $argv;

	abort(sprintf(USAGE, basename($argv[0])), 1);
}

require_once 'ovh.inc';

if (! ($ovh_application_key and $ovh_application_secret and $ovh_consummer_key)) {
	abort('ovh.inc?');
}

require_once 'vendor/autoload.php';
use \Ovh\Api;

$ovh = new Api($ovh_application_key, $ovh_application_secret, $ovh_endpoint, $ovh_consummer_key);

if (!($argc >= 2)) {
	usage();
}

$telnum=$msgtext=$smsid=false;

$action=$argv[1];

switch ($action) {
	case 'name';
		break;
	case 'info';
		break;
	case 'send';
		if (!($argc == 4)) {
			usage();
		}
		$telnum=$argv[2];
		$msgtext=$argv[3];
		break;
	case 'pending';
		break;
	case 'cancel';
		if (!($argc == 3)) {
			usage();
		}
		$smsid=$argv[2];
		break;
	default:
		usage();
}

switch ($action) {
	case 'name';
		try {
			$r = $ovh->get('/sms');

			echo $r[0], PHP_EOL;
		}
		catch (Exception $e) {
			die($e->getMessage());
		}
		break;

	case 'info';
		try {
			$r = $ovh->get('/sms/' . $ovh_service_name);

			print_r($r);
		}
		catch (Exception $e) {
			die($e->getMessage());
		}
		break;

	case 'send';
		$args = array(
			'charset'			=> 'UTF-8',
			'class'				=> 'phoneDisplay',
			'coding'			=> '7bit',
			'noStopClause'		=> false,
			'priority'			=> 'high',
//			'sender'			=> 'iZend',
			'senderForResponse'	=> true,
			'validityPeriod'	=> '1440',
			'differedPeriod'	=> '2880',
			'message'			=> $msgtext,
			'receivers'			=> array($telnum),
		);

		try {
			$r = $ovh->post('/sms/' . $ovh_service_name . '/jobs', $args);

			print_r($r);
		}
		catch (Exception $e) {
			die($e->getMessage());
		}
		break;

	case 'pending';
		try {
			$r = $ovh->get('/sms/' . $ovh_service_name . '/jobs');

			print_r($r);
		}
		catch (Exception $e) {
			die($e->getMessage());
		}
		break;

	case 'cancel';
		try {
			$r = $ovh->delete('/sms/' . $ovh_service_name . '/jobs/' . $smsid);
		}
		catch (Exception $e) {
			die($e->getMessage());
		}
		break;

	default:
		break;
}
