<div class="comments-area" style=" margin-bottom: 30px;">
	<div class="row mb-2">
		<div class="col-sm-6 d-none d-md-block ">
			<h3>
				Управление правами доступа</h3>
		</div>
		<!-- /.col -->
		<div class="col-sm-6">
			<ol class="breadcrumb float-sm-right">
				<li class="breadcrumb-item">
					<a href="{{ php_self }}">
						<i class="fa fa-home"></i>
					</a>
				</li>
				<li class="breadcrumb-item">
					<a href="?mod=perm">Управление правами доступа</a>
				</li>

			</ol>
		</div>
		<!-- /.col -->
	</div>
	<!-- /.row -->
</div>
<div class="comments-area">
	<h3 id="reply-title" class="comment-reply-title">
		<a href="?mod=perm">Управление правами доступа</a>
	</h3>
	<style>
		.pChanged {
			border-color: var(--warning);
		}
	</style>
	<script type="text/javascript">
		var permDefault = {{ DEFAULT_JSON }};

function onUpdatePerm(name) {
	var f = document.getElementById('permSubmit');
	var v = permDefault[name];
	f[name].classList.toggle('pChanged', f[name].value != v);
}

// AJAX сохранение без перехода на страницу результата
document.addEventListener('DOMContentLoaded', function () {
	var form = document.getElementById('permSubmit');
	if (!form) return;

	form.addEventListener('submit', function (e) {
		e.preventDefault();
		var fd = new FormData(form);
		fd.append('ajax', '1');

		const btn = form.querySelector('button[type="submit"]');
		if (btn) {
			btn.disabled = true;
			btn.dataset._old = btn.innerHTML;
			btn.innerHTML = 'Сохранение...';
		}

		fetch('admin.php?mod=perm', {
			method: 'POST',
			body: fd,
			credentials: 'same-origin'
		}).then(r => r.json()).then(data => {
			if (data.success) {
				let header = 'Права доступа: Успешно';
				let bodyMsg = '';
				if (Array.isArray(data.changes) && data.changes.length) {
					const maxLines = 12;
					let lines = [];
					for (let i = 0; i < data.changes.length; i++) {
						if (i >= maxLines) break;
						const ch = data.changes[i];
						let line = '[' + (ch.groupTitle || ch.group) + '] ' + (ch.title || ch.id) + ': ' + ch.displayOld + ' → ' + ch.displayNew;
						lines.push(line);
					}
					if (data.changes.length > maxLines) {
						lines.push('… +' + (data.changes.length - maxLines) + ' ещё');
					}
					bodyMsg = lines.join('\n');
				} else {
					bodyMsg = 'Изменений нет';
				}

				let htmlList = '';
				if (bodyMsg) {
					let items = bodyMsg.split('\n').map(l => '<li style="margin:2px 0;word-wrap:break-word">' + l.replace(/</g, '&lt;') + '</li>').join('');
					htmlList = '<div class="perm-toast-wrapper" style="max-width:560px">' +
						'<div style="font-weight:600;margin:0 0 6px">' + header + ' (' + (data.updated || 0) + ')</div>' +
						'<div class="perm-toast-scroll" style="max-height:300px;overflow:auto;border:1px solid #e2e6ea;border-radius:4px;padding:6px;background:#fff">' +
						'<ol style="margin:0;padding-left:18px;max-width:100%">' + items + '</ol>' +
						'</div>' +
						'<div style="margin-top:8px;display:flex;gap:6px;flex-wrap:wrap">' +
						'<button type="button" class="btn btn-sm btn-outline-secondary perm-copy-btn">Copy</button>' +
						'<button type="button" class="btn btn-sm btn-outline-secondary perm-close-btn">Закрыть</button>' +
						'</div>' +
						'</div>';
				}

				try {
					if (window.showToast) {
						let toast = showToast(htmlList, {
							type: 'success',
							title: 'Права доступа',
							sticked: true,
							timeout: 0
						});
						setTimeout(() => {
							if (!toast) return;
							let copyBtn = toast.querySelector('.perm-copy-btn');
							let closeBtn = toast.querySelector('.perm-close-btn');
							if (copyBtn) {
								copyBtn.addEventListener('click', () => {
									try {
										navigator.clipboard.writeText(bodyMsg);
										copyBtn.textContent = 'OK';
										setTimeout(() => copyBtn.textContent = 'Copy', 1500);
									} catch (e) {}
								});
							}
							if (closeBtn) {
								closeBtn.addEventListener('click', () => {
									try {
										toast.parentNode && toast.parentNode.removeChild(toast);
									} catch (e) {}
								});
							}
						}, 30);
					} else if (window.show_info) {
						show_info(bodyMsg);
					} else {
						alert(header + '\n' + bodyMsg);
					}
				} catch (ex) {}

				// Сбрасываем подсветку изменённых полей
				if (Array.isArray(data.changes)) {
					data.changes.forEach(ch => {
						if (ch.formName && form.elements[ch.formName]) {
							permDefault[ch.formName] = form.elements[ch.formName].value;
							form.elements[ch.formName].classList.remove('pChanged');
						}
					});
				}
			} else {
				try {
					if (window.show_error) {
						show_error('Результат: Ошибка');
					} else {
						alert('Результат: Ошибка');
					}
				} catch (ex) {}
			}
		}).catch(err => {
			console.error('Permissions save error', err);
			try {
				if (window.show_error) {
					show_error('Network/JS error');
				} else {
					alert('Network/JS error');
				}
			} catch (ex) {}
		}).finally(() => {
			if (btn) {
				btn.disabled = false;
				btn.innerHTML = btn.dataset._old || 'Сохранить изменения';
			}
		});
	});
});
	</script>
	<!-- Form header -->
	<form id="permSubmit" name="permSubmit" method="POST">
		<input type="hidden" name="save" value="1"/>
		<input type="hidden" name="token" value="{{ token }}"/>
		<!-- /Form header -->
		<!-- Group menu header -->
		<ul class="nav nav-tabs" id="userTabs" role="tablist">
			{% for group in GRP %}
				<li class="nav-item">
					<a class="nav-link {% if loop.first %}active{% endif %}" id="tab-{{ group.id }}" data-toggle="tab" href="#userTabs-{{ group.id }}" role="tab" aria-controls="userTabs-{{ group.id }}" aria-selected="{% if loop.first %}true{% else %}false{% endif %}">{{ group.title }}</a>
				</li>
			{% endfor %}
		</ul>
		<!-- Group content header -->
		<div class="tab-content mt-3" id="userTabsContent">
			{% for group in GRP %}
				<!-- Content for group [{{ group.id }}] {{ group.title }} -->
				<div class="tab-pane fade {% if loop.first %}show active{% endif %}" id="userTabs-{{ group.id }}" role="tabpanel" aria-labelledby="tab-{{ group.id }}">
					<div>
						<i>Управление правами группы пользователей:
							<b>{{ group.title }}</b>
						</i>
					</div>
					<br/>
					{% for block in CONFIG %}
						<div class="pconf">
							<h1>{{ block.title }}</h1>
							{% if (block.description) %}
								<i>{{ block.description }}</i><br/>
							{% endif %}
							{% for area in block.items %}
								<h2>{{ area.title }}</h2>
								{% if (area.description) %}
									<i>{{ area.description }}</i><br/><br/>
								{% endif %}
								<table class="table table-sm">
									<thead>
										<tr class="contHead">
											<td width="220">
												<b>#ID</b>
											</td>
											<td>
												<b>Описание</b>
											</td>
											<td width="110">
												<b>Доступ</b>
											</td>
										</tr>
									</thead>
									<tbody>
							{% for entry in area.items %}
								<tr class="contentEntry1">
									<td>
										<strong>{{entry.id}}</strong>
									</td>
									<td>{{ entry.title }}</td>
									<td>
										<select name="{{ entry.name }}|{{group.id}}" onchange="onUpdatePerm('{{ entry.name }}|{{group.id}}');" class="custom-select custom-select-sm">
											<option value="-1">--</option>
											<option value="0" {% if (isSet(entry.perm[group.id]) and (not entry.perm[group.id])) %} selected="selected" {% endif %}>Нет</option>
											<option value="1" {% if (isSet(entry.perm[group.id]) and (entry.perm[group.id])) %} selected="selected" {% endif %}>Да</option>
										</select>
									</td>
								</tr>
							{% endfor %}
									</tbody>
								</table>
								<br/>
							{% endfor %}
						</div>
					{% endfor %}
				</div>
			{% endfor %}
		</div>
		<!-- /Tab content -->
		<div class="form-group my-3 text-center">
			<button type="submit" class="btn btn-outline-success">Сохранить изменения</button>
		</div>
	</form>
</div>
