<?php
// modules/excursions/backend/routes_poi.php
// Админка: вкладка "Пункты интереса (POI)" с загрузкой аудио и фото

ini_set('display_errors',1);
error_reporting(E_ALL);
?>
<!DOCTYPE html>
<html lang="ru">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Менеджер экскурсий — Пункты интереса</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet@1.9.3/dist/leaflet.css" />
  <style>
    body, html { margin:0; padding:0; height:100%; font-family:Arial,sans-serif; }
    #map { position:relative; width:100%; height:100%; }
    #toggleSidebar { position:absolute; top:10px; right:10px; z-index:1001; padding:8px 12px; background:#fff; border:1px solid #ccc; border-radius:4px; cursor:pointer; }
    #sidebar { z-index:1000; position:fixed; bottom:0; left:0; width:100%; height:50vh; transform:translateY(100%); transition:transform .3s ease; border-top:1px solid #ccc; background:#fff; padding:10px; box-sizing:border-box; overflow-y:auto; }
    #sidebar.open { transform:translateY(0); }
    @media (min-width:768px) {
      body,html{display:flex;}
      #map{flex:2;height:auto;}
      #sidebar{position:relative;transform:translateY(0);bottom:auto;left:auto;width:300px;height:auto;border-top:none;border-left:1px solid #ccc;}
      #toggleSidebar{display:none;}
    }
    #addPoi{padding:6px 12px;margin-bottom:10px;}
    #poiList{max-height:100px;overflow-y:auto;margin-bottom:10px;}
    .poi-item{padding:6px;border:1px solid #ddd;border-radius:4px;margin-bottom:6px;}
    .poi-item.active{background:#eef;}
    .poi-item button{margin-left:5px;}
    #poiForm fieldset{margin-top:10px;border:1px solid #ccc;padding:8px;}
    #poiForm legend{font-weight:bold;}
    #poiForm label{display:block;margin:6px 0;}
    #poiForm input[type=file]{display:block;}
    #poiForm textarea{width:100%;height:60px;box-sizing:border-box;}
    #poiForm audio,#poiForm img{display:block;max-width:100%;margin-top:4px;}
    #savePoi,#cancelPoi{padding:8px 16px;margin-top:10px;margin-right:10px;cursor:pointer;}
  </style>
</head>
<body>
  <button id="toggleSidebar">Точки интереса</button>
  <div id="map"></div>
  <div id="sidebar">
    <h2>Пункты интереса</h2>
    <button id="addPoi">+ Добавить POI</button>
    <div id="poiList"></div>
    <div id="poiForm"></div>
    <button id="savePoi" disabled>Сохранить POI</button>
    <button id="cancelPoi">Отмена</button>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/leaflet@1.9.3/dist/leaflet.js"></script>
  <script>
  (async function(){
    const params = new URLSearchParams(window.location.search);
    const routeId = params.get('id');
    if(!routeId) return alert('Не указан id маршрута');

    const apiPois = '/modules/excursions/backend/api/pois.php';
    // Load languages dynamically
    const langs = await fetch('/modules/excursions/backend/api/languages.php')
                         .then(r=>r.json());

    // Initialize map
    const map = L.map('map').setView([47.7261,10.3172],13);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{maxZoom:19}).addTo(map);

    // Sidebar toggle for mobile
    const toggle = document.getElementById('toggleSidebar');
    const sidebar = document.getElementById('sidebar');
    toggle.addEventListener('click', ()=> sidebar.classList.toggle('open'));
    map.on('click', ()=> sidebar.classList.remove('open'));

    // Load and draw existing route
    const routeRes = await fetch(`/modules/excursions/backend/api/routes.php?id=${routeId}`);
    if (routeRes.ok) {
      const routeData = await routeRes.json();
      if (routeData.polyline) {
        const coords = JSON.parse(routeData.polyline).map(p=>[p[1],p[0]]);
        const poly = L.polyline(coords,{color:'blue'}).addTo(map);
        map.fitBounds(poly.getBounds());
      }
    }

    const drawnItems = new L.FeatureGroup().addTo(map);
    let currentPoi = null;

    // Load POIs from API
    async function loadPois(){
      const res = await fetch(`${apiPois}?route_id=${routeId}`);
      const pois = await res.json();
      const listEl = document.getElementById('poiList');
      listEl.innerHTML = '';
      drawnItems.clearLayers();

      pois.forEach(poi=>{
        // List item
        const div = document.createElement('div');
        div.className = 'poi-item';
        div.id = 'poi-'+poi.id;
        div.innerHTML = `
          <strong>#${poi.poi_order}</strong>
          (${poi.lat.toFixed(5)},${poi.lng.toFixed(5)})
          <button class="editBtn" data-id="${poi.id}">Редакт.</button>
          <button class="delBtn" data-id="${poi.id}">Удалить</button>
        `;
        listEl.append(div);

        // Map marker
        L.circleMarker([poi.lat,poi.lng],{radius:poi.radius/10})
         .addTo(drawnItems);

        // Edit handler
        div.querySelector('.editBtn').onclick = ()=> editPoi(poi);
        // Delete handler
        div.querySelector('.delBtn').onclick = ()=> deletePoi(poi.id);
      });
    }

    // Add new POI by map click
    document.getElementById('addPoi').onclick = ()=>{
      map.once('click', e=>{
        editPoi({
          id: null,
          poi_order: 0,
          lat: e.latlng.lat,
          lng: e.latlng.lng,
          radius: 50,
          translations: {}
        });
      });
      alert('Кликните на карте, чтобы добавить точку интереса');
    };

    // Build and show form for POI
    function editPoi(poi){
      currentPoi = poi;
      document.querySelectorAll('.poi-item').forEach(el=>el.classList.remove('active'));
      if(poi.id) document.getElementById('poi-'+poi.id).classList.add('active');

      let html = `<h3>${poi.id?'Редактировать POI #'+poi.id:'Новый POI'}</h3>`;
      html += `<label>Порядок <input id="fldOrder" type="number" value="${poi.poi_order}" /></label>`;
      html += `<label>Радиус <input id="fldRadius" type="number" value="${poi.radius}" /></label>`;
      html += `<label>Lat <input id="fldLat" type="text" value="${poi.lat}" /></label>`;
      html += `<label>Lng <input id="fldLng" type="text" value="${poi.lng}" /></label>`;

      langs.forEach(l=>{
        const tr = poi.translations[l.code] || {};
        html += `<fieldset><legend>${l.name}</legend>`;
        html += `<label>Текст<textarea id="txt_${l.code}">${tr.text||''}</textarea></label>`;
        html += `<label>Аудио <input type="file" id="audio_${l.code}" accept="audio/*" /></label>`;
        html += `<audio id="prAudio_${l.code}" controls src="${tr.audio_url||''}"></audio>`;
        html += `<label>Фото <input type="file" id="img_${l.code}" accept="image/*" /></label>`;
        html += `<img id="prImg_${l.code}" src="${tr.image_url||''}" alt="" />`;
        html += `</fieldset>`;
      });

      document.getElementById('poiForm').innerHTML = html;
      document.getElementById('savePoi').disabled = false;
      document.getElementById('cancelPoi').onclick = ()=>{
        document.getElementById('poiForm').innerHTML = '';
        document.getElementById('savePoi').disabled = true;
      };
    }

    // Save POI (create or update) via POST multipart
    document.getElementById('savePoi').onclick = async ()=>{
      const fd = new FormData();
      fd.append('route_id', routeId);
      fd.append('poi_order', document.getElementById('fldOrder').value);
      fd.append('lat', document.getElementById('fldLat').value);
      fd.append('lng', document.getElementById('fldLng').value);
      fd.append('radius', document.getElementById('fldRadius').value);

      langs.forEach(l=>{
        fd.append(`translations[${l.code}][text]`, document.getElementById(`txt_${l.code}`).value);
        const aud = document.getElementById(`audio_${l.code}`).files[0];
        if(aud) fd.append(`audio_${l.code}`, aud);
        const img = document.getElementById(`img_${l.code}`).files[0];
        if(img) fd.append(`image_${l.code}`, img);
      });

      const url = apiPois + (currentPoi.id? `?id=${currentPoi.id}` : '');
      const res = await fetch(url, { method:'POST', body: fd });
      if (res.ok) {
        loadPois();
        document.getElementById('poiForm').innerHTML = '';
        document.getElementById('savePoi').disabled = true;
      } else {
        alert('Ошибка сохранения: '+res.status);
      }
    };

    // Delete POI
    async function deletePoi(id){
      if(!confirm('Удалить точку?')) return;
      const res = await fetch(`${apiPois}?id=${id}`, { method:'DELETE' });
      if (res.status === 204) loadPois();
      else alert('Ошибка удаления: '+res.status);
    }

    // Initial load
    loadPois();
  })();
  </script>
</body>
</html>
