{if $access['modules.update'] || $user.name == 'Demo profile'}

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

	{if isset($error_message) && $error_message}
		<div class="col-12">
			<div class="alert alert-danger">{$error_message}</div>
		</div>
	{/if}

	<div class="col-12">
		<form method="POST" action="/admin?action=modules/shops/edit"  enctype="multipart/form-data">

			<div class="row">
				<div class="col-12">

					<ul class="nav nav-tabs mb-2">
						<li class="nav-item">
							<button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tab-main" type="button">
								Основное
							</button>
						</li>

						<li class="nav-item">
							<button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-seo" type="button">
								SEO
							</button>
						</li>
					</ul>

					<div class="tab-content">

						<!-- ОСНОВНОЕ -->
						<div class="tab-pane fade active show" id="tab-main">
							<div class="row">
								<div class="col-6">

									<div class="mb-3">
										<label class="form-label">Название магазина *</label>
										<input type="text" name="shop_name" class="form-control" required value="{$page.shop_name}">
									</div>

									<div class="mb-3">
										<label class="form-label">Slug *</label>
										<input type="text" name="slug" class="form-control" required value="{$page.slug}">
									</div>

									<div class="mb-3">
										<label class="form-label">Локация магазина</label>

										<div id="map" style="height: 300px; border-radius: 8px; border: 1px solid #ddd;"></div>

										<input type="hidden" name="location_lat" id="location_lat" value="{$page.lat}">
										<input type="hidden" name="location_lng" id="location_lng" value="{$page.lng}">

										<small class="text-muted">Кликни по карте — координаты обновятся</small>
									</div>

									<div class="mb-3">
										<label class="form-label">Адрес</label>
										<input type="text" name="location_address" id="location_address" class="form-control" readonly value="{$page.location}">
									</div>

								</div>

								<div class="col-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>


									<div class="col-12 mt-3">
										<h6>Изображения магазина:</h6>
										<input type="file" id="shop_images" name="shop_images[]" multiple accept="image/*" class="form-control mb-2">
										<div id="images_preview" class="d-flex flex-wrap gap-2">
											{foreach from=$page.shop_images key=idx item=image}
												<div class="image-card {if $image.is_main}main{/if}" data-index="{$idx}" data-existing="1" data-id="{$image.id}">
													<img src="{$image.url}">
													<button type="button" class="delete-btn">&times;</button>
													{if $image.is_main}<div class="main-label">Main</div>{/if}
												</div>
											{/foreach}
										</div>
									</div>


									<div class="col-12 mt-3">
										<h6>Видео магазина:</h6>
										<input type="file" id="shop_videos" name="shop_videos[]" multiple accept="video/*" class="form-control mb-2">
										<div id="videos_preview" class="d-flex flex-wrap gap-2">
											{foreach from=$page.shop_videos key=idxv item=video}
												<div class="video-card" data-index="{$idxv}" data-existing="1" data-id="{$video.id}">
													<img src="{$video.thumb}">
													<button type="button" class="delete-btn">&times;</button>
{*
													{if $image.is_main}<div class="main-label">Main</div>{/if}
*}
												</div>
											{/foreach}
										</div>
									</div>
									<input type="hidden" name="is_main_image" id="is_main_image_input" value="">
									<input type="hidden" name="deleted_images" id="deleted_images_input">
									<input type="hidden" name="deleted_videos" id="deleted_videos_input">
								</div>
							</div>
						</div>

						<!-- SEO -->
						<div class="tab-pane fade" id="tab-seo">

							<fieldset class="form-icon-group left-icon position-relative">
								<input type="text" name="meta_keys" class="form-control mt-2 mb-2" value="" placeholder="Meta keywords">
								<div class="form-icon position-absolute"><svg ...></svg></div>
							</fieldset>

							<fieldset class="form-icon-group left-icon position-relative">
								<input type="text" name="meta_desc" class="form-control mt-2 mb-2" value="" placeholder="Meta description">
								<div class="form-icon position-absolute"><svg ...></svg></div>
							</fieldset>

						</div>

					</div>

				</div>

				<!-- Описание -->
				<div class="col-12">
					<h6 class="mt-2">Описание:</h6>
					<textarea id="short_desc" name="description">{$page.description}</textarea>
				</div>

				<!-- Доп-поля -->
				<div class="row">
					{foreach from=$fields item=field key=index}
						<div class="col-12 col-md-4 mt-3">
							<label>{$lang.fields.coupons[$index]}</label>
							<input type="text" class="form-control" name="x_value[{$index}]" value="{$field}">
							<input type="hidden" name="field_ids[]" value="{$index}">
						</div>
					{/foreach}
				</div>

				<div class="col-3">
					<button type="submit" name="editshop" class="btn btn-primary mt-2 mb-2">
						Сохранить
					</button>
				</div>

				<input type="hidden" name="page_id" value="{$page.shop_id}">
			</div>

		</form>
	</div>
	<style>
		.image-card {
			position: relative;
			width: 120px;
			height: 120px;
			border-radius: 10px;
			overflow: hidden;
			border: 2px solid transparent;
			box-shadow: 0 2px 6px rgba(0,0,0,0.15);
			cursor: pointer;
			transition: transform 0.2s, border-color 0.2s;
		}
		.image-card:hover { transform: scale(1.05); }
		.image-card img { width: 100%; height: 100%; object-fit: cover; }
		.image-card .delete-btn {
			position: absolute; top: 5px; right: 5px;
			background: rgba(255,0,0,0.8); border:none; color:white; border-radius:50%;
			width:22px; height:22px; font-weight:bold; line-height:18px;
		}
		.image-card .main-label {
			position: absolute; bottom:5px; left:50%; transform:translateX(-50%);
			background: rgba(0,123,255,0.8); color:white; padding:2px 6px; font-size:12px; border-radius:4px;
		}
		.image-card.main { border-color:#007bff; }

		.video-card {
			position: relative;
			width: 120px;
			height: 120px;
			border-radius: 10px;
			overflow: hidden;
			border: 2px solid transparent;
			box-shadow: 0 2px 6px rgba(0,0,0,0.15);
			cursor: pointer;
			transition: transform 0.2s, border-color 0.2s;
		}
		.video-card:hover { transform: scale(1.05); }
		.video-card img { width: 100%; height: 100%; object-fit: cover; }
		.video-card .delete-btn {
			position: absolute; top: 5px; right: 5px;
			background: rgba(255,0,0,0.8); border:none; color:white; border-radius:50%;
			width:22px; height:22px; font-weight:bold; line-height:18px;
		}
		.video-card .main-label {
			position: absolute; bottom:5px; left:50%; transform:translateX(-50%);
			background: rgba(0,123,255,0.8); color:white; padding:2px 6px; font-size:12px; border-radius:4px;
		}
		.video-card.main { border-color:#007bff; }
	</style>

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

		let lat = parseFloat(document.getElementById("location_lat").value) || 40.1772;
		let lng = parseFloat(document.getElementById("location_lng").value) || 44.50349;

		let map = L.map('map').setView([lat, lng], 14);
		let marker = L.marker([lat, lng]).addTo(map);

		L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
			maxZoom: 19,
		}).addTo(map);

		map.on('click', async function (e) {
			const lat = e.latlng.lat;
			const lng = e.latlng.lng;

			document.getElementById("location_lat").value = lat;
			document.getElementById("location_lng").value = lng;

			marker.setLatLng(e.latlng);

			const url =
					`https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lng}&accept-language=ru`;

			try {
				const response = await fetch(url, {
					headers: { "User-Agent": "YourAppName/1.0" }
				});
				const data = await response.json();

				if (data && data.display_name) {
					document.getElementById("location_address").value = data.display_name;
				} else {
					document.getElementById("location_address").value = "Адрес не найден";
				}

			} catch (err) {
				document.getElementById("location_address").value = "Ошибка получения адреса";
			}
		});
		document.addEventListener('DOMContentLoaded', () => {

			const videosInput = document.getElementById('shop_videos');
			const videosPreview = document.getElementById('videos_preview');
		/*	const deletedVideosInput = document.createElement('input');
			deletedVideosInput.type = 'hidden';
			deletedVideosInput.name = 'deleted_videos';
			deletedVideosInput.id = 'deleted_videos_input';
			document.querySelector('form').appendChild(deletedVideosInput);*/

			let existingVideos = Array.from(document.querySelectorAll('.video-card[data-existing="1"]'));
			let newVideos = [];
			let deletedVideos = [];

			function updateHiddenVideos() {
				$("#deleted_videos_input").val(deletedVideos.join(','));
			}

			function renderNewVideos() {
				newVideos.forEach((file, idx) => {
					const reader = new FileReader();
					reader.onload = e => {
						const div = document.createElement('div');
						div.className = 'video-card';
						div.dataset.index = existingVideos.length + idx;
						div.innerHTML = `
                    <img src="${e.target.result}">
                    <button type="button" class="delete-btn">&times;</button>
                `;

						// Удаление новой видео
						div.querySelector('.delete-btn').addEventListener('click', ev => {
							ev.stopPropagation();
							newVideos.splice(idx, 1);
							div.remove();
						});

						videosPreview.appendChild(div);
					};
					reader.readAsDataURL(file);
				});
			}

			function renderAllVideos() {
				videosPreview.innerHTML = '';

				// Существующие видео
				existingVideos.forEach((div) => {
					if (!deletedVideos.includes(div.dataset.id)) {
						const clone = div.cloneNode(true);

						clone.querySelector('.delete-btn').addEventListener('click', ev => {
							ev.stopPropagation();
							deletedVideos.push(clone.dataset.id);
							clone.remove();
							updateHiddenVideos();
						});

						videosPreview.appendChild(clone);
					}
				});

				renderNewVideos();
				updateHiddenVideos();
			}

			// Добавление новых видео
			videosInput.addEventListener('change', e => {
				newVideos.push(...Array.from(e.target.files));
				renderAllVideos();
			});

			// Первичный рендер
			renderAllVideos();


			const imagesInput = document.getElementById('shop_images');
			const imagesPreview = document.getElementById('images_preview');
			const deletedInput = document.getElementById('deleted_images_input');
			const mainInput = document.getElementById('is_main_image_input');

			let existingImages = Array.from(document.querySelectorAll('.image-card[data-existing="1"]'));
			let newImages = [];
			let deletedImages = [];
			let mainIndex = existingImages.findIndex(img => img.classList.contains('main'));
			if(mainIndex === -1) mainIndex = 0;

			function updateHiddenInputs() {
				deletedInput.value = deletedImages.join(',');
				mainInput.value = mainIndex;
			}

			function updateMainLabels() {
				document.querySelectorAll('.image-card').forEach((card, idx) => {
					card.classList.toggle('main', idx === mainIndex);
				});
				updateHiddenInputs();
			}

			function renderNewImages() {
				newImages.forEach((file, idx) => {
					const reader = new FileReader();
					reader.onload = e => {
						const div = document.createElement('div');
						div.className = 'image-card' + ((existingImages.length + idx) === mainIndex ? ' main' : '');
						div.dataset.index = existingImages.length + idx;
						div.innerHTML = `
                    <img src="${e.target.result}">
                    <button type="button" class="delete-btn">&times;</button>
                `;

						// Удаление новой картинки
						div.querySelector('.delete-btn').addEventListener('click', ev => {
							ev.stopPropagation();
							newImages.splice(idx, 1);
							div.remove();
							if(mainIndex >= existingImages.length + newImages.length) mainIndex = 0;
							updateMainLabels();
						});

						// Выбор главной картинки
						div.addEventListener('click', ev => {
							if(!ev.target.classList.contains('delete-btn')){
								mainIndex = parseInt(div.dataset.index);
								updateMainLabels();
							}
						});

						imagesPreview.appendChild(div);
					};
					reader.readAsDataURL(file);
				});
			}

			function renderAll() {
				imagesPreview.innerHTML = '';

				// Существующие
				existingImages.forEach((div, idx) => {
					if(!deletedImages.includes(div.dataset.id)){
						const clone = div.cloneNode(true);
						clone.dataset.index = idx;
						clone.classList.toggle('main', idx === mainIndex);

						clone.querySelector('.delete-btn').addEventListener('click', ev => {
							ev.stopPropagation();
							deletedImages.push(clone.dataset.id);
							clone.remove();
							if(mainIndex === idx) mainIndex = 0;
							updateHiddenInputs();
						});

						clone.addEventListener('click', ev => {
							if(!ev.target.classList.contains('delete-btn')){
								mainIndex = parseInt(clone.dataset.index);
								updateMainLabels();
							}
						});

						imagesPreview.appendChild(clone);
					}
				});

				renderNewImages();
				updateHiddenInputs();
			}

			// Обработка выбора новых файлов
			imagesInput.addEventListener('change', e => {
				newImages.push(...Array.from(e.target.files));
				renderAll();
			});

			// Обновление при submit (на всякий случай)
			const form = document.querySelector('form');
			form.addEventListener('submit', () => {
				updateHiddenInputs();
			});

			// Первичный рендер
			renderAll();
		});


	</script>
{/literal}

{/if}
