<?php include('protect.php'); ?>
<!DOCTYPE html>
<html lang="sq">
<head>
  <meta charset="UTF-8">
  <title>Menu Admin – Belvedere</title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <style>
    body { font-family: sans-serif; margin: 20px; background: #f9f9f9; }
    h1 { text-align: center; }
    .category {
      background: #fff;
      border: 1px solid #ccc;
      border-radius: 6px;
      margin-bottom: 10px;
      padding: 10px;
      box-shadow: 0 1px 4px rgba(0,0,0,0.06);
    }
    .cat-header {
      background: #8B0000;
      color: #fff;
      padding: 10px;
      cursor: pointer;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-radius: 6px 6px 0 0;
    }
    .cat-content { padding: 10px; }
    .collapsed .cat-content { display: none; }
    .item {
      background: #f6f6f6;
      padding: 10px;
      margin-top: 10px;
      border-radius: 4px;
      border: 1px solid #ddd;
    }
    input, textarea {
      width: 100%;
      margin: 5px 0;
      padding: 6px;
      font-size: 14px;
    }
    button {
      padding: 6px 10px;
      margin: 4px 2px;
      cursor: pointer;
    }
    .preview {
      width: 90px;
      height: 90px;
      object-fit: cover;
      border-radius: 4px;
      margin-top: 5px;
    }
  </style>
</head>
<body>
    <a href="logout.php" style="position:absolute; top:10px; right:10px; background:#dc3545; color:#fff; padding:8px 12px; border-radius:6px; text-decoration:none;">🔒 Dil</a>

  <h1>🍽️ Menu Admin – Belvedere</h1>
  <div id="menu-editor"></div>

  <div style="text-align:center; margin-top: 20px;">
    <button onclick="addCategory()">+ Shto Kategori</button>
    <button onclick="saveToServer()">💾 Ruaj Menunë</button>
    <button onclick="backupMenu()">⬇️ Backup</button>
    <button onclick="document.getElementById('importInput').click()">⬆️ Importo</button>
    <input type="file" id="importInput" accept="application/json" style="display:none" onchange="importBackup(event)">
  </div>

  <script>
    let menuData = [];
    let metaData = { wifi: '' };

    async function loadMenu() {
      const res = await fetch('menus/belvedere.json?_=' + Date.now());
      const data = await res.json();
      menuData = Array.isArray(data) ? data : data.menu || [];
      metaData = data.meta || { wifi: '' };
      render();
    }

    function render() {
      const editor = document.getElementById('menu-editor');
      editor.innerHTML = '';

      menuData.forEach((cat, cIndex) => {
        const container = document.createElement('div');
        container.className = 'category';
        container.dataset.catId = cat.id;

        const header = document.createElement('div');
        header.className = 'cat-header';
        header.innerHTML = `<span>📂 ${cat.title.sq || 'Kategori ' + (cIndex+1)}</span><span>↕</span>`;
        header.onclick = () => container.classList.toggle('collapsed');
        container.appendChild(header);

        const content = document.createElement('div');
        content.className = 'cat-content';
        content.innerHTML = `
          <input placeholder="Titulli (sq)" value="${cat.title.sq || ''}" oninput="menuData[${cIndex}].title.sq=this.value">
          <input placeholder="Titulli (en)" value="${cat.title.en || ''}" oninput="menuData[${cIndex}].title.en=this.value">
          <input placeholder="Titulli (mk)" value="${cat.title.mk || ''}" oninput="menuData[${cIndex}].title.mk=this.value">
          <button onclick="addItem('${cat.id}')">➕ Shto Produkt</button>
          <button onclick="deleteCategory('${cat.id}')">🗑️ Fshi Kategori</button>`;

        cat.items = cat.items || [];
        cat.items.forEach((item, i) => {
          const itemDiv = document.createElement('div');
          itemDiv.className = 'item';
          itemDiv.innerHTML = `
            <input placeholder="Emri (sq)" value="${item.name.sq || ''}" oninput="menuData[${cIndex}].items[${i}].name.sq=this.value">
            <input placeholder="Emri (en)" value="${item.name.en || ''}" oninput="menuData[${cIndex}].items[${i}].name.en=this.value">
            <input placeholder="Emri (mk)" value="${item.name.mk || ''}" oninput="menuData[${cIndex}].items[${i}].name.mk=this.value">
            <textarea placeholder="Përshkrimi (sq)" oninput="menuData[${cIndex}].items[${i}].desc.sq=this.value">${item.desc.sq || ''}</textarea>
            <textarea placeholder="Përshkrimi (en)" oninput="menuData[${cIndex}].items[${i}].desc.en=this.value">${item.desc.en || ''}</textarea>
            <textarea placeholder="Përshkrimi (mk)" oninput="menuData[${cIndex}].items[${i}].desc.mk=this.value">${item.desc.mk || ''}</textarea>
            <input placeholder="Çmimi" value="${item.price || ''}" oninput="menuData[${cIndex}].items[${i}].price=this.value">
            ${item.image ? `<img src="images/belvedere/${item.image}" class="preview"><br>` : ''}
            <input type="file" onchange="uploadImage(event, '${cat.id}', ${i})">
            <button onclick="deleteItem('${cat.id}', ${i})">❌ Fshi Produkt</button>`;
          content.appendChild(itemDiv);
        });

        container.appendChild(content);
        editor.appendChild(container);
      });
    }

    function addCategory() {
      menuData.push({
        id: 'cat' + Date.now(),
        title: { sq: '', en: '', mk: '' },
        items: []
      });
      render();
    }

    function addItem(catId) {
      const cat = menuData.find(c => c.id === catId);
      if (cat) {
        cat.items.push({
          name: { sq: '', en: '', mk: '' },
          desc: { sq: '', en: '', mk: '' },
          price: '',
          image: ''
        });
        render();
      }
    }

    function deleteCategory(catId) {
      menuData = menuData.filter(c => c.id !== catId);
      render();
    }

    function deleteItem(catId, index) {
      const cat = menuData.find(c => c.id === catId);
      if (cat) {
        cat.items.splice(index, 1);
        render();
      }
    }

    function uploadImage(event, catId, index) {
      const file = event.target.files[0];
      if (!file) return;
      const filename = Date.now() + '-' + file.name;
      const formData = new FormData();
      formData.append("file", file);
      fetch(`upload-image.php?rid=belvedere&filename=${filename}`, {
        method: "POST",
        body: formData
      }).then(res => {
        if (res.ok) {
          const cat = menuData.find(c => c.id === catId);
          cat.items[index].image = filename;
          render();
        } else {
          alert("❌ Ngarkimi i fotos dështoi.");
        }
      });
    }

    function saveToServer() {
      fetch('save-menu.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: 'belvedere', menu: menuData, meta: metaData })
      }).then(res => {
        alert(res.ok ? "✅ Menu u ruajt." : "❌ Gabim gjatë ruajtjes.");
      });
    }

    function backupMenu() {
      const blob = new Blob([JSON.stringify({ menu: menuData, meta: metaData }, null, 2)], { type: 'application/json' });
      const a = document.createElement('a');
      a.href = URL.createObjectURL(blob);
      a.download = 'menu-backup.json';
      a.click();
    }

    function importBackup(event) {
      const file = event.target.files[0];
      if (!file) return;
      const reader = new FileReader();
      reader.onload = function(e) {
        try {
          const imported = JSON.parse(e.target.result);
          menuData = imported.menu || [];
          metaData = imported.meta || { wifi: '' };
          render();
        } catch {
          alert("❌ Formati i backup-it nuk është valid.");
        }
      };
      reader.readAsText(file);
    }

    loadMenu();
  </script>
</body>
</html>