<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 value="{$product.name|escape}">
						</div>

						<div class="mb-3">
							<label class="form-label">Slug (URL) *</label>
							<input type="text" name="slug" class="form-control" required value="{$product.slug|escape}">
						</div>

						<div class="mb-3">
							<label class="form-label">Цена *</label>
							<input type="number" step="0.01" name="price" class="form-control" required value="{$product.price|default:0}">
						</div>

						<div class="mb-3">
							<label class="form-label">Количество на складе</label>
							<input type="number" name="stock" class="form-control" value="{$product.stock|default:0}">
						</div>

						<div class="form-check form-switch mb-3">
							<input class="form-check-input" type="checkbox" name="is_active" {if $product.is_active|default:1}checked{/if}>
							<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 disabled value="">- Категория -</option>
							{foreach from=$categories item=category}
								{if $category.parentid == 0}
									<option value="{$category.id}" style="font-weight: bold;"
											{if in_array($category.id, $selectedCategories)}selected{/if}>
										{$category.name}
									</option>
									{foreach from=$categories item=subcategory}
										{if $subcategory.parentid == $category.id}
											<option value="{$subcategory.id}"
													{if in_array($subcategory.id, $selectedCategories)}selected{/if}>
												{$subcategory.name}
											</option>
										{/if}
									{/foreach}
								{/if}
							{/foreach}
						</select>

						<label class="form-label">Описание</label>
						<textarea name="description" class="form-control" rows="8">{$product.description|escape}</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">
						{if $product_images}
							{foreach $product_images as $img}
								<div class="position-relative" style="width:120px;">
									<img src="{$img.url}" class="img-thumbnail" style="height:120px;object-fit:cover;">
									<button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0 remove-existing-image"
											data-id="{$img.id}" style="border-radius:50%;padding:2px 6px;">×</button>
								</div>
							{/foreach}
						{/if}
					</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">
					{if !empty($product.attributes)}
						{foreach from=$product.attributes item=attr name=attrLoop}
							<div class="d-flex gap-2 align-items-center">
								<input type="hidden" name="attributes[{$index}][id]" value="{$attr.id}">
								<input type="text" name="attributes[{$smarty.foreach.attrLoop.index}][name]" value="{$attr.name}" placeholder="Название" class="form-control form-control-sm" required>
								<input type="text" name="attributes[{$smarty.foreach.attrLoop.index}][value]" value="{$attr.value}" placeholder="Значение" class="form-control form-control-sm" required>
								<button type="button" class="btn btn-sm btn-danger remove-attribute">×</button>
							</div>
						{/foreach}
					{/if}
				</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" value="{$product.meta_keys|escape}">
				</div>
				<div class="mb-3">
					<input type="text" name="meta_desc" class="form-control" placeholder="Meta description" value="{$product.meta_desc|escape}">
				</div>
			</div>

		</div>

		<input type="hidden" name="shop_id" value="{$shop.shop_id}">
		{if $product.product_id}
			<input type="hidden" name="product_id" value="{$product.product_id}">
		{/if}

		<button type="submit" name="save_shop_product" class="btn btn-success mt-3">
			{if $product.id}Сохранить изменения{else}Добавить товар{/if}
		</button>

	</form>
</div>

{literal}
	<script>
		document.addEventListener("DOMContentLoaded", function() {
			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');

			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() {
				// Удаляем только новые файлы, существующие изображения оставляем
				const existingImages = preview.querySelectorAll(".existing-image");
				preview.innerHTML = "";
				existingImages.forEach(img => preview.appendChild(img));

				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") {
					if (e.target.classList.contains("remove-existing-image")) {
						const imgId = e.target.dataset.id;
						fetch("/admin/ajax_delete_image.php", {
							method: "POST",
							headers: { "Content-Type": "application/x-www-form-urlencoded" },
							body: "image_id=" + imgId
						}).then(res => res.text()).then(() => {
							e.target.parentNode.remove();
						});
					} else {
						const index = e.target.dataset.index;
						filesArray.splice(index, 1);
						renderPreview();
						syncInputFiles();
					}
				}
			});

			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';

				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;

				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();
				});

				wrapper.appendChild(inputName);
				wrapper.appendChild(inputValue);
				wrapper.appendChild(removeBtn);

				attributesContainer.appendChild(wrapper);
			});

			// Удаление существующих атрибутов
			attributesContainer.addEventListener('click', function(e) {
				if (e.target.classList.contains('remove-attribute')) {
					e.target.parentElement.remove();
				}
			});

		});

	</script>
{/literal}
