<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>

<div class="col-12">
	<h3 class="mb-3">Добавить товар в магазин: <a target="_blank" href="/shops/?shop_id={$shop.shop_id}">{$shop.shop_name}</a></h3>

	<form method="POST" enctype="multipart/form-data">

		<!-- Табы -->
		<ul class="nav nav-tabs mb-3">
			<li class="nav-item">
				<button type="button" class="nav-link active" data-bs-toggle="tab" data-bs-target="#tab-main">Основное</button>
			</li>
			<li class="nav-item">
				<button type="button" class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-images">Изображения</button>
			</li>
			<li class="nav-item">
				<button type="button" class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-attributes">Характеристики</button>
			</li>
			<li class="nav-item">
				<button type="button" class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-seo">SEO</button>
			</li>
		</ul>

		<div class="tab-content">

			<!-- Основное -->
			<div class="tab-pane fade show active" id="tab-main">
				<div class="row">

					<div class="col-md-6">

						<div class="mb-3">
							<label class="form-label">Название товара *</label>
							<input type="text" name="name" class="form-control" required>
						</div>

						<div class="mb-3">
							<label class="form-label">Slug (URL) *</label>
							<input type="text" name="slug" class="form-control" required>
						</div>

						<div class="mb-3">
							<label class="form-label">Цена *</label>
							<input type="number" step="0.01" name="price" class="form-control" required>
						</div>

						<div class="mb-3">
							<label class="form-label">Количество на складе</label>
							<input type="number" name="stock" class="form-control">
						</div>

						<div class="form-check form-switch mb-3">
							<input class="form-check-input" type="checkbox" name="is_active" checked>
							<label class="form-check-label">Активный товар</label>
						</div>

					</div>

					<div class="col-md-6">
						<select class="form-select array-select form-control mt-2 mb-2 h142" name="category[]" id="category" multiple>
							<option selected disabled value="">- Категория -</option>
							{foreach from=$categories item=category}
								{if $category.parentid == 0}
									<option value="{$category.id}" style="font-weight: bold;">{$category.name}</option>
									{foreach from=$categories item=subcategory}
										{if $subcategory.parentid == $category.id}
											<option value="{$subcategory.id}">{$subcategory.name}</option>
										{/if}
									{/foreach}
								{/if}
							{/foreach}
						</select>

						<label class="form-label">Описание</label>
						<textarea name="description" class="form-control" rows="8"></textarea>
					</div>

				</div>
			</div>

			<!-- Изображения -->
			<div class="tab-pane fade" id="tab-images">
				<div class="mb-3">
					<label class="form-label">Изображения товара</label>
					<input type="file" name="images[]" id="productImages" multiple class="form-control">

					<div id="imagePreview" class="d-flex flex-wrap gap-2 mt-3"></div>
				</div>

			</div>

			<div class="tab-pane fade" id="tab-attributes">
				<div class="mb-3">
					<button type="button" id="addAttribute" class="btn btn-sm btn-outline-primary mb-2">Добавить характеристику</button>
				</div>
				<div id="attributesContainer" class="d-flex flex-column gap-2"></div>
			</div>

			<!-- SEO -->
			<div class="tab-pane fade" id="tab-seo">
				<div class="mb-3">
					<input type="text" name="meta_keys" class="form-control" placeholder="Meta keywords">
				</div>
				<div class="mb-3">
					<input type="text" name="meta_desc" class="form-control" placeholder="Meta description">
				</div>
			</div>

		</div>

		<!-- Hidden -->
		<input type="hidden" name="shop_id" value="{$shop.shop_id}">

		<!-- Submit -->
		<button type="submit" name="add_shop_product" class="btn btn-success mt-3">Добавить товар</button>

	</form>
</div>

{literal}
<script>
	var contentSection = document.getElementById('contentSection');
	contentSection.classList.add('active');
	var contentBlock = document.getElementById('contentBlock');
	contentBlock.classList.add('show');
	var currentLink = document.getElementById('addShop');
	currentLink.classList.add('active');

	document.addEventListener("DOMContentLoaded", function() {

		const input = document.getElementById("productImages");
		const preview = document.getElementById("imagePreview");

		// Будем хранить файлы вручную
		let filesArray = [];

		input.addEventListener("change", function(event) {
			const newFiles = Array.from(event.target.files);

			// Добавляем в массив
			filesArray = filesArray.concat(newFiles);

			// Обновляем интерфейс
			renderPreview();
			syncInputFiles();
		});

		function renderPreview() {
			preview.innerHTML = "";

			filesArray.forEach((file, index) => {
				const reader = new FileReader();

				reader.onload = function(e) {
					const wrapper = document.createElement("div");
					wrapper.className = "position-relative";
					wrapper.style.width = "120px";

					wrapper.innerHTML = `
                    <img src="${e.target.result}" class="img-thumbnail" style="height:120px;object-fit:cover;">
                    <button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0"
                        data-index="${index}"
                        style="border-radius:50%;padding:2px 6px;">×</button>
                `;

					preview.appendChild(wrapper);
				};

				reader.readAsDataURL(file);
			});
		}

		// Удаление файла
		preview.addEventListener("click", function(e) {
			if (e.target.tagName === "BUTTON") {
				const index = e.target.dataset.index;
				filesArray.splice(index, 1);
				renderPreview();
				syncInputFiles();
			}
		});

		// Синхронизируем виртуальный массив файлов с реальным input
		function syncInputFiles() {
			const dataTransfer = new DataTransfer();
			filesArray.forEach(file => dataTransfer.items.add(file));
			input.files = dataTransfer.files;
		}

		const attributesContainer = document.getElementById('attributesContainer');
		const addAttributeBtn = document.getElementById('addAttribute');

		addAttributeBtn.addEventListener('click', function() {
			const index = attributesContainer.children.length;

			// создаём обёртку
			const wrapper = document.createElement('div');
			wrapper.className = 'd-flex gap-2 align-items-center';

			// input для названия
			const inputName = document.createElement('input');
			inputName.type = 'text';
			inputName.name = `attributes[${index}][name]`;
			inputName.placeholder = 'Название';
			inputName.className = 'form-control form-control-sm';
			inputName.required = true;

			// input для значения
			const inputValue = document.createElement('input');
			inputValue.type = 'text';
			inputValue.name = `attributes[${index}][value]`;
			inputValue.placeholder = 'Значение';
			inputValue.className = 'form-control form-control-sm';
			inputValue.required = true;

			// кнопка удаления
			const removeBtn = document.createElement('button');
			removeBtn.type = 'button';
			removeBtn.className = 'btn btn-sm btn-danger';
			removeBtn.textContent = '×';

			removeBtn.addEventListener('click', function() {
				wrapper.remove();
				updateAttributeIndexes();
			});

			// добавляем элементы в wrapper
			wrapper.appendChild(inputName);
			wrapper.appendChild(inputValue);
			wrapper.appendChild(removeBtn);

			// добавляем wrapper в контейнер
			attributesContainer.appendChild(wrapper);
		});

		function updateAttributeIndexes() {
			Array.from(attributesContainer.children).forEach((child, idx) => {
				const inputs = child.querySelectorAll('input');
				inputs[0].name = `attributes[${idx}][name]`;
				inputs[1].name = `attributes[${idx}][value]`;
			});
		}
	});
</script>
{/literal}