<h3>{$lang.datatable.email_template_edit}</h3><hr>
<div class="sub-layout d-flex flex-row">
	<div class="order-1 custom_scroll">
		<h6 class="border-bottom pb-2">{$lang.datatable.file_list}:</h6>
		{function name="renderFolder" folder=$tpl_files tplDirectory=$tplDirectory}
			<ul class="list-group me-1">
				{foreach $folder.folders as $folderName => $subFolder}
					<li>
						<div class="accordion" id="accordion_{$folderName|replace:'/':'_'}">
							<div class="accordion-item">
								<h3 class="accordion-header" id="heading_{$folderName|replace:'/':'_'}">
									<a class="accordion-button collapsed p-1" type="button" data-bs-toggle="collapse" data-bs-target="#collapse_{$folderName|replace:'/':'_'}" aria-expanded="false" aria-controls="collapse_{$folderName|replace:'/':'_'}">
										<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-folder" viewBox="0 0 16 16">
											<path d="M8 1a1 1 0 0 1 1 1v1h6a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1h4V1z"/>
										</svg>
										<span class="ps-1">{$folderName}</span>
									</a>
								</h3>
								<div id="collapse_{$folderName|replace:'/':'_'}" class="accordion-collapse body-color collapse" aria-labelledby="heading_{$folderName|replace:'/':'_'}">
									<div class="accordion-body">
										{call name="renderFolder" folder=$subFolder tplDirectory=$tplDirectory}
									</div>
								</div>
							</div>
						</div>
					</li>
				{/foreach}
				{foreach $folder.files as $file}
					<li class="mt-1 mb-2">
						<div class="d-flex align-items-center px-2">
							<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi bi-file-earmark-text me-2" viewBox="0 0 16 16">
								<path d="M14 4.5V14a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V2a2 2 0 0 1 2-2h5.5L14 4.5zM10 1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V5h-3.5a.5.5 0 0 1-.5-.5V1z"/>
								<path d="M5 7h6v1H5zm0 2h6v1H5zm0 2h4v1H5z"/>
							</svg>
							<a href="admin?action=email-templates-edit&sub_action=edit&tpl_file={$tplDirectory}/{$file}" class="text-decoration-none py-0">{$file|basename}</a>
						</div>
					</li>
				{/foreach}
			</ul>
		{/function}
		{call name="renderFolder" folder=$tpl_files tplDirectory=$tplDirectory}
	</div>

	<div class="order-2 flex-grow-1 custom_scroll border-start ps-3">
		{if isset($tpl_file)}
			{*<div class="tooltip-container modern-tooltip">
				<div class="tooltip-item">
					<span class="icon">👤</span>
					<span class="label">Отправитель:</span>
					<span class="value">{ $senderName }</span>
				</div>
				<div class="tooltip-item">
					<span class="icon">👤</span>
					<span class="label">Получатель:</span>
					<span class="value">{ $receiverName }</span>
				</div>
				<div class="tooltip-item">
					<span class="icon">💳</span>
					<span class="label">Сумма:</span>
					<span class="value">{ $paymentSum }</span>
				</div>
			</div>*}
			<style>
				.modern-tooltip {
					border-radius: 8px;
					padding: 12px;
					box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
					font-family: Arial, sans-serif;
					color: #333;
				}

				.tooltip-item {
					display: flex;
					align-items: center;
					margin-bottom: 8px;
				}

				.tooltip-item:last-child {
					margin-bottom: 0;
				}

				.icon {
					margin-right: 8px;
					font-size: 16px;
				}

				.label {
					font-weight: bold;
					margin-right: 6px;
					color: #555;
				}
			</style>

			<h6>{$lang.datatable.file_name}: {if isset($tpl_content)}{$tpl_file}{/if}</h6>
			<textarea class="editor" id="editor" name="editor">{if isset($tpl_content)}{$tpl_content}{/if}</textarea>
			<br>
			<button class="btn btn-primary" {if $access['modules.update']}onclick="saveChanges()"{/if}>{$lang.datatable.save_edits}</button>
			<div id="status"></div>
			<script>
				// Инициализация редактора
				var editor;

				// Функция для инициализации CodeMirror с нужной темой
				function initializeEditor() {
					var theme = document.documentElement.getAttribute('data-bs-theme') === 'dark' ? 'dracula' : 'default';

					if (editor) {
						// Если редактор уже инициализирован, просто меняем тему
						editor.setOption("theme", theme);
					} else {
						// Инициализация CodeMirror с нумерацией строк
						editor = CodeMirror.fromTextArea(document.getElementById('editor'), {
							lineNumbers: true,
							mode: "text/x-php",
							theme: theme,
							matchBrackets: true,
							// lineWrapping: true, // Перенос строк
							viewportMargin: Infinity
						});

						// Добавляем границы снизу ко всем строкам
						addBottomBorderToAllLines();
					}
				}

				// Функция для добавления границы снизу ко всем строкам
				function addBottomBorderToAllLines() {
					var totalLines = editor.lineCount();
					for (var i = 0; i < totalLines; i++) {
						editor.addLineClass(i, 'wrap', 'editor-line-border-bottom');
					}
				}

				// Инициализация редактора при загрузке страницы
				initializeEditor();

				// Отслеживание изменений атрибута data-bs-theme
				var observer = new MutationObserver(function(mutations) {
					mutations.forEach(function(mutation) {
						if (mutation.attributeName === 'data-bs-theme') {
							// При изменении атрибута перезапускаем редактор с новой темой
							initializeEditor();
						}
					});
				});

				// Наблюдаем за изменениями атрибутов <html>
				observer.observe(document.documentElement, {
					attributes: true
				});
			</script>
		{if $access['modules.update']}
			<script>
				// Функция сохранения
				function saveChanges() {
					var tplContent = editor.getValue(); // Получаем контент из CodeMirror
					var tplFile = '{$tpl_file}';
					var tplDirectory = '{$tplDirectory}';
					var xhr = new XMLHttpRequest();
					xhr.onreadystatechange = function () {
						if (xhr.readyState === 4 && xhr.status === 200) {
							document.getElementById('status').innerHTML = xhr.responseText;
						}
					};
					xhr.open('POST', 'admin?action=email-templates-edit&sub_action=save', true);
					xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
					xhr.send('tpl_file=' + encodeURIComponent(tplFile) + '&tpl_content=' + encodeURIComponent(tplContent) + '&tpl_directory=' + encodeURIComponent(tplDirectory));
				}
			</script>
		{/if}
		{/if}
	</div>
</div>
<script>
	var fatSection = document.getElementById('fatSection');
	fatSection.classList.add('active');
	var filesAndTemplates = document.getElementById('filesAndTemplates');
	filesAndTemplates.classList.add('show');
	var currentLink = document.getElementById('emailTemplates');
	currentLink.classList.add('active');
</script>