{extends file="layout.html"}
{block name=title}LMS: {$layout.pagetitle|striphtml}{/block}
{block name=module_content}

{$hide_disabled_users = ConfigHelper::checkConfig('documents.hide_disabled_users')}
{$hide_deleted_users = ConfigHelper::checkConfig('documents.hide_deleted_users')}

<!--// $Id$ //-->
<H1>{$layout.pagetitle}</H1>

{$default_all_attachments = ConfigHelper::checkConfig('documents.default_all_attachments')}

<style>

	#usertype {
		margin-right: 0.8em;
	}

	#buttons tr:first-child td {
		padding-bottom: 0.15em;
	}

	#buttons tr:not(:first-child):not(:last-child) td {
		padding-top: 0.15em;
		padding-bottom: 0.15em;
	}

	#buttons tr:last-child td {
		padding-top: 0.15em;
	}

	#buttons tr td > *:not(:first-child) {
		margin-left: 0.3em;
	}

</style>

<script>

	{if $docid}
	window.open('?m=documentview&id={$docid}{if $attachments}&attachments=1{/if}');
	{/if}

	function toggle_all_attachments(docid) {
		var elem = $('#allattachments-' + docid);
		var toggle = $('#allattachments-toggle-' + docid);
		elem.toggle();
		if (elem.is(':visible'))
			toggle.html('<img src="img/desc_order.gif">');
		else
			toggle.html('<img src="img/asc_order.gif">');
	}

	function applyFilter() {
		document.choosefilter.submit();
	}

</script>

<TABLE class="lmsbox lms-ui-background-cycle">
	<COLGROUP>
		<COL style="width: 1%;">
		<COL style="width: 1%;">
		<COL style="width: 1%;">
		<COL style="width: 96%;">
		<COL style="width: 1%;">
	</COLGROUP>
    <THEAD>
	<TR>
		<TD class="nobr">
			<A href="?m=documentlist&o=cdate{if $filter.direction == "asc" && $filter.order == "cdate"},desc{/if}">{trans("Creation date<!document>")}</A>{if $filter.order == "cdate"}<IMG src="img/{if $filter.direction == "desc"}asc{else}desc{/if}_order.gif" alt="">{/if}
			/ <A href="?m=documentlist&o=sdate{if $filter.direction == "asc" && $filter.order == "sdate"},desc{/if}">{trans("Confirmation date<!document>")}:</A>{if $filter.order == "sdate"}<IMG src="img/{if $filter.direction == "desc"}asc{else}desc{/if}_order.gif" alt="">{/if}
			<BR><B>{trans("Number:")}</B>
		</TD>
		<TD class="nobr">
			<A href="?m=documentlist&o=user{if $filter.direction == "asc" && $filter.order == "user"},desc{/if}">{trans("Created by<!document>")}</A>{if $filter.order == "user"}<IMG src="img/{if $filter.direction == "desc"}asc{else}desc{/if}_order.gif" alt="">{/if}
			/ <A href="?m=documentlist&o=cuser{if $filter.direction == "asc" && $filter.order == "cuser"},desc{/if}">{trans("Confirmed by<!document>")}:</A>{if $filter.order == "cuser"}<IMG src="img/{if $filter.direction == "desc"}asc{else}desc{/if}_order.gif" alt="">{/if}
			<BR><A href="?m=documentlist&o=type{if $filter.direction == "asc" && $filter.order == "type"},desc{/if}"><B>{trans("Type:")}</B></A>{if $filter.order == "type"}<IMG src="img/{if $filter.direction == "desc"}asc{else}desc{/if}_order.gif" alt="">{/if}
		</TD>
		<TD class="nobr">
			<A href="?m=documentlist&amp;o=title{if $filter.direction == "asc" && $filter.order == "title"},desc{/if}">{trans("Title:")}</A>{if $filter.order == "title"}<IMG src="img/{if $filter.direction == "desc"}asc{else}desc{/if}_order.gif" alt="">{/if}
			<BR>{trans("Period")}
			<BR>{trans("Reference document:")}
		</TD>
		<TD class="nobr"> <A href="?m=documentlist&amp;o=customer{if $filter.direction == "asc" && $filter.order == "customer"},desc{/if}">{trans("Customer:")}</A>{if $filter.order == "customer"}<IMG src="img/{if $filter.direction == "desc"}asc{else}desc{/if}_order.gif" alt="">{/if}</TD>
		<TD class="text-right nobr">
			{button icon="add" label="New Document" onclick="location.href = '?m=documentadd{if !empty($filter.customer)}&cid={$filter.customer}{/if}{if !empty($filter.type) && count($filter.type) == 1}&type={reset($filter.type)}{/if}';"}
		</TD>
	</TR>
	<TR>
		<TD colspan="5">
			<div class="lms-ui-filter-container">
				<div class="lms-ui-filter-definition">
                    <FORM method="GET" name="choosefilter" id="documentlist">
					<input type="hidden" name="m" value="documentlist">

					<span class="bold">{trans("Filter:")}</span> {trans("Customer:")}
					{customerlist form="documentlist" customers=$customers selected=$filter.customer selectname="customer" inputname="c" firstoption="— all customers —"}

					<input type="hidden" name="t[]" value="0">
					<label>
						{trans("Type:")}
						<select size="1" name="t[]" multiple class="lms-ui-multiselect"
							data-default-value="{trans("— all —")}">
							{foreach Localisation::arraySort($_DOCTYPES) as $key => $item}
								{if $key < 0}
									<option value="{$key}"{if is_array($filter.type) && in_array($key, $filter.type)} selected{/if}>{$item}</option>
								{/if}
							{/foreach}
						</select>
					</label>

					<input type="hidden" name="service[]" value="0">
					<label>
						{trans("Service:")}
						<SELECT size="1" name="service[]" multiple class="lms-ui-multiselect" data-default-value="{trans("— all —")}">
							{foreach $_SERVICETYPES as $key => $item}
							<OPTION VALUE="{$key}"{if is_array($filter.service) && in_array($key, $filter.service)} selected{/if}>{$item}</OPTION>
							{/foreach}
						</SELECT>
					</label>

					<span class="nobr">
						{trans("User:")}
						{if empty($users)}
							<input type="hidden" name="usertype" value="">
							<input type="hidden" name="u[]" value="0">
						{else}
							<select name="usertype" id="usertype">
								<option value="creator"{if empty($filter.usertype) || $filter.usertype == 'creator'} selected{/if}>{trans("creator")}</option>
								<option value="authorising"{if $filter.usertype == 'authorising'} selected{/if}>{trans("authorising")}</option>
								<option value="archiver"{if empty($filter.usertype) || $filter.usertype == 'archiver'} selected{/if}>{trans("archiver")}</option>
							</select>

							<input type="hidden" name="u[]" value="0">
							<select name="u[]" multiple class="lms-ui-multiselect" data-default-value="{trans("— all —")}">
								{foreach $users as $user}
									{if (!is_array($filter.userid) || !in_array($user.id, $filter.userid))
										&& ($hide_disabled_users && empty($user.access)
										|| $hide_deleted_users && !empty($user.deleted))}
										{continue}
									{/if}
									<option value="{$user.id}"
										{if empty($user.access)} data-blend{/if}
										{if !empty($user.deleted)} data-crossed{/if}
										{if is_array($filter.userid) && in_array($user.id, $filter.userid)} selected{/if}
											>{$user.rname|trunescape:40} ({$user.login})</option>
								{/foreach}
							</select>
						{/if}
					</span>


					<label>
						{trans("Period:")}
						<SELECT name="periodtype">
							<OPTION value="creationdate"{if empty($filter.periodtype) || $filter.periodtype == 'creationdate'} selected{/if}>{trans("creation date")}</OPTION>
							<OPTION value="confirmationdate"{if $filter.periodtype == 'confirmationdate'} selected{/if}>{trans("confirmation date")}</OPTION>
							<OPTION value="archivizationdate"{if $filter.periodtype == 'archivizationdate'} selected{/if}>{trans("archivization date")}</OPTION>
							<OPTION value="fromdate"{if $filter.periodtype == 'fromdate'} selected{/if}>{trans("'from' date")}</OPTION>
							<OPTION value="todate"{if $filter.periodtype == 'todate'} selected{/if}>{trans("'to' date")}</OPTION>
						</SELECT>
					</label>

					<span class="lms-ui-date-period-container">
						{date_period_preset from="#documentlist [name=\"from\"]" to="#documentlist [name=\"to\"]"}
						<span>{trans("from")}</span>
						<input type="text" name="from" size="10" maxlength="10"
							value="{if $filter.from > 0}{$filter.from|date_format:"Y/m/d"}{/if}"
							{tip class="lms-ui-date" text="Enter date in YYYY/MM/DD format (empty field means no limit) or click to choose it from calendar"}>
						<span>{trans("to")}</span>
						<input type="text" name="to" size="10" maxlength="10"
							value="{if $filter.to > 0}{$filter.to|date_format:"Y/m/d"}{/if}"
							{tip class="lms-ui-date" text="Enter date in YYYY/MM/DD format (empty field means no limit) or click to choose it from calendar"}>
					</span>

					{if $numberplans|size}
						<label>
							{trans("Number plan:")}
							<SELECT name="p" {tip text="Select numbering plan"}>
								<OPTION value="0">{trans("— all —")}</OPTION>
								{foreach $numberplans as $plan}
								{$period = $plan.period}
								<OPTION value="{$plan.id}"{if $filter.numberplan == $plan.id} selected{/if}>{number number=$plan.next template=$plan.template time=$invoice.cdate customerid=$filter.customer} ({$_NUM_PERIODS.$period})</OPTION>
								{/foreach}
							</SELECT>
						</label>
					{else}
						<input type="hidden" name="p" value="0">
					{/if}

					<label>
						{trans("Status:")}
						<SELECT name="s" {tip text="Select document status"}>
							<OPTION value="-1">{trans("— all —")} </OPTION>
							<OPTION value="0"{if $filter.status == 0} selected{/if}>{trans("unconfirmed")}</OPTION>
							<OPTION value="1"{if $filter.status == 1} selected{/if}>{trans("confirmed")}</OPTION>
							<OPTION value="4"{if $filter.status == 5} selected{/if}>{trans("confirmed (signed document scan)")}</OPTION>
							<OPTION value="5"{if $filter.status == 4} selected{/if}>{trans("confirmed (sms authorization)")}</OPTION>
							<OPTION value="2"{if $filter.status == 2} selected{/if}>{trans("review (signed document scan)")}</OPTION>
							<OPTION value="3"{if $filter.status == 3} selected{/if}>{trans("waiting for signed document scan")}</OPTION>
							<option value="6"{if $filter.status == 6} selected{/if}>{trans("waiting for customer action (expired)")}</option>
						</SELECT>
					</label>

					<label>
						{trans("Archived:")}
						<SELECT name="archived" {tip text="Select document archived state"}>
							<OPTION value="-1">{trans("— all —")} </OPTION>
							<OPTION value="1"{if $filter.archived == 1} selected{/if}>{trans("yes")}</OPTION>
							<OPTION value="0"{if $filter.archived == 0} selected{/if}>{trans("no")}</OPTION>
						</SELECT>
					</label>

					<A href="javascript:applyFilter();">&raquo;&raquo;&raquo;</A>
                    </form>
				</div>
				{persistent_filter}
			</div>
		</TD>
	</TR>
	{if $pagination->getTotal() != 0}
	<TR>
		<TD class="lms-ui-pagination" COLSPAN="5">
			{include file="pagination.html" form="page-form"}
		</TD>
	</TR>
	{/if}
    </THEAD>
    <TBODY class="lms-ui-multi-check">
	<FORM METHOD="POST" NAME="page" id="page-form" ACTION="?m=documentedit&action=confirm">
	{foreach $documentlist as $doc}
	{assign var=docid value=$doc.docid}
	{if empty($doc.attachments)}
		{$doc.attachments = array()}
	{/if}
	{$docattach = reset($doc.attachments)}
	{capture assign="url"}?m=documentview&id={$doc.docid}{if $default_all_attachments}&attachments=1{elseif $doc.attachments|size == 1}&attachmentid={$docattach.id}{/if}{/capture}
	<TR class="highlight{if $doc.closed} lms-ui-document-closed{/if}{if $doc.archived} lms-ui-document-archived{/if}" data-archived="{if $doc.archived}1{else}0{/if}" data-closed="{if $doc.closed}1{else}0{/if}"
		data-senddate="{if $doc.senddate}{$doc.senddate|date_format:"Y-m-d H:i"}{else}{$doc.senddate}{/if}"
		data-popup-menu-title="{t a=$doc.docid|string_format:"#%06d"}Document $a{/t}">
		<TD class="nobr" data-target-url="{$url}"{if $doc.description} {tip text=$doc.description}{/if}>
			{$doc.cdate|date_format:"Y-m-d H:i"}{if $doc.sdate} / {$doc.sdate|date_format:"Y-m-d H:i"}{/if}
			{if $doc.closed == $smarty.const.DOC_OPEN && $doc.confirmdate}
				{hint text=$doc.confirmdate|date_format:"Y-m-d H:i" icon="wait"}
			{/if}
			{if $doc.number}<BR>
				<B>{number number=$doc.number template=$doc.template time=$doc.cdate customerid=$doc.customerid}</B>
			{/if}
		</TD>
		<TD class="nobr" data-target-url="{$url}">
			{$doc.username|escape}
			{if $doc.cuserid} / {$doc.cusername|escape}{/if}
			{if $doc.closed == $smarty.const.DOC_CLOSED_AFTER_CUSTOMER_SMS}
				{if !$doc.cuserid}
					{icon name="sms" tip="customer has accepted document via sms"}
				{/if}
			{elseif $doc.closed == $smarty.const.DOC_CLOSED_AFTER_CUSTOMER_SCAN}
				{icon name="sign" tip="attached document scans with customer signature"}
			{/if}
			<BR><B>{assign var=type value=$doc.type}{$_DOCTYPES.$type}</B>
		</TD>
		<TD class="nobr" data-target-url="{$url}">
			{$doc.title|truncate:40:"&hellip;":true}
			{if $doc.description}
				{hint icon="info" content=$doc.description|escape|replace:"\n":'<br>'}
			{/if}
			{if $doc.fromdate || $doc.todate}<BR>
				{if $doc.fromdate}{trans("from")} {$doc.fromdate|date_format:"Y-m-d"}{/if}
				{if $doc.todate}{trans("to")} {$doc.todate|date_format:"Y-m-d"}{/if}
				{if empty($doc.closed) && ($doc.fromdate || $doc.todate) && !empty($doc.dynamicperiod)}{trans("<!document-period>(dynamic)")}{/if}
			{/if}
			{if $doc.reference}<br>
			<a href="?m={if $doc.reference.type < 0}documentview{else}invoice{/if}&id={$doc.reference.id}" rel="external">
				{t a=$_DOCTYPES[$doc.reference.type] b=$doc.reference.fullnumber c=$doc.reference.cdate|date_format:"Y-m-d"}$a no. $b issued on $c{/t}
			</a>
			{/if}
            {block name="documentlistpluginreference"}
            {/block}
		</TD>
		<TD class="nobr"><A href="?m=customerinfo&amp;id={$doc.customerid}">{$doc.name|truncate:40:"&hellip;":true}</A></TD>
		<TD class="lms-ui-buttons text-right nobr">
			{buttons}
				{if $doc.senddocuments}
					{textformat assign="tip" wrap=5000}
						{if $doc.senddate}{trans("Send document again")}<br><strong>{t a=$doc.senddate|date_format:"Y-m-d H:i"}(already sent on $a){/t}</strong>{else}{trans("Document send")}{/if}
					{/textformat}
					{button type="link" class="send-document" icon="{if $doc.senddate}mailsent{else}mail{/if}" href="?m=documentsend&id={$doc.docid}"
						tip=$tip}
				{/if}
				{assign var=type value=$doc.type}
				{button type="link" icon="save" href="?m=documentview&id={$doc.docid}&save=1" tip="Save"}
				{if ! $doc.closed && ($docrights.$type.rights & $smarty.const.DOCRIGHT_CONFIRM)}
					{button type="link" icon="confirm" href="?m=documentedit&id={$doc.docid}&action=confirm" tip="Confirm"}
				{/if}
				{if $doc.closed && !$doc.archived && ($docrights.$type.rights & $smarty.const.DOCRIGHT_ARCHIVE)}
					{button type="link" icon="archive" href="?m=documentedit&id={$doc.docid}&action=archive" tip="Archive"
						class="archive-document"}
				{/if}
				{if ($docrights.$type.rights & $smarty.const.DOCRIGHT_DELETE)}
					{button type="link" icon="delete" class="delete-document"
						href="?m=documentdel&id={$doc.docid}" tip="Remove document"}
				{/if}
				{if ($docrights.$type.rights & $smarty.const.DOCRIGHT_EDIT)}
					{button type="link" icon="edit" href="?m=documentedit&id={$doc.docid}" tip="Edit"}
				{/if}
				{if $docattach.type == 1 || $doc.attachments|size == 1}
					{documentview id="global-{$doc.docid}-{$docattach.id}" type=$docattach.contenttype name=$docattach.filename
						url=$url external=true
						text="<i class=\"lms-ui-icon-view{if preg_match('/pdf/',$docattach.contenttype)} pdf{elseif preg_match('#^application/(rtf|.+(oasis|opendocument|openxml).+)$#i',$docattach.contenttype)} xls{/if}\"></i>"
						tip="Preview"}
				{/if}
			{/buttons}
			{if $doc.attachments|size > 1 || $docattach.type < 1}
			<a href="#" id="allattachments-toggle-{$doc.docid}" onclick="toggle_all_attachments({$doc.docid}); return false;" title="{trans("more document attachments")}">
				<img src="img/asc_order.gif">
			</a>
			{/if}
			<div id="allattachments-{$doc.docid}" style="display: none;">
				{foreach $doc.attachments as $docattach}
					{documentview
						id="local-{$doc.docid}-{$docattach.id}"
						type=$docattach.contenttype
						doctype=$doc.type
						name=$docattach.filename
						url="?m=documentview&id={$doc.docid}&attachmentid={$docattach.id}"
						external=true
					}
					{if $docattach.type == -1}<i class="lms-ui-icon-user" title="<strong>{t a=date("Y/m/d H:i", $docattach.cdate)}Sent by customer at $a{/t}</strong>"></i>{/if}
					<br>
				{/foreach}
			</div>
			<INPUT TYPE="checkbox" NAME="marks[{$docid}]" VALUE="{$docid}" class="lms-ui-multi-check"{if $marks.$docid} checked{/if}>
		</TD>
	</TR>
	{foreachelse}
	<tr>
		<td colspan="5" class="empty-table">
			{trans("No such documents matching search criteria or list is empty.")}
		</td>
	</tr>
	{/foreach}
	</FORM>
    </TBODY>
    <TFOOT>
	{if $pagination->getTotal() != 0}
	<TR>
		<TD class="lms-ui-pagination" COLSPAN="5">
			{include file="pagination.html" form="page-form"}
		</TD>
	</TR>
	{/if}
	<TR>
		<TD COLSPAN="5">
			{if $documentlist|size}
			<TABLE WIDTH="100%" id="buttons">
				<TR>
					<TD class="nobr">
						{button icon="mail" label="Send documents" id="send-documents"}
						{button icon="confirm" label="Confirm" id="confirm-documents"}
						{button icon="archive" label="Archive" id="archive-documents"}
						{button icon="delete" label="Delete" id="delete-documents"}
					</TD>
					<TD class="text-right nobr">
						<label>
							{trans("Check All")}
							<INPUT TYPE="checkbox" class="lms-ui-multi-check-all" VALUE="1">
						</label>
					</TD>
				</TR>
				<tr>
					<td colspan="2">
						<fieldset>
							{button icon="print" label="Print" id="print-documents"}
							<label>
								<input type="checkbox" name="attachments" value="1" form="page-form">
								{trans("attachments")}
							</label>
							<label>
								<input type="checkbox" name="related" value="1" form="page-form">
								{trans("related documents")}
							</label>
							<select name="related_documents[]" form="page-form"  multiple class="lms-ui-multiselect"}
									data-default-value="{trans("- all -")}" data-shorten-to-default-value="false">
								{foreach Localisation::arraySort($_DOCTYPES) as $key => $related_document}
									{if $key < 0}
									<option value="{$key}">{$related_document}</option>
									{/if}
								{/foreach}
							</select>
						</fieldset>
					</td>
				</tr>
			</TABLE>
			{/if}
		</TD>
	</TR>
    </TFOOT>
</TABLE>

<script>

	$('#send-documents').click(function() {
		if (!$(this).closest('tfoot').prev('.lms-ui-multi-check').find('input.lms-ui-multi-check:checked').length) {
			alertDialog($t('No document has been selected!'), this);
			return;
		}

		confirmDialog($t("Are you sure, you want to send documents to customer?"), this).done(function() {
			document.page.action="?m=documentsend";
			document.page.target="_blank";
			document.page.submit();
		});
	});

	$('#print-documents').click(function() {
		if (!$(this).closest('tfoot').prev('.lms-ui-multi-check').find('input.lms-ui-multi-check:checked').length) {
			alertDialog($t('No document has been selected!'), this);
			return;
		}

		document.page.action="?m=documentview";
		document.page.target="_blank";
		document.page.submit();
	});

	$('#confirm-documents').click(function() {
		if (!$(this).closest('tfoot').prev('.lms-ui-multi-check').find('input.lms-ui-multi-check:checked').length) {
			alertDialog($t('No document has been selected!'), this);
			return;
		}

		document.page.action="?m=documentedit&action=confirm";
		document.page.target="";
		document.page.submit();
	});

	$('#archive-documents').click(function() {
		if (!$(this).closest('tfoot').prev('.lms-ui-multi-check').find('input.lms-ui-multi-check:checked').length) {
			alertDialog($t('No document has been selected!'), this);
			return;
		}

		{if !ConfigHelper::checkConfig('documents.allow_unapproved_document_archiving')}
			if ($('tr[data-closed="0"] :checked').length) {
				alertDialog($t('One or more of selected documents are not confirmed!'), this);
				return;
			}
		{/if}

		confirmDialog($t("Are you sure, you want to archive selected documents?"), this).done(function() {
			document.page.action = "?m=documentedit&action=archive";
			document.page.target = "";
			document.page.submit();
		});
	});

	$('#delete-documents').click(function() {
		if (!$(this).closest('tfoot').prev('.lms-ui-multi-check').find('input.lms-ui-multi-check:checked').length) {
			alertDialog($t('No document has been selected!'), this);
			return;
		}

		confirmDialog($t("Are you sure, you want to delete selected documents?"), this).done(function () {
			document.page.action = "?m=documentdel";
			document.page.target = "";
			document.page.submit();
		});
	});

	$('.archive-document').click(function() {
		confirmDialog($t("Are you sure, you want to archive that document?"), this).done(function() {
			location.href = $(this).attr('href');
		});
		return false;
	});

	$('.delete-document').click(function() {
		confirmDialog($t("Are you sure, you want to remove that document?"), this).done(function() {
			location.href = $(this).attr('href');
		});
		return false;
	});

	$('.send-document').click(function() {
		var senddate = $(this).closest('tr').attr('data-senddate');
		if (parseInt(senddate) === 0) {
			confirmDialog($t("Are you sure, you want to send document to customer?"), this).done(function () {
				window.open($(this).attr('href'));
			});
		} else {
            confirmDialog($t("Document was sent to customer already on $a. Are you sure, you want to send document again?", senddate), this).done(function () {
                window.open($(this).attr('href'));
            });
        }
		return false;
	});

</script>

{/block}
