{extends file="layout.html"}
{block name=title}LMS: {$layout.pagetitle|striphtml}{/block}
{block name=module_content}
{$document_confirm_date_required = intval(ConfigHelper::getConfig('phpui.document_confirm_date_required'))}
<!--// $Id$ //-->
<H1>{$layout.pagetitle}</H1>
{$xajax}

<style>

	.document-button-panel {
		display: flex;
		flex-direction: column;
	}

	.document-button-subpanel,
	.document-button-subpanel > div {
		display: flex;
		align-items: center;
	}

	.document-button-subpanel:first-child > div:not(:first-child) {
		flex-wrap: wrap;
	}

	.document-button-subpanel {
		flex-wrap: wrap;
	}

	.document-button-subpanel > div {
		display: flex;
		flex-wrap: nowrap;
	}

	.document-button-subpanel > div > * {
		margin-left: 0.3em;
		margin-right: 0.3em;
	}

/*
	.document-button-subpanel > div:first-child {
		padding-bottom: 0.3em;
	}
*/

	table.lmsbox > thead >tr:not(:first-child) {
		border-top: none;
	}

	#document-period {
		display: flex;
		flex-direction: column;
	}

	#document-period > *:not(:first-child) {
		margin-top: 0.3em;
	}

	#document-period > div {
		display: flex;
	}

	#document-period > div > div:first-child {
		display: flex;
		flex-direction: column;
	}

	#document-period > div > div:first-child > :not(:first-child) {
		margin-top: 0.3em;
	}

	#document-period > div > div:not(:first-child) {
		display: flex;
		align-items: center;
		margin-left: 0.5em;
	}

	#dynamic-period-option {
		display: flex;
		align-items: center;
	}

</style>

<script>

	function DocTemplateChanged() {
		reset_login_timeout();
		var consents = {};
		$("[data-consent-type]").each(function() {
			consents[$(this).attr('data-consent-type')] = $(this).prop('checked');
		});
		xajax_DocTemplateChanged(
			$('[name="document[type]"]').val(),
			$('[name="document[templ]"]').val(),
			$('[name="customerid"]').val(),
			consents
		);
	}

	function DocTypeChanged() {
		reset_login_timeout();
		xajax_DocTypeChanged($('[name="document[type]"]').val(),
			$('[name="customerid"]').val());
	}

	function enable_templates() {
		$('#templ').prop('disabled', false);
	}

	function disable_templates() {
		$('#templ').val('');
		$('#templ').prop('disabled', true);
	}

	function CustomerChanged() {
		reset_login_timeout();
		xajax_CustomerChanged($('[name="document[type]"]').val(),
			$('[name="document[templ]"]').val(),
			$('[name="customerid"]').val());
		if (typeof customer_assignment_helper !== 'undefined') {
			customer_assignment_helper.setCustomer($('[name="customerid"]').val());
		}
	}

</script>

<form name="documentadd" method="POST" id="documentadd-form" action="?m=documentadd">
<input type="submit" class="hiddenbtn">
{if $customer.id}{$cid=$customer.id}{elseif $document.customerid}{$cid=$document.customerid}{else}{$cid=""}{/if}
<table class="lmsbox">
	<colgroup>
		<col style="width: 1%;">
		<col style="width: 1%;">
		<col style="width: 98%;">
	</colgroup>
    <thead>
		<tr>
			<td>
				{icon name="type"}
			</td>
			<td>
				<strong>{trans("Type:")}</strong>
			</td>
			<td>
				<select size="1" name="document[type]" id="doctype" onchange="DocTypeChanged();"
						{tip class="lms-ui-advanced-select-test" text="Select document type" trigger="type"} required>
					<option value="0">{trans("— select type —")}</option>
					{foreach Localisation::arraySort($_DOCTYPES) as $key => $item}
						{if $key < 0 && in_array($key, $docrights)}
							<option value="{$key}"{if $document.type==$key} selected{/if}>{$item}</option>
						{/if}
					{/foreach}
				</select>
			</td>
		</tr>
		<tr style="display:table-row;">
			<td>
				{icon name="template"}
			</td>
			<td>
				<strong>{trans("Template:")}</strong>
			</td>
			<td>
				<select size="1" id="templ" name="document[templ]" {if $document.type >= 0} disabled{/if}
					onchange="DocTemplateChanged();"
					{tip text="Select template to generate new document if you haven't got prepared file" trigger="templ"}
				>
					{include file="document/documenttemplateoptions.html"}
				</select>
			</td>
		</tr>
		<tr>
			<td>
				{icon name="document"}
			</td>
			<td class="nobr">
				<strong>{trans("Title:")}</strong>
			</td>
			<td class="nobr">
				<input type="text" id="title" name="document[title]" value="{$document.title}" required
					{tip text="Enter document title" trigger="title"} size="40">
			</td>
		</tr>
    </thead>
    <tbody>
		<tr id="customerselection">
			<td>
				{icon name="customer"}
			</td>
			<td class="nobr">
				<strong>{trans("Customer:")}</strong>
			</td>
			<td>
				{customerlist customers=$customers selected=$cid version=2
					selectname="customer" input_id="customerid_input" inputname="customerid" required=true customOnChange="CustomerChanged();"}
			</td>
		</tr>
		<tr>
			<td>
				{icon name="id"}
			</td>
			<td>
				<strong>{trans("Number:")}</strong>
			</td>
			<td>
				{numberplan_selection
					customer_selector = "#customerid_input"
					doctype_selector  = "#doctype"
					cdate_selector    = "[name='document[cdate]']"
					numberplanlist    = $numberplans
					input_name        = "document[number]"
					input_value       = $document.number
					select_name       = "document[numberplanid]"
					selected          = $document.numberplanid
					number_trigger    = "number"
					plan_trigger      = "numberplanid"
					time              = $document.cdate
					customer_id       = $cid
					planDocumentType  = $planDocumentType
					reference_selector = '#refdoc'
				}
			</td>
		</tr>
		<tr>
			<td>
				{icon name="calendar"}
			</td>
			<td class="nobr">
				<strong>{trans("Consent date")}</strong>
			</td>
			<td class="nobr">
				{if ConfigHelper::checkPrivilege("document_consent_date")}
					<input type="text" name="document[cdate]" value="{$document.cdate|date_format:"Y/m/d"}" size="12"
						placeholder="{trans("yyyy/mm/dd")}" data-cdate="{$document.cdate}"
							{tip class="lms-ui-date" text="Enter date of settlement in YYYY/MM/DD format (empty field means current date) or click to select it from calendar" trigger="cdate"}
					>
					{if $document.cdatewarning}
						<input type="hidden" name="document[cdatewarning]" value="1">
					{/if}
				{else}
					<input type="hidden" name="document[cdate]" value="{$document.cdate|date_format:"Y/m/d"}">
					{$document.cdate|date_format:"Y-m-d"}
				{/if}
			</td>
		</tr>
		<tr>
			<td class="valign-top">
				{icon name="period"}
			</td>
			<td class="valign-top">
				<strong>{trans("Period")}</strong>
			</td>
			<td>
				<div id="document-period">
					{capture assign="hint"}{strip}
						The validity date range of the document is determined upon its approval.
					{/strip}{/capture}
					<div id="dynamic-period-option">
						<label>
							<input type="checkbox" name="document[dynamicperiod]" value="1"
								{if !empty($document.dynamicperiod)} checked{/if}>
							{trans("<!document-period>dynamic")}
						</label>
						{hint content=$hint}
					</div>
					{$allow_past_date = ConfigHelper::checkConfig('documents.allow_past_date', true)}
					<div>
						<div>
							<label>
								{trans("from")}
								<input type="text" name="document[fromdate]" id="fromdate"
									value="{if $document.fromdate}{$document.fromdate}{/if}"
									placeholder="{trans("yyyy/mm/dd")}"
									{tip class="lms-ui-date lms-ui-date-unix" text="Enter start date in YYYY/MM/DD format (optional)" trigger="fromdate"}
									{if !$allow_past_date}data-min-date="{date('Y-m-d')}"{/if}
									size="10">&nbsp;
							</label>
							<label>
								{trans("to")}
								<input type="text" name="document[todate]" id="todate"
									value="{if $document.todate}{$document.todate}{/if}"
									placeholder="{trans("yyyy/mm/dd")}"
									{tip class="lms-ui-date lms-ui-date-unix" text="Enter end date in YYYY/MM/DD format (optional)" trigger="todate"}
									{if !$allow_past_date}data-min-date="{date('Y-m-d')}"{/if}
									size="10">
							</label>
						</div>
						{date_period_preset from="#fromdate" to="#todate" periods="previous-year,previous-month,current-year,current-month,next-month,next-year"}
					</div>
				</div>
			</td>
		</tr>
		<tr>
			<td>
				{icon name="service"}
			</td>
			<td>
				<strong>{trans("Service start")}</strong>
			</td>
			<td>
				<input type="text" name="document[startdate]" id="startdate"
					value="{if $document.startdate}{$document.startdate}{/if}"
					placeholder="{trans("yyyy/mm/dd")}"
					{tip class="lms-ui-date lms-ui-date-unix" text="Enter service start date in YYYY/MM/DD format (optional)" trigger="startdate"}
					size="10">
			</td>
		</tr>
		<tr{if $document.closed} style="display: none;"{/if}>
			<td>
				{icon name="period"}
			</td>
			<td>
				<strong>{trans("Wait for customer action till:")}</strong>
			</td>
			<td>
				<input type="text" name="document[confirmdate]" id="confirmdate"
					value="{if $document.confirmdate}{$document.confirmdate}{/if}"
					placeholder="{trans("yyyy/mm/dd")}"
					{tip class="lms-ui-date lms-ui-date-unix" text="Enter date in YYYY/MM/DD format we wait for customer action till (optional)" trigger="confirmdate"}
					size="10">
			</td>
		</tr>
		<tr>
			<td>
				{icon name="description"}
			</td>
			<td>
				<strong>{trans("Description:")}</strong>
			</td>
			<td>
				<textarea name="document[description]" rows="5" cols="50"
					{tip text="Enter additional information (optional)"}>{$document.description}</textarea>
			</td>
		</tr>
		<tr id="referencedocument">
			{include file="document/documentreference.html"}
		</tr>
		{block name="documentpluginreference"}
		{/block}
		<tr id="document-file-row"{if !$document.type} style="display: none;"{/if}>
			<td>
				{icon name="import"}
			</td>
			<td>
				<strong>{trans("Files:")}</strong>
			</td>
			<td>
				{fileupload id="attachments" fileupload=$fileupload form="documentadd-form"}
			</td>
		</tr>
		<tr id="attachment-row"{if !$attachment_result} style="display: none;"{/if}>
			<td>
				{icon name="import"}
			</td>
			<td class="nobr">
				<strong>{trans("Document attachments:")}</strong>
			</td>
			<td id="attachment-cell">
				{$attachment_result}
			</td>
		</tr>
		<tr>
			<td>
				{icon name="confirm"}
			</td>
			<td class="nobr">
				<label for="closed">
					<strong>{trans("Confirmed:")}</strong>
				</label>
			</td>
			<td>
				<input type="checkbox" name="document[closed]" id="closed" value="1" {if $document.closed} checked{/if}>
			</td>
		</tr>
		<tr>
			<td colspan="3" class="lms-ui-box-buttons">
				<div class="document-button-panel">
					<div class="document-button-subpanel">
						<div>
							{button icon="save" class="operation-button" id="submit-button" label="Submit"}
							{button icon="cancel" label="Cancel" onclick="location.href = '?m=documentlist';"}
						</div>
						<div>
							<label>
								<input type="checkbox" id="new-window-toggle">
								{trans("new window")}
							</label>
							<label>
								<input type="checkbox" name="document[reuse]" value="on" {if $document.reuse}checked{/if}>
								{trans("Display this form again, when that document is saved")}
							</label>
						</div>
					</div>
					<div class="document-button-subpanel">
						<div>
							{button icon="print" class="operation-button" id="print-button" label="Print"}
							<label>
								<input type="checkbox" name="with-attachments" value="1">
								{trans("attachments")}
							</label>
							<label>
								<input type="checkbox" name="document[sendmail]" value="1"{if !empty($document.sendmail)} checked{/if}>
								{trans("send to customer email")}
							</label>
							<label>
								<input type="checkbox" name="document[sendmail-with-reference-document]" value="1"
									{if !empty($document['sendmail-with-reference-document'])} checked{/if}
									{if empty($document.sendmail)} disabled{/if}>
								<span class="lms-ui-label">
									{trans("with reference document")}
								</span>
							</label>
						</div>
					</div>
				</div>
			</td>
		</tr>
    </tbody>
</table>

{if !empty($promotions)}
{block name="documentpromotions"}
	{include file="document/documentpromotions.html"}
{/block}
{/if}

{block name="document-consents"}
	{include file="document/documentconsents.html"}
{/block}

<div id="plugin" name="plugin">{$plugin_result}</div>
{$script_result}
</form>

<script>

	$('.operation-button').click(function() {
		var form = $('#documentadd-form');
		if (form.get(0).checkValidity()) {
			$('.operation-button').prop('disabled', !$('#new-window-toggle').prop('checked'));
			setStorageItem('documentadd_cdate', $('[name="document[cdate]"]').val());
			setStorageItem('documentadd_cdate_lastuse', new Date().getTime());
			if ($(this).is('#print-button')) {
				form.attr('action', form.attr('action') + '&print=1');
				{if empty($promotions)}
					form.submit();
				{/if}
			} else {
				{if empty($promotions)}
					form.attr('action', form.attr('action').replace('&print=1', '')).submit();
				{/if}
			}
		}
	});

	var cdateLastUse = getStorageItem("documentadd_cdate_lastuse");
	if (cdateLastUse == null || new Date().getTime() - cdateLastUse > 900 * 1000) {
		removeStorageItem("documentadd_cdate");
		removeStorageItem("documentadd_cdate_lastuse");
	}
	var cdate = getStorageItem("documentadd_cdate");
	if (cdate !== null) {
		$('[name="document[cdate]"]').val(cdate);
	}

	$(function() {
		$('form[name="documentadd"] [name="document[title]"]').focus();

		$('[name="document[cdate]"]').change(function() {
			removeStorageItem("documentadd_cdate");
		});

		$('#new-window-toggle').click(function() {
			if (this.checked) {
				$('form[name="documentadd"]').attr('target', '_blank');
			} else {
				$('form[name="documentadd"]').removeAttr('target');
			}
		});

		$('[name="document[type]"]').change(function() {
			$('#document-file-row').toggle(parseInt($(this).val()) != 0);
		});

		$('[name="document[sendmail]"]').change(function() {
			$('[name="document[sendmail-with-reference-document]"]').prop('disabled', !$(this).prop('checked'));
		});

		var documentConfirmDateRequired = parseInt({$document_confirm_date_required});

		function confirmDateRequired() {
			var fromDate = parseInt($('[name="document[fromdate]"]').val());
			$('#confirmdate').prop(
					'required',
					!$('#closed').prop('checked') && fromDate && fromDate > (Date.now() / 1000) + documentConfirmDateRequired * 86400
			);
		}

		$('#closed').change(function() {
			if (documentConfirmDateRequired) {
				confirmDateRequired();
			}
			$('#confirmdate').closest('tr').toggle(!$(this).prop('checked'));
		});

		if (documentConfirmDateRequired) {
			$('#fromdate').change(confirmDateRequired).change();
		}

		{if !empty($defaultDocEngine)}
			DocTemplateChanged();
		{/if}
	});
	//setnumberplans();

</script>
{/block}
