{include file="rt/rtticketshared.html"}

<style>

	#ticket.lms-ui-box-container .lms-ui-box-row-label {
		min-width: 12em;
	}

	#ticket.lms-ui-box-container .lms-ui-box-row.categories .lms-ui-box-row-field {
		flex-wrap: wrap;
	}

	#requestor.lms-ui-box-row-field {
		flex-direction: column !important;
		align-items: flex-start !important;
	}

	#requestor .indicated-person .lms-ui-box-row-label {
		justify-content: flex-end;
		display: flex;
	}

	#requestor_mail_combobox,
	#requestor_phone_combobox {
		width: 20em;
	}

</style>

{box_container id="ticket"}
	{box_header multi_row=true}
		{box_header icon="helpdesk" label="Subject" icon_class="fa-fw"}
			<INPUT type="text" size="50" name="ticket[subject]" maxlength="{ConfigHelper::getConfig('rt.subject_max_length', 50)}"
				   value="{$ticket.subject|default:""|escape}" {tip text="Enter subject" trigger="subject"} {if $layout.module !="eventadd"} required{/if}>
		{/box_header}
		{box_header icon="service" label="Service type" icon_class="fa-fw"}
			<select name="ticket[service]" id="ticket-service"
				{tip class="lms-ui-advanced-select-test" text="Choose service type" trigger="service"}
				{if ConfigHelper::checkConfig('rt.ticket_service_required')} required{/if}>
				<option value="" selected hidden>{trans("select")}</option>
				{foreach $_SERVICETYPES as $key => $service}
					<option value="{$key}"{if $key == $ticket.service} selected{/if}>{$service}</option>
				{/foreach}
			</select>
		{/box_header}
		{box_header icon="type" label="Ticket type" icon_class="fa-fw"}
			<select name="ticket[type]" id="ticket-type"
				{tip class="lms-ui-advanced-select-test" text="Choose ticket type" trigger="type"}
				{if ConfigHelper::checkConfig('rt.ticket_type_required')} required{/if}>
				<option value="" selected hidden>{trans("select")}</option>
				{foreach Localisation::arraySort($_RT_TYPES, 'label') as $key => $type}
					<option value="{$key}"{if $key == $ticket.type} selected{/if}>{$type.label}</option>
				{/foreach}
			</select>
		{/box_header}
		{if ConfigHelper::checkPrivilege('helpdesk_ticket_custom_times')}
			{box_header icon="calendar" label="<!rtticket>Custom create time" icon_class="fa-fw"}
				<input type="text" name="ticket[customcreatetime]"
					value="{if $ticket.customcreatetime}{$ticket.customcreatetime|date_format:"Y/m/d H:i"}{/if}"
					{tip class="lms-ui-datetime" trigger="customcreatetime"}>
			{/box_header}
			{box_header icon="calendar" label="<!rtticket>Custom resolve time" icon_class="fa-fw"}
				<input type="text" name="ticket[customresolvetime]"
					value="{if $ticket.customresolvetime}{$ticket.customresolvetime|date_format:"Y/m/d H:i"}{/if}"
					{tip class="lms-ui-datetime" trigger="customresolvetime"}>
			{/box_header}
		{/if}
	{/box_header}

	{box_contents}
		{box_panel}
			{block name="rtticketmodify-leftcolumn"}
			{if $layout.module != 'eventadd'}
			{box_row icon="customer" label="Customer" icon_class="fa-fw"}
				{$customer_selector='[name=&quot;ticket[custid]&quot;]'}
				{$address_selector='[name=&quot;ticket[address_id]&quot;]'}
				{customerlist form="ticket-form" customers=$customerlist selected=$customerid version=2
					selectname="ticket[customerid]" inputname="ticket[custid]"
					selecttip="Select customer from list or enter his data if is not a customer"
					customOnChange="change_customer('{$customer_selector}', '{$address_selector}');"}
			{/box_row}
			{/if}

			{box_row icon="user" label="Requestor" field_id="requestor" icon_class="fa-fw"}
				<div class="lms-ui-box-row">
					<select name="ticket[requestor_userid]" {tip class="lms-ui-advanced-select-test" text="Select requestor from list" trigger="requestor_userid"}>
						<option value="">{trans("<!person>— none —")}</option>
						<option value="0"{if $ticket.requestor_userid == '0'} selected{/if}>{trans("— indicated person —")}</option>
						{foreach $userlist as $user}
							{if $user.id != $ticket.requestor_userid
								&& ($hide_disabled_users && !$user.access
									|| $hide_deleted_users && $user.deleted)}
								{continue}
							{/if}
							<option value="{$user.id}"
								class="{if !$user.access} lms-ui-disabled{/if}{if $user.deleted} lms-ui-crossed{/if}"
								{if $ticket.requestor_userid == $user.id} selected{/if}
							>{strip}
								{$user.rname|trunescape:40} ({$user.login})
							{/strip}</option>
						{/foreach}
					</select>
					<label>
						<input type="checkbox" class="assign-to-me" data-userid="{$layout.logid}"
							data-target='[name="ticket[requestor_userid]"]'>
						{trans("assign to me")}
					</label>
				</div>
				<div class="lms-ui-box-row indicated-person">
					<div class="lms-ui-box-row-label">
						<label for="requestor_name">{trans("Name")}</label>
					</div>
					<div class="lms-ui-box-row-field">
						<input type="text" name="ticket[requestor_name]" id="requestor_name" value="{$ticket.requestor_name}" {tip trigger="requestor_name"}>
					</div>
				</div>
				<div class="lms-ui-box-row indicated-person">
					<div class="lms-ui-box-row-label">
						<label for="requestor_mail_combobox">{trans("E-mail")}</label>
					</div>
					<div class="lms-ui-box-row-field">
						<input type="hidden" name="ticket[requestor_customer_mail]" id="requestor_customer_mail"
							value="{$ticket.requestor_customer_mail}">
						<input type="hidden" name="ticket[requestor_mail]" id="requestor_mail"
							value="{$ticket.requestor_mail}">
						<select id="requestor_mail_combobox" autocomplete="off"
								data-value="{$ticket.requestor_mail}"
								data-alt-invalid-field="#requestor_mail"
								data-id-value="{$ticket.requestor_customer_mail}"
								data-alt-field="#requestor_customer_mail"
								{tip class="lms-ui-combobox" trigger="requestor_mail"}>
							{foreach $customercontacts.emails as $item}
								<option value="{$item.contact}"{if $item.contact == $ticket.requestor_customer_mail} selected{/if}
									>{$item.contact}{if !empty($item.name)} ({$item.name|escape}){/if}</option>
							{/foreach}
						</select>
					</div>
				</div>
				<div class="lms-ui-box-row indicated-person">
					<div class="lms-ui-box-row-label">
						<label for="requestor_phone_combobox">{trans("Phone")}</label>
					</div>
					<div class="lms-ui-box-row-field">
						<input type="hidden" name="ticket[requestor_customer_phone]" id="requestor_customer_phone"
							value="{$ticket.requestor_customer_phone}">
						<input type="hidden" name="ticket[requestor_phone]" id="requestor_phone"
							value="{$ticket.requestor_phone}">
						<select id="requestor_phone_combobox" autocomplete="off"
							data-value="{$ticket.requestor_phone}"
							data-alt-invalid-field="#requestor_phone"
							data-id-value="{$ticket.requestor_customer_phone}"
							data-alt-field="#requestor_customer_phone"
							{tip class="lms-ui-combobox" trigger="requestor_phone"}>
							{foreach $customercontacts.phones as $item}
								<option value="{$item.contact}"{if $item.contact == $ticket.requestor_customer_phone} selected{/if}
									>{$item.contact}{if !empty($item.name)} ({$item.name|escape}){/if}</option>
							{/foreach}
						</select>
					</div>
				</div>
			{/box_row}

{if $layout.module == 'rtticketadd'}
			{box_row icon="message" label="Message template" field_id="message-templates" id="message-template-row"
				visible=!empty($messagetemplates) icon_class="fa-fw"}
				{include file="rt/rtmessagetemplates.html" templates=$messagetemplates tip="Select message template"
					target='[name="ticket[body]"]'}
			{/box_row}

			{block name="rtticketadd-content"}
			{box_row icon="message" label="<!rt>Content" icon_class="fa-fw"}
				<div class="valign-middle">
					<textarea name="ticket[body]" id="ticket-body" cols="50" rows="5"
						{tip class="lms-ui-wysiwyg-editor lms-ui-helpdesk" text="Enter ticket content" trigger="body"}
						{if isset($ticket.wysiwyg.body)} data-wysiwyg="{$ticket.wysiwyg.body}"{/if}
						>{$ticket.body}</textarea>
					{speech_recognition target="#ticket-body"}
				</div>
			{/box_row}
			{/block}

			{box_row icon="note" label="Note template" field_id="note-templates" id="note-template-row"
				visible=!empty($notetemplates) icon_class="fa-fw"}
				{include file="rt/rtmessagetemplates.html" templates=$notetemplates tip="Select note template"
					target='[name="ticket[note]"]'}
			{/box_row}

			{box_row icon="note" label="Note" icon_class="fa-fw"}
				<div class="valign-middle">
					<textarea name="ticket[note]" id="ticket-note" cols="50" rows="5"
						{tip text="Enter ticket content" trigger="body"}
						>{$ticket.note}</textarea>
					{speech_recognition target="#ticket-note"}
				</div>
			{/box_row}

			{box_row icon="attachment" label="Attachments" icon_class="fa-fw"}
				{fileupload id="files" fileupload=$fileupload form="ticket-form"}
			{/box_row}
{/if}

			{box_row icon="categories" label="Categories" class="categories" icon_class="fa-fw"}
				{if ConfigHelper::checkConfig('rt.allow_empty_categories', ConfigHelper::checkConfig('phpui.helpdesk_allow_empty_categories'))}
				<input type="hidden" name="ticket[categorywarn]" value="{$ticket.categorywarn}">
				{/if}
				{include file="rt/rtcategoryselection.html" categories=$categories name_prefix="ticket[categories]"}
			{/box_row}

			{box_row icon="message" label="Notify users" labelid="notify" icon_class="fa-fw"}
				<INPUT type="checkbox" name="ticket[notify]" id="notify" value="1"{if $ticket.notify} checked{/if}>
			{/box_row}
			{/block}
		{/box_panel}
		{box_panel}
			{block name="rtticketmodify-rightcolumn"}
			{box_row icon="owner" label="Owner" icon_class="fa-fw"}
				<select size="1" name="ticket[owner]" id="owner"
						{tip class="lms-ui-advanced-select-test" text="Select user" trigger="owner"}>
					<option value="0">{trans("— select user —")}</option>
					{foreach $userlist as $user}
						{if $user.id != $ticket.owner
							&& ($hide_disabled_users && !$user.access
								|| $hide_deleted_users && $user.deleted)}
							{continue}
						{/if}
						<option value="{$user.id}"
							class="{if !$user.access} lms-ui-disabled{/if}{if $user.deleted} lms-ui-crossed{/if}"
							{if $user.id == $ticket.owner} selected{/if}
						>{strip}
							{$user.rname|trunescape:40} ({$user.login})
						{/strip}</option>
					{/foreach}
				</select>
				&nbsp;
				<label>
					<input type="checkbox" class="assign-to-me" data-userid="{$layout.logid}"
						data-target='[name="ticket[owner]"]'>
					{trans("assign to me")}
				</label>
			{/box_row}

			{box_row icon="verifier" label="Verifier" field_id="rtverifiers" icon_class="fa-fw"}
				{if $layout.module != 'rtticketedit' || !$ticket.oldverifierid || $ticket.oldverifierid == $layout.logid || ConfigHelper::checkConfig('privileges.superuser')}
					<select size="1" name="ticket[verifierid]" {tip class="lms-ui-advanced-select-test" text="Select user" trigger="verifierid"}>
						<option value="">{trans("— select user —")}</option>
						{foreach $userlist as $user}
							{if $user.id != $ticket.verifierid
								&& ($hide_disabled_users && !$user.access
									|| $hide_deleted_users && $user.deleted)}
								{continue}
							{/if}
							<option value="{$user.id}"
								class="{if !$user.access} lms-ui-disabled{/if}{if $user.deleted} lms-ui-crossed{/if}"
								{if $user.id == $ticket.verifierid} selected{/if}
							>{strip}
								{$user.rname|trunescape:40} ({$user.login})
							{/strip}</option>
						{/foreach}
					</select>
				{else}
					<input type="hidden" name="ticket[verifierid]" value="{$ticket.oldverifierid}">
					<span title="{trans("Only verifier can change this")}">{$ticket.verifier_username}</span>
				{/if}
			{/box_row}

			{box_row icon="deadline" label="<!rt>Deadline" icon_class="fa-fw"}
				{if $layout.module != 'rtticketedit'
					|| ConfigHelper::checkConfig('rt.allow_all_users_modify_deadline', ConfigHelper::checkConfig('phpui.helpdesk_allow_all_users_modify_deadline'))
					|| !$ticket.oldverifierid || $ticket.oldverifierid == $layout.logid}
					<input type="text" name="ticket[deadline]" value="{if $ticket.deadline}{$ticket.deadline|date_format:"Y/m/d H:i"}{/if}" size="20"
						{tip text="Enter deadline in YYYY/MM/DD HH:MM format or click to select it from applet" class="lms-ui-datetime" trigger="deadline"}>
					{day_selection elem='[name="ticket[deadline]"]'}
				{else}
					<input type="hidden" name="ticket[deadline]" value="{if $ticket.deadline}{$ticket.deadline|date_format:"Y/m/d H:i"}{/if}">
					<span title="{trans("Only verifier can change this")}">{if $ticket.deadline}{$ticket.deadline|date_format:"Y-m-d H:i"}{else}{trans("<!rt>— none —")}{/if}</span>
				{/if}
			{/box_row}

			{box_row icon="status" label="Status" icon_class="fa-fw"}
				<SELECT name="ticket[state]" id="state" {tip class="lms-ui-advanced-select-test" text="Select status" trigger="state"}>
					{foreach $_RT_STATES as $stateidx => $state}
					<OPTION value="{$stateidx}"{if $ticket.state == $stateidx} selected{/if}>{$state.label}</OPTION>
					{/foreach}
				</SELECT>
				&nbsp;
				<label>
					<INPUT type="checkbox" name="ticket[resolve]" id="resolve" value="{$smarty.const.RT_RESOLVED}"{if isset($message.resolve) || $message.state == $smarty.const.RT_RESOLVED} CHECKED{/if}{tip trigger="resolve"}>
					{trans("resolve ticket")}
				</label>
			{/box_row}

			{box_row icon="queue" label="Queue" icon_class="fa-fw"}
				<select size="1" name="ticket[queue]" id="queue-selection"
						{tip class="lms-ui-advanced-select-test" text="Select queue" trigger="queue"}>
					{foreach $queuelist as $item}
						<option value="{$item.id}"
							{if $item.newticketsubject && $item.newticketbody || $item.newticketsmsbody} data-newticket-notify="1"{/if}
							{if $item.id == $queue} selected{/if}>{$item.name}</option>
					{/foreach}
				</select>
			{/box_row}

			{box_row icon="cause" label="Cause" icon_class="fa-fw"}
				<SELECT size="1" name="ticket[cause]" {tip text="Select ticket cause" trigger="cause"}>
					<OPTION value="0" {if !$ticket.cause}selected{/if}>{trans("unknown/other")}</OPTION>
					<OPTION value="1" {if $ticket.cause == 1}selected{/if}>{trans("customer's side")}</OPTION>
					<OPTION value="2" {if $ticket.cause == 2}selected{/if}>{trans("company's side")}</OPTION>
				</SELECT>
			{/box_row}

			{box_row icon="source" label="Ticket source" icon_class="fa-fw"}
				<SELECT size="1" name="ticket[source]" {tip text="Select ticket source" trigger="source"}>
					{foreach Localisation::arraySort($_RT_SOURCES) as $sourceidx => $source}
					<OPTION value="{$sourceidx}"{if $ticket.source == $sourceidx}selected {/if}>{$source}</OPTION>
					{/foreach}
				</SELECT>
			{/box_row}

			{box_row icon="priority" label="Priority" icon_class="fa-fw"}
				<SELECT size="1" name="ticket[priority]" {tip text="Set ticket priority" trigger="priority"}>
					{foreach $_RT_PRIORITIES as $priorityidx => $priority}
					<OPTION value="{$priorityidx}"{if $ticket.priority == $priorityidx} selected{/if}>{$priority}</OPTION>
					{/foreach}
					<OPTION value="" {if (is_array($ticket.priority) && in_array(null, $ticket.priority)) || is_null($ticket.priority)} selected{/if}>{trans("undefined")}</OPTION>
				</SELECT>
			{/box_row}

{if $layout.module != 'eventadd'}
			{box_row icon="location" label="Location" icon_class="fa-fw"}
				{if $ticket.address_id > 0 && $customerid}
					{$selected_address_id = $ticket.address_id}
				{else}
					{$selected_address_id = null}
				{/if}
				{if $address_id_warning}
					{$class = "lms-ui-error"}
				{else}
					{$class = ""}
				{/if}
				{if $layout.module == 'rtticketedit'}
					{$preselection = false}
				{else}
					{$preselection = true}
				{/if}
				{include file="customer/customeraddresses.html" id="customer_addresses" name="ticket[address_id]"
					trigger="address_id" selected_address_id=$selected_address_id class=$class
					preselection=$preselection}
				<input type="hidden" name="address_id_warning" value="{if $address_id_warning}1{else}0{/if}">
			{/box_row}
{/if}

			{$visibility=(!empty($nodes) && $layout.module != 'eventadd')}
			{box_row class="node-row" icon="node" label="Node:" visible=$visibility}
				<select class="node-list" name="ticket[nodeid]" {tip text="Select node" trigger="nodeid"}>
					<option value="">{trans("— none —")}</option>
					{if !empty($nodes)}
						{foreach $nodes as $node}
							<option value="{$node.id}"{if $node.id == $ticket.nodeid || count($nodes) == 1} selected{/if}>{$node.name}: {$node.location}</option>
						{/foreach}
					{/if}
				</select>
			{/box_row}

			{box_row icon="netnode" label="Network node" icon_class="fa-fw"}
				{network_node_selection
					elemname='ticket[netnodeid]'
					onchange="xajax_netnode_changed($(this).val(), $('#ticketnetdevid').val(), 'ticket', 'ticketnetdevs', 'ticketnetdevid')"
					selected=$ticket.netnodeid}
			{/box_row}

			{box_row icon="netdev" label="Device" field_id="ticketnetdevs" icon_class="fa-fw"}
				{include file="rt/rtnetdevs.html" form="ticket"}
			{/box_row}

			{box_row id="customernotify-row" icon="message" label="Notify customer" labelid="customernotify"}
				<input type="checkbox" id="customernotify" name="ticket[customernotify]" value="1"{if isset($ticket.customernotify)} checked{/if}>
			{/box_row}

			{box_row icon="invproject" label="Investment project" icon_class="fa-fw"}
				<SELECT name="ticket[invprojectid]" {tip class="lms-ui-advanced-select-test" text="Select investment projects" trigger="invprojectid"}>
					<OPTION value="">{trans("— none —")}</OPTION>
					{foreach $invprojectlist as $idx => $project}
					<OPTION value="{$idx}" {if $idx == $ticket.invprojectid} selected{/if}>
					{$project.name} ({$project.id})
					</OPTION>
					{/foreach}
				</SELECT>
			{/box_row}

			{function ticket_item_content}
				{capture name="item_content_result" assign="item_content_result"}{strip}
					{hint icon="info" mode="toggle" url="?m=rtticketinfo&id={$item.id}"}
					(#{$item.id})
					<a class="lms-ui-list-item-name" href="?m=rtticketview&id={$item.id}">{$item.name}</a>
				{/strip}{/capture}
			{/function}

			{box_row icon="parentticket" label="Primary ticket" icon_class="fa-fw"}
				{if isset($ticket)}
					{$parent = $ticket.parent}
				{else}
					{$parent = array()}
				{/if}
				{list id="parent-ticket" tipid="parentid" tip="Enter ID of primary ticket" items=$parent
					field_name_pattern="ticket[parentid]" item_content="ticket_item_content"}
			{/box_row}

			{if empty($ticket.parent)}
				{$class = "blend"}
				{$tip = "No primary ticket is selected!"}
			{else}
				{$class = ""}
				{$tip = ""}
			{/if}
			{box_row icon="relatedticket" label="Related tickets" class=$class tip=$tip icon_class="fa-fw"}
				{list id="related-tickets" tipid="related-tickets-id" tip="Enter ticket identifier or ticket subject part"
					items=$ticket.relatedtickets field_name_pattern="ticket[relatedtickets][%id%]" item_content="ticket_item_content"
					disabled=empty($ticket.parent)}
			{/box_row}
			{/block}
{/box_panel}
	{/box_contents}

	{if $layout.module != 'eventadd'}
	{box_buttons}
		{button type="submit" icon="save" accesskey="s" label="Submit"}
		{button icon="cancel" onclick="location.href = '?m=rtqueueview{if isset($backid)}#{$backid}{/if}'"
			label="Cancel"}
	{/box_buttons}
	{/if}
{/box_container}

<script src="js/templates/rt/rtticketmodify.js"></script>
<script>

		$('body').on('change', '.template-selector', function() {
			var selected = $('option:selected', this);
			if (parseInt(selected.val()) == 0) {
				return;
			}
			$('[name="ticket[subject]"]').val(Base64.decode(selected.attr('data-subject')));

			var message = Base64.decode(selected.attr('data-message'));
			var editor = tinyMCE.get(0);
			if (editor) {
				editor.setContent(message);
			}
			$($(this).attr('data-target')).val(message);
		});

		initListQuickSearch({
			selector: '#parent-ticket',
			field_name_pattern: 'ticket[parentid]',
			single: true,
			ajax: '?m=quicksearch&api=1&ajax=1&mode=ticket&what=',
			item_content: function(item) {
				return sprintf("#%06d", item.id) + ' <a href="?m=rtticketview&id=' + item.id + '">' +
					item.name + '</a>';
			},
			excluded_elements: [ {if isset($ticket.ticketid)}'{$ticket.ticketid}'{/if} ],
			conflict_lists: [ '#related-tickets' ]
		});
		initListQuickSearch({
			selector: '#related-tickets',
			field_name_pattern: 'ticket[relatedtickets][%id%]',
			ajax: '?m=quicksearch&api=1&ajax=1&mode=ticket&what=',
			item_content: function(item) {
				return sprintf("#%06d", item.id) + ' <a href="?m=rtticketview&id=' + item.id + '">' +
						item.name + '</a>';
			},
			excluded_elements: [ {if isset($ticket.ticketid)}'{$ticket.ticketid}'{/if} ],
			conflict_lists: [ '#parent-ticket' ]
		});

	$(function() {
		$('#customer_addresses').on('lms:address_list_updated', function() {
			{if ConfigHelper::checkConfig('rt.location_required')}
				{if $layout.module == 'eventadd'}
					$(this).prop('required', $('[name="event[custid]"]').val().length > 0).trigger('lms:advanced_select_update');
				{else}
					$(this).prop('required', $('[name="ticket[custid]"]').val().length > 0).trigger('lms:advanced_select_update');
				{/if}
			{/if}
		}).on('lms:advanced_select_validate_required', function(e, data) {
			{if ConfigHelper::checkConfig('rt.location_required')}
				{if $layout.module == 'eventadd'}
					var emptyCustomerId = !$('[name="event[custid]"]').val().length;
				{else}
					var emptyCustomerId = !$('[name="ticket[custid]"]').val().length;
				{/if}
				data.advancedSelectElement.toggleClass('lms-ui-error', !emptyCustomerId && data.invalidValue);
				this.setCustomValidity(!emptyCustomerId && data.invalidValue ? $t('Location address is not selected') : '');
			{/if}
		});

		{if $layout.module != 'eventadd'}
			$('#customer_addresses').trigger('lms:address_list_updated');
		{/if}

		{if ConfigHelper::checkConfig('rt.notify_auto_check_on_queue_change')}
			// Auto-check "Notify users" when queue changes
			var queueElem = $('[name="ticket[queue]"]');
			var originalQueue = queueElem.val();
			queueElem.change(function() {
				$('#notify').prop('checked', $(this).val() !== originalQueue);
			});
		{/if}
	});

</script>
