<?php

/**
 *
 * @copyright  2017 izend.org
 * @version    2
 * @link       http://www.izend.org
 */

require_once 'readarg.php';
require_once 'strtofname.php';
require_once 'filtersms.php';
require_once 'models/sms.inc';

function smseditor($lang, $clang, $node_id) {
	$action='init';
	if (isset($_POST['sms_configure'])) {
		$action='configure';
	}

	$sms_modified=$sms_title=$sms_name=$sms_cloud=$sms_subject=$sms_text=false;

	switch($action) {
		case 'init':
			$r = sms_get_campaign($clang, $node_id);
			if ($r) {
				extract($r);	/* sms_modified sms_title sms_name sms_cloud sms_subject sms_text */
			}
			break;

		case 'configure':
			if (isset($_POST['sms_modified'])) {
				$sms_modified=filter_var($_POST['sms_modified'], FILTER_VALIDATE_INT, array('options' => array('min_range' => 0)));
			}
			if (isset($_POST['sms_title'])) {
				$sms_title=readarg($_POST['sms_title']);
				$sms_name = strtofname($sms_title);
			}
			if (isset($_POST['sms_cloud'])) {
				$sms_cloud=readarg($_POST['sms_cloud'], true, false);	// trim but DON'T strip!
				preg_match_all('/(\S+)/', $sms_cloud, $r);
				$sms_cloud=implode(' ', array_unique($r[0]));
			}
			if (isset($_POST['sms_subject'])) {
				$sms_subject=readarg($_POST['sms_subject']);
			}
			if (isset($_POST['sms_text'])) {
				$sms_text=trimsms(readarg($_POST['sms_text'], false, false));	// don't trim and DON'T strip!
			}
			break;
		default:
			break;
	}

	$missing_title=false;
	$bad_title=false;

	$missing_subject=false;

	$missing_text=false;

	switch($action) {
		case 'configure':
			if (!$sms_title or !$sms_name) {
				$missing_title = true;
			}
			else if (!preg_match('#^\w+(-\w+)*$#', $sms_name)) {
				$bad_title = true;
			}

			if (!$sms_subject) {
				$missing_subject = true;
			}

			if (!$sms_text) {
				$missing_text = true;
			}

			break;

		default:
			if (!$sms_text) {
				$missing_text = true;
			}

			break;
	}

	switch($action) {
		case 'configure':
			if ($missing_title or $bad_title or $missing_text) {
				break;
			}

			$r = sms_set_campaign($clang, $node_id, $sms_title, $sms_name, $sms_cloud, $sms_subject, $sms_text);

			if (!$r) {
				$internal_error=true;
				break;
			}

			$sms_modified=time();

			break;

		default:
			break;
	}

	list(, $sms_coding, $sms_msglen, $sms_count, $sms_len)=filtersms($sms_text);

	$inlanguages=view('inlanguages', false, compact('clang'));

	$errors = compact('internal_error', 'missing_title', 'bad_title', 'missing_subject', 'missing_text');

	$output = view('smseditor', $lang, compact('clang', 'inlanguages', 'sms_modified', 'sms_title', 'sms_cloud', 'sms_subject', 'sms_text', 'sms_msg', 'sms_coding', 'sms_msglen', 'sms_count', 'sms_len', 'errors'));

	return $output;
}

