<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Manajemen Konten | CMS Admin SMK Teratai Putih 3</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
  <link rel="stylesheet" href="/css/admin.css">
  <style>
    .json-editor {
      width: 100%;
      height: 400px;
      font-family: monospace;
      padding: 1rem;
      border: 1px solid var(--border-color);
      border-radius: var(--radius-sm);
      resize: vertical;
    }
    .photo-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 1.5rem;
    }
    .photo-card {
      background: #fff;
      border: 1px solid var(--border-color);
      border-radius: var(--radius-md);
      padding: 1rem;
      text-align: center;
    }
    .photo-card img {
      max-width: 100%;
      height: 150px;
      object-fit: cover;
      border-radius: var(--radius-sm);
      margin-bottom: 1rem;
    }
    .tab-btn {
      padding: 0.75rem 1.25rem;
      background: transparent;
      border: none;
      border-bottom: 3px solid transparent;
      color: var(--text-muted);
      font-weight: 600;
      cursor: pointer;
      white-space: nowrap;
      transition: all 0.2s;
    }
    .tab-btn:hover {
      color: var(--primary-navy);
    }
    .tab-btn.active {
      color: var(--primary-navy);
      border-bottom-color: var(--primary-navy);
    }
  </style>
</head>
<body>

  <div class="admin-wrapper">
    <%- include('partials/admin-sidebar') %>

    <div class="admin-content">
      <%- include('partials/admin-header', { title: 'Manajemen Konten & Media' }) %>

      <main class="admin-main">
        <% if (message) { %>
          <div class="alert alert-success" style="margin-bottom: 1.5rem;">
            <%= message %>
          </div>
        <% } %>

        <div id="textAlert" class="alert alert-success" style="display: none; margin-bottom: 1.5rem;"></div>

        <div class="card" style="margin-bottom: 2rem;">
          <div class="card-header" style="display: flex; justify-content: space-between; align-items: center;">
            <h3><i class="fa-solid fa-pen-nib text-blue"></i> Edit Konten Teks Website</h3>
            <button onclick="saveAllText()" class="btn btn-primary"><i class="fa-solid fa-save"></i> Simpan Semua Teks</button>
          </div>
          <div class="card-body">
            <p class="text-muted" style="margin-bottom: 1.5rem;">Pilih halaman yang ingin diedit melalui tab di bawah ini. Cukup isi dalam **Bahasa Indonesia**, sistem akan otomatis menerjemahkannya ke Bahasa Inggris untuk pengunjung asing.</p>
            
            <div class="content-tabs" style="display: flex; gap: 1rem; margin-bottom: 1.5rem; overflow-x: auto; padding-bottom: 0px; border-bottom: 2px solid var(--border-color);">
              <button class="tab-btn active" onclick="switchTab('homepage')">Beranda & Umum</button>
              <button class="tab-btn" onclick="switchTab('profil_page')">Profil Sekolah</button>
              <button class="tab-btn" onclick="switchTab('jurusan_page')">Program Keahlian</button>
              <button class="tab-btn" onclick="switchTab('lab_page')">Fasilitas Lab</button>
              <button class="tab-btn" onclick="switchTab('berita_page')">Informasi Sekolah</button>
              <button class="tab-btn" onclick="switchTab('ppdb_page')">PPDB Online</button>
              <button class="tab-btn" onclick="switchTab('kontak_page')">Kontak Kami</button>
            </div>

            <div class="content-accordion">
              <% 
                const groups = {
                  'homepage': ['menu', 'homepage', 'footer'],
                  'profil_page': ['profil_page'],
                  'jurusan_page': ['jurusan_page'],
                  'lab_page': ['lab_page'],
                  'berita_page': ['berita_page', 'berita_detail'],
                  'ppdb_page': ['ppdb_page'],
                  'kontak_page': ['kontak_page']
                };

                function getSubMenuTitle(key, section) {
                  if (section === 'menu') {
                    if (key.startsWith('jurusan_')) return 'Sub Menu: Program Keahlian';
                    if (key.startsWith('lab_')) return 'Sub Menu: Fasilitas Lab';
                    if (key.startsWith('berita_')) return 'Sub Menu: Informasi Sekolah';
                    if (key.startsWith('ppdb_')) return 'Sub Menu: PPDB';
                    if (key.startsWith('profil_')) return 'Sub Menu: Profil';
                    return 'Menu Utama (Navigasi)';
                  }
                  if (section === 'footer') return 'Bagian: Footer & Hak Cipta';
                  
                  if (key.startsWith('major_tjkt_')) return 'Sub Menu: Jurusan TJKT';
                  if (key.startsWith('major_axioo-class_')) return 'Sub Menu: Jurusan Axioo Class';
                  if (key.startsWith('major_akl_')) return 'Sub Menu: Jurusan AKL';
                  if (key.startsWith('major_mplb_')) return 'Sub Menu: Jurusan MPLB';

                  if (key.startsWith('lab_lab-tjkt_')) return 'Sub Menu: Lab TJKT';
                  if (key.startsWith('lab_lab-axioo_')) return 'Sub Menu: Lab Axioo Class';
                  if (key.startsWith('lab_lab-akl_')) return 'Sub Menu: Lab AKL';
                  if (key.startsWith('lab_lab-mplb_')) return 'Sub Menu: Lab MPLB';

                  const parts = key.split('_');
                  if (parts.length > 0) {
                    const prefix = parts[0];
                    const map = {
                      'hero': 'Section: Hero Banner (Atas)',
                      'stats': 'Section: Statistik Singkat',
                      'profil': 'Section: Profil Singkat / Visi Misi',
                      'sambutan': 'Section: Sambutan Kepala Sekolah',
                      'jurusan': 'Section: Program Keahlian',
                      'lab': 'Section: Fasilitas Laboratorium',
                      'review': 'Section: Ulasan Google',
                      'news': 'Section: Berita Terbaru',
                      'cta': 'Section: Panggilan Bertindak (CTA)',
                      'form': 'Section: Formulir Isian',
                      'brochure': 'Section: Brosur & Syarat',
                      'req': 'Section: Persyaratan',
                      'info': 'Section: Info Kontak',
                      'addr': 'Section: Alamat Sekolah',
                      'wa': 'Section: Kontak WhatsApp',
                      'tel': 'Section: Telepon',
                      'search': 'Section: Kolom Pencarian',
                      'filter': 'Section: Filter Kategori',
                      'no': 'Section: Pesan Data Kosong',
                      'back': 'Section: Navigasi Halaman',
                      'related': 'Section: Konten Terkait',
                      'read': 'Section: Tombol Baca',
                      'capacity': 'Section: Kapasitas Ruangan',
                      'conn': 'Section: Konektivitas',
                      'hw': 'Section: Hardware',
                      'sw': 'Section: Software',
                      'all': 'Section: Tautan Umum',
                      'axioo': 'Section: Kelas Industri Axioo',
                      'gender': 'Section: Pilihan Jenis Kelamin',
                      'major': 'Section: Pilihan Jurusan'
                    };
                    return map[prefix] || 'Section: ' + prefix.charAt(0).toUpperCase() + prefix.slice(1);
                  }
                  return 'Section: Umum';
                }

                function formatLabel(key) {
                  return key.split('_').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');
                }

                const photoMap = {
                  'Section: Hero Banner (Atas)': [
                    { key: 'hero_slider_1', label: 'Foto Slider 1 (Beranda)' },
                    { key: 'hero_slider_2', label: 'Foto Slider 2 (Beranda)' },
                    { key: 'hero_slider_3', label: 'Foto Slider 3 (Beranda)' },
                    { key: 'hero_slider_4', label: 'Foto Slider 4 (Beranda)' }
                  ],
                  'Section: Sambutan Kepala Sekolah': [{ key: 'profil_kepsek', label: 'Foto Kepala Sekolah' }],
                  'Section: Profil Singkat / Visi Misi': [{ key: 'profil_gedung', label: 'Foto Gedung/Profil' }],
                  'Sub Menu: Lab TJKT': [{ key: 'lab_tjkt', label: 'Foto Fasilitas Lab TJKT' }],
                  'Sub Menu: Lab Axioo Class': [{ key: 'lab_axioo', label: 'Foto Fasilitas Lab Axioo Class' }],
                  'Sub Menu: Lab AKL': [{ key: 'lab_akl', label: 'Foto Fasilitas Lab AKL' }],
                  'Sub Menu: Lab MPLB': [{ key: 'lab_mplb', label: 'Foto Fasilitas Lab MPLB' }]
                };
              %>

              <% Object.keys(groups).forEach(groupId => { %>
                <div id="tab-<%= groupId %>" class="tab-content" style="<%= groupId === 'homepage' ? 'display: block;' : 'display: none;' %>">
                  <% 
                    const tabGroupedKeys = {};
                    groups[groupId].forEach(section => {
                      if (idLocale[section]) {
                        Object.keys(idLocale[section]).forEach(key => {
                          const subMenu = getSubMenuTitle(key, section);
                          if (!tabGroupedKeys[subMenu]) tabGroupedKeys[subMenu] = [];
                          tabGroupedKeys[subMenu].push({ key, section });
                        });
                      }
                    });
                    const subMenuKeys = Object.keys(tabGroupedKeys);
                  %>

                  <% if (subMenuKeys.length > 1) { %>
                    <div style="margin-bottom: 1.5rem; background: var(--bg-slate); padding: 1rem; border-radius: var(--radius-md); border-left: 4px solid var(--accent-gold);">
                      <label style="font-weight: 700; color: var(--primary-navy); margin-bottom: 0.5rem; display: block; font-size: 0.95rem;">
                        <i class="fa-solid fa-filter text-gold" style="margin-right: 0.35rem;"></i> Pilih Bagian / Sub Menu yang Ingin Diedit:
                      </label>
                      <select class="submenu-dropdown" onchange="filterSubMenu('<%= groupId %>', this.value)" style="width: 100%; padding: 0.75rem; border-radius: 6px; border: 1px solid #cbd5e1; font-family: 'Plus Jakarta Sans', sans-serif; font-size: 1rem; background: #fff; cursor: pointer;">
                        <% subMenuKeys.forEach((subMenu, idx) => { %>
                          <option value="<%= idx %>"><%= subMenu %></option>
                        <% }) %>
                      </select>
                    </div>
                  <% } %>

                  <% subMenuKeys.forEach((subMenu, idx) => { %>
                    <div class="submenu-group-<%= groupId %>" id="submenu-group-<%= groupId %>-<%= idx %>" style="<%= (subMenuKeys.length > 1 && idx !== 0) ? 'display: none;' : 'display: block;' %> margin-bottom: 2rem; border: 1px solid var(--border-color); border-radius: var(--radius-md); overflow: hidden; box-shadow: var(--shadow-sm);">
                      <div style="background: linear-gradient(to right, rgba(15, 44, 89, 0.08), transparent); padding: 1rem 1.5rem; border-bottom: 2px solid var(--primary-navy);">
                        <h4 style="margin: 0; color: var(--primary-navy); font-size: 1.05rem; font-weight: 700;">
                          <i class="fa-solid fa-layer-group text-gold" style="margin-right: 0.5rem;"></i> <%= subMenu %>
                        </h4>
                      </div>
                      <div style="padding: 1.5rem; background: #fff;">
                        <% if (photoMap[subMenu]) { %>
                          <div style="margin-bottom: 2rem; padding: 1.5rem; background: rgba(15, 44, 89, 0.03); border: 1px solid rgba(15, 44, 89, 0.1); border-radius: 8px;">
                            <h5 style="margin-top: 0; margin-bottom: 1rem; color: var(--primary-navy); font-weight: 700;"><i class="fa-solid fa-image text-gold"></i> Kelola Foto Bagian Ini</h5>
                            <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 1.5rem;">
                              <% photoMap[subMenu].forEach(photoInfo => { %>
                                <div style="background: #fff; padding: 1rem; border-radius: 6px; box-shadow: var(--shadow-sm); border: 1px solid var(--border-color);">
                                  <span style="display: block; font-size: 0.9rem; font-weight: 600; margin-bottom: 0.5rem;"><%= photoInfo.label %></span>
                                  <img src="<%= settings.images && settings.images[photoInfo.key] ? settings.images[photoInfo.key] : 'https://images.unsplash.com/photo-1524178232363-1fb2b075b655?auto=format&fit=crop&w=600&q=80' %>" alt="<%= photoInfo.label %>" style="width: 100%; height: 140px; object-fit: cover; border-radius: 4px; margin-bottom: 1rem; border: 1px solid #e2e8f0;">
                                  <form action="/admin/content/photo" method="POST" enctype="multipart/form-data">
                                    <input type="hidden" name="imageKey" value="<%= photoInfo.key %>">
                                    <input type="file" name="photoFile" accept="image/*" required style="width: 100%; font-size: 0.8rem; margin-bottom: 0.5rem;">
                                    <button type="submit" class="btn btn-primary" style="width: 100%; padding: 0.4rem; font-size: 0.85rem;"><i class="fa-solid fa-upload"></i> Unggah & Ganti Foto</button>
                                  </form>
                                </div>
                              <% }) %>
                            </div>
                          </div>
                        <% } %>

                        <% tabGroupedKeys[subMenu].forEach(item => { %>
                          <div style="margin-bottom: 1.25rem; padding-bottom: 1.25rem; border-bottom: 1px dashed #e2e8f0;">
                            <div style="display: block;">
                              <label style="font-size: 0.95rem; font-weight: 700; color: #1e293b; margin-bottom: 0.5rem; display: flex; align-items: center; justify-content: space-between;">
                                <span><%= formatLabel(item.key) %></span>
                                <span style="font-size: 0.75rem; color: #94a3b8; font-family: monospace; font-weight: 400; background: #f1f5f9; padding: 0.2rem 0.5rem; border-radius: 4px;">Key: <%= item.section %>.<%= item.key %></span>
                              </label>
                              <textarea 
                                class="content-input-id" 
                                data-section="<%= item.section %>" 
                                data-key="<%= item.key %>" 
                                rows="<%= idLocale[item.section][item.key].length > 80 ? 3 : 1 %>"
                                style="width: 100%; padding: 0.85rem; border-radius: 6px; border: 1px solid #cbd5e1; resize: vertical; font-family: 'Plus Jakarta Sans', sans-serif; font-size: 0.95rem; line-height: 1.6; background: #f8fafc;"
                              ><%= idLocale[item.section][item.key] %></textarea>
                            </div>
                          </div>
                        <% }) %>
                      </div>
                    </div>
                  <% }) %>
                </div>
              <% }) %>
            </div>

            <div class="text-right" style="margin-top: 1.5rem; text-align: right;">
              <button onclick="saveAllText()" class="btn btn-primary"><i class="fa-solid fa-save"></i> Simpan Semua Teks</button>
            </div>
          </div>
        </div>

          </div>
        </div>

      </main>
    </div>
  </div>

  <script>
    function switchTab(tabId) {
      document.querySelectorAll('.tab-content').forEach(el => el.style.display = 'none');
      document.querySelectorAll('.tab-btn').forEach(el => el.classList.remove('active'));
      document.getElementById('tab-' + tabId).style.display = 'block';
      event.currentTarget.classList.add('active');
    }

    function filterSubMenu(groupId, selectedIdx) {
      const groups = document.querySelectorAll('.submenu-group-' + groupId);
      groups.forEach(group => {
        group.style.display = 'none';
      });
      const activeGroup = document.getElementById('submenu-group-' + groupId + '-' + selectedIdx);
      if (activeGroup) {
        activeGroup.style.display = 'block';
      }
    }

    async function saveAllText() {
      const idData = {};
      const alertBox = document.getElementById('textAlert');
      const btn = event.currentTarget;
      const originalText = btn.innerHTML;
      btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Menyimpan & Menerjemahkan (Mohon Tunggu)...';
      btn.disabled = true;
      
      // Gather ID data
      document.querySelectorAll('.content-input-id').forEach(input => {
        const section = input.getAttribute('data-section');
        const key = input.getAttribute('data-key');
        if(!idData[section]) idData[section] = {};
        idData[section][key] = input.value;
      });

      try {
        // Send ID (backend will auto translate and save EN)
        let resId = await fetch('/admin/content/text', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ lang: 'id', data: JSON.stringify(idData) })
        });
        let resultId = await resId.json();
        if (!resultId.success) throw new Error(resultId.message);

        alertBox.innerHTML = '<i class="fa-solid fa-check-circle"></i> Berhasil menyimpan dan menerjemahkan seluruh teks konten!';
        alertBox.style.display = 'block';
        alertBox.className = 'alert alert-success';
        
        // Scroll to top to see alert
        window.scrollTo({ top: 0, behavior: 'smooth' });

      } catch (err) {
        alertBox.innerHTML = '<i class="fa-solid fa-triangle-exclamation"></i> Gagal menyimpan: ' + err.message;
        alertBox.style.display = 'block';
        alertBox.className = 'alert alert-danger';
        window.scrollTo({ top: 0, behavior: 'smooth' });
      }
      
      btn.innerHTML = originalText;
      btn.disabled = false;
      
      setTimeout(() => { alertBox.style.display = 'none'; }, 5000);
    }
  </script>
</body>
</html>
