<?php

/**
 *
 * @copyright  2016-2017 izend.org
 * @version    3
 * @link       http://www.izend.org
 */

require_once 'userhasrole.php';
require_once 'userprofile.php';
require_once 'models/thread.inc';

function campaigneditpage($lang, $clang, $thread, $node) {
	global $with_toolbar;

	$user_id=user_profile('id');

	if (!$user_id) {
		return run('error/unauthorized', $lang);
	}

	$thread_id = thread_id($thread);
	if (!$thread_id) {
		return run('error/notfound', $lang);
	}

	$node_id = thread_node_id($thread_id, $node, $clang);
	if (!$node_id) {
		return run('error/notfound', $lang);
	}

	$r = thread_get($clang, $thread_id);
	if (!$r) {
		return run('error/notfound', $lang);
	}
	extract($r); /* thread_user_id thread_type thread_name thread_title thread_abstract thread_cloud */

	if ($thread_type != 'campaign') {
		return run('error/notfound', $lang);
	}

	if ($thread_user_id != $user_id and !user_has_role('administrator')) {
		return run('error/notfound', $lang);
	}

	$node_editor = build('smseditor', $lang, $clang, $node_id);

	$node_name=$node_title=false;
	$r = thread_get_node($clang, $thread_id, $node_id);
	if ($r) {
		extract($r); /* node_name node_title */
	}

	head('title', $node_title ? $node_title : $node_id);
	head('description', false);
	head('keywords', false);
	head('robots', 'noindex, nofollow');

	$banner=$toolbar=false;

	$headline_text=translate('campaignsummary:title', $lang);
	$headline_url=url('campaignedit', $lang) . '/' . $thread_id . '?' . 'clang=' . $clang;
	$headline = compact('headline_text', 'headline_url');
	$viewsms=$node_name ? url('campaign', $clang) . '/'. $thread_id . '/' . $node_id : false;

	$banner = build('banner', $lang, $with_toolbar ? compact('headline') : compact('headline', 'viewsms'));
	$toolbar = $with_toolbar ? build('toolbar', $lang, compact('viewsms')) : false;

	$prev_node_label=$prev_node_url=false;
	$r=thread_node_prev($clang, $thread_id, $node_id);
	if ($r) {
		extract($r);
		$prev_node_label = $prev_node_title ? $prev_node_title : $prev_node_id;
		$prev_node_url=url('campaignedit', $lang) . '/' . $thread_id . '/'. $prev_node_id . '?' . 'clang=' . $clang;
	}

	$next_node_label=$next_node_url=false;
	$r=thread_node_next($clang, $thread_id, $node_id);
	if ($r) {
		extract($r);
		$next_node_label = $next_node_title ? $next_node_title : $next_node_id;
		$next_node_url=url('campaignedit', $lang) . '/' . $thread_id . '/'. $next_node_id . '?' . 'clang=' . $clang;
	}

	$title = view('headline', false, $headline);
	$sidebar = view('sidebar', false, compact('title'));

	$content = view('campaigneditpage', $lang, compact('node_editor', 'node_id', 'node_title', 'prev_node_url', 'prev_node_label', 'next_node_url', 'next_node_label'));

	$output = layout('editing', compact('toolbar', 'banner', 'content', 'sidebar'));

	return $output;
}

