<?php
/*
** Zabbix
** Copyright (C) 2001-2023 Zabbix SIA
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**/


/**
 * @var CView $this
 */
?>

<script>
	const current_userid = <?= CWebUser::$data['userid'] ?>;
	const current_user_name = <?= json_encode(getUserFullname(CWebUser::$data)) ?>;
	const old_dashboardid = <?= $data['old_dashboardid'] ?>;
	let dashboard_inaccessible = <?= json_encode($data['dashboard_inaccessible']) ?>;
	let subscriptions_sanitized = true;

	function sanitizeSubscriptions() {
		document.querySelectorAll('#subscriptions-table tbody tr').forEach((row) => {
			if (row.querySelector('[name*=recipient_inaccessible]').value == 1) {
				const recipientid = row.querySelector('[name*=recipientid]').value;

				if (row.querySelector('[name*=recipient_type]').value == <?= ZBX_REPORT_RECIPIENT_TYPE_USER ?>) {
					userids.delete(recipientid);
				}
				else {
					usrgrpids.delete(recipientid);
				}

				row.remove();
			}
			else if (row.querySelector('[name*=creator_type]').value == <?= ZBX_REPORT_RECIPIENT_TYPE_USER ?>) {
				const creator = row.querySelector('[name*=creatorid]').parentNode.querySelector('span');
				creator.textContent = current_user_name;
				creator.setAttribute('title', current_user_name);
				creator.classList.remove('<?= ZBX_STYLE_GREY ?>');

				row.querySelector('[name*=creatorid]').value = <?= CWebUser::$data['userid'] ?>;
				row.querySelector('[name*=creator_type]').value = <?= ZBX_REPORT_CREATOR_TYPE_USER ?>;
				row.querySelector('[name*=creator_name]').value = current_user_name;
				row.querySelector('[name*=creator_inaccessible]').value = 0;
			}
		});

		subscriptions_sanitized = true;
	}

	function showConfirmationDialog(e) {
		const update_btn = document.querySelector('#update');

		if (update_btn === null || subscriptions_sanitized) {
			return;
		}

		e.preventDefault();

		overlayDialogue({
			'class': 'modal-popup position-middle',
			'content': <?= json_encode(_('Report generated by other users will be changed to the current user.')) ?>,
			'buttons': [
				{
					'title': <?= json_encode(_('OK')) ?>,
					'focused': true,
					'action': () => {
						sanitizeSubscriptions();
						e.target.submit();
					}
				},
				{
					'title': <?= json_encode(_('Cancel')) ?>,
					'cancel': true,
					'class': '<?= ZBX_STYLE_BTN_ALT ?>',
					'action': () => {}
				}
			]
		}, update_btn);
	}

	document.addEventListener('DOMContentLoaded', () => {
		$('#dashboardid').on('change', () => {
			dashboard_inaccessible = false;

			const dashboard = $('#dashboardid').multiSelect('getData');

			if (old_dashboardid == 0 || !dashboard.length) {
				return;
			}

			subscriptions_sanitized = dashboard[0].id == old_dashboardid;
		});

		document.querySelector('#scheduledreport-form').addEventListener('submit', showConfirmationDialog);

		const clone_btn = document.querySelector('#clone');

		if (clone_btn !== null) {
			clone_btn.addEventListener('click', () => {
				if ($('#userid').data('multiSelect').options.disabled) {
					$('#userid')
						.multiSelect('clean')
						.multiSelect('addData', [{
							id: current_userid,
							name: current_user_name
						}]);
				}

				document.querySelector('#name').focus();

				if (dashboard_inaccessible) {
					$('#dashboardid').multiSelect('clean');
				}

				sanitizeSubscriptions();

				const update_btn = document.querySelector('#update');
				update_btn.setAttribute('id', 'add');
				update_btn.setAttribute('value', 'scheduledreport.create');
				update_btn.textContent = <?= json_encode(_('Add')) ?>;

				document.querySelectorAll('#reportid, #clone, #delete').forEach((elem) => { elem.remove(); });
			});
		}

		const test_btn = document.querySelector('#test');

		if (test_btn !== null) {
			test_btn.addEventListener('click', (event) => {
				const form = event.target.closest('form');
				const parameters = {
					period: form.elements['period'].value,
					now: Math.floor(Date.now() / 1000)
				};

				if (typeof form.elements['dashboardid'] !== 'undefined') {
					parameters.dashboardid = form.elements['dashboardid'].value;
				}

				document.querySelectorAll('#name, #subject, #message').forEach((elem) => {
					parameters[elem.id] = elem.value.trim();
				});

				PopUp('popup.scheduledreport.test', parameters, {
					dialogue_class: 'modal-popup-medium',
					trigger_element: event.target
				});
			});
		}
	});
</script>
