<?php
// admin/menu.php - Menu management for public navigation
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';

$db = get_db();

// Default menu items
$default_nav = [
  ['label'=>'Beranda','href'=>base_url() . '/public/index.php'],
  ['label'=>'Tentang','href'=>base_url() . '/public/about.php'],
  ['label'=>'Siswa','href'=>base_url() . '/public/students.php'],
  ['label'=>'Guru','href'=>base_url() . '/public/teachers.php'],
  ['label'=>'Berita','href'=>base_url() . '/public/berita.php'],
  ['label'=>'Download','href'=>base_url() . '/public/download.php'],
  ['label'=>'Admin','href'=>base_url() . '/admin/login.php','class'=>'btn btn-sm btn-outline-primary ms-2']
];

// Load current nav from settings
$nav_json = get_setting('nav_items', '');
$nav_items = [];
if ($nav_json) {
  $decoded = json_decode($nav_json, true);
  if (is_array($decoded)) $nav_items = $decoded;
}
if (empty($nav_items)) $nav_items = $default_nav;

// Handle save
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $labels = $_POST['label'] ?? [];
  $hrefs = $_POST['href'] ?? [];
  $classes = $_POST['class'] ?? [];
  $icons = $_POST['icon'] ?? [];
  $new_nav = [];
  foreach ($labels as $i => $label) {
    $label = trim($label);
    $href = trim($hrefs[$i] ?? '');
    $class = trim($classes[$i] ?? '');
    $icon = trim($icons[$i] ?? '');
    if ($label && $href) {
      $item = ['label'=>$label, 'href'=>$href];
      if ($class) $item['class'] = $class;
      if ($icon) $item['icon'] = $icon;
      $new_nav[] = $item;
    }
  }
  if (!empty($_POST['menu_structure'])) {
    $structure = json_decode($_POST['menu_structure'], true);
    if (is_array($structure)) {
      $db->prepare("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)")->execute(['nav_items', json_encode($structure)]);
      header('Location: menu.php?msg=saved'); exit;
    }
  }
}

include '_header.php';
?>
<style>
.menu-item-row { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: .5rem; margin-bottom: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.03); }
.menu-item-row .handle { cursor: move; }
.menu-item-row .btn { margin-right: 2px; }
.menu-item-row .edit-menu-item { background: #fff3cd; color: #856404; border: 1px solid #ffeeba; }
.submenu-list { border-left: 2px dashed #cbd5e1; margin-left: 2.5rem; padding-left: 1.5rem; }
</style>
<!-- Modal Edit Menu -->
<div class="modal fade" id="editMenuModal" tabindex="-1" aria-labelledby="editMenuModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="editMenuModalLabel">Edit Menu</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="editMenuForm">
          <input type="hidden" id="editMenuIndex">
          <div class="mb-2"><label>Label<input type="text" id="editLabel" class="form-control" required></label></div>
          <div class="mb-2"><label>Link (href)<input type="text" id="editHref" class="form-control" required></label></div>
          <div class="mb-2"><label>Class (opsional)<input type="text" id="editClass" class="form-control"></label></div>
          <div class="mb-2"><label>Icon (opsional)<input type="text" id="editIcon" class="form-control"></label></div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
        <button type="button" class="btn btn-primary" id="saveEditMenu">Simpan</button>
      </div>
    </div>
  </div>
</div>
<div class="container-fluid">
  <h1 class="mt-3 mb-4">Manajemen Menu Navigasi Publik</h1>
  <?php if (!empty($_GET['msg'])): ?>
    <div class="alert alert-success">Menu berhasil disimpan.</div>
  <?php endif; ?>
  <form method="post" class="card p-3 mb-4" id="menuForm">
    <div id="menu-list" class="sortable-list">
      <?php
      function render_menu_items($items, $parent = '') {
        foreach ($items as $i => $item) {
          $hasChildren = !empty($item['children']) && is_array($item['children']);
          $rowId = 'menu-'.uniqid();
          echo '<div class="row mb-2 align-items-end menu-item-row position-relative" data-id="'.($parent.$i).'" id="'.$rowId.'">';
          echo '<div class="col-auto d-flex align-items-center pe-0"><span class="handle btn btn-light border me-2" title="Urutkan"><i class="fa fa-bars"></i></span></div>';
          echo '<div class="col-md-3"><label>Label<input type="text" name="label[]" class="form-control" value="'.e($item['label']).'" required></label></div>';
          echo '<div class="col-md-4"><label>Link (href)<input type="text" name="href[]" class="form-control" value="'.e($item['href']).'" required></label></div>';
          echo '<div class="col-md-2"><label>Class (opsional)<input type="text" name="class[]" class="form-control" value="'.e($item['class'] ?? '').'" placeholder="btn btn-sm btn-outline-primary ms-2"></label></div>';
          echo '<div class="col-md-2"><label>Icon (opsional)<input type="text" name="icon[]" class="form-control" value="'.e($item['icon'] ?? '').'" placeholder="fa fa-home"></label></div>';
          echo '<div class="col-md-1 text-end">';
          echo '<button type="button" class="btn btn-danger btn-sm remove-menu-item" title="Hapus"><i class="fa fa-trash"></i></button>';
          echo '<button type="button" class="btn btn-info btn-sm ms-1 add-sub-menu" title="Tambah Sub Menu"><i class="fa fa-level-down-alt"></i></button>';
          echo '<button type="button" class="btn btn-warning btn-sm ms-1 edit-menu-item" data-rowid="'.$rowId.'" title="Edit"><i class="fa fa-edit"></i></button>';
          echo '</div>';
          echo '</div>';
          // Sub menu container
          echo '<div class="submenu-list">';
          if ($hasChildren) render_menu_items($item['children'], $parent.$i.'-');
          echo '</div>';
        }
      }
      render_menu_items($nav_items);
      ?>
    </div>
    <button type="button" class="btn btn-secondary btn-sm mb-2" id="add-menu-item"><i class="fa fa-plus"></i> Tambah Menu</button>
    <button type="submit" class="btn btn-primary float-end">Simpan Menu</button>
  </form>

  <?php
  // Render menu structure as table for detail view
  function render_menu_table($items, $level = 0) {
    foreach ($items as $item) {
      echo '<tr>';
      echo '<td style="padding-left:'.($level*32).'px">'.e($item['label']).'</td>';
      echo '<td>'.e($item['href']).'</td>';
      echo '<td>'.e($item['class'] ?? '').'</td>';
      echo '<td>'.e($item['icon'] ?? '').'</td>';
      echo '<td>';
      if (!empty($item['children'])) echo '<span class="badge bg-info">Sub Menu</span>';
      echo '</td>';
      echo '</tr>';
      if (!empty($item['children'])) render_menu_table($item['children'], $level+1);
    }
  }
  ?>
  <div class="card mt-4">
    <div class="card-header bg-primary text-white">Detail Struktur Menu (Preview)</div>
    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-bordered table-sm mb-0">
          <thead class="table-light"><tr><th>Label</th><th>Link</th><th>Class</th><th>Icon</th><th>Sub Menu</th></tr></thead>
          <tbody>
            <?php render_menu_table($nav_items); ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<link rel="stylesheet" href="../assets/vendor/fontawesome/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Add/remove menu item row
const menuList = document.getElementById('menu-list');
document.getElementById('add-menu-item').onclick = function() {
  menuList.appendChild(createMenuRow());
};
menuList.addEventListener('click', function(e) {
  if (e.target.closest('.remove-menu-item')) {
    e.target.closest('.menu-item-row').nextElementSibling?.remove();
    e.target.closest('.menu-item-row').remove();
  }
  if (e.target.closest('.add-sub-menu')) {
    const submenu = e.target.closest('.menu-item-row').nextElementSibling;
    submenu.appendChild(createMenuRow());
  }
  if (e.target.closest('.edit-menu-item')) {
    const row = e.target.closest('.menu-item-row');
    const label = row.querySelector('input[name="label[]"]').value;
    const href = row.querySelector('input[name="href[]"]').value;
    const classVal = row.querySelector('input[name="class[]"]').value;
    const icon = row.querySelector('input[name="icon[]"]').value;
    document.getElementById('editLabel').value = label;
    document.getElementById('editHref').value = href;
    document.getElementById('editClass').value = classVal;
    document.getElementById('editIcon').value = icon;
    document.getElementById('editMenuIndex').value = row.id;
    new bootstrap.Modal(document.getElementById('editMenuModal')).show();
  }
});
document.getElementById('saveEditMenu').onclick = function() {
  const rowId = document.getElementById('editMenuIndex').value;
  const row = document.getElementById(rowId);
  if (row) {
    row.querySelector('input[name="label[]"]').value = document.getElementById('editLabel').value;
    row.querySelector('input[name="href[]"]').value = document.getElementById('editHref').value;
    row.querySelector('input[name="class[]"]').value = document.getElementById('editClass').value;
    row.querySelector('input[name="icon[]"]').value = document.getElementById('editIcon').value;
  }
  bootstrap.Modal.getInstance(document.getElementById('editMenuModal')).hide();
};
function createMenuRow() {
  const row = document.createElement('div');
  row.className = 'row mb-2 align-items-end menu-item-row bg-light rounded shadow-sm p-2 position-relative';
  row.innerHTML = `
    <div class=\"col-auto d-flex align-items-center pe-0\"><span class=\"handle btn btn-light border me-2\" title=\"Urutkan\" style=\"cursor:move;\"><i class=\"fa fa-bars\"></i></span></div>
    <div class=\"col-md-3\"><label>Label
      <input type=\"text\" name=\"label[]\" class=\"form-control\" required></label></div>
    <div class=\"col-md-4\"><label>Link (href)
      <input type=\"text\" name=\"href[]\" class=\"form-control\" required></label></div>
    <div class=\"col-md-2\"><label>Class (opsional)
      <input type=\"text\" name=\"class[]\" class=\"form-control\" placeholder=\"btn btn-sm btn-outline-primary ms-2\"></label></div>
    <div class=\"col-md-2\"><label>Icon (opsional)
      <input type=\"text\" name=\"icon[]\" class=\"form-control\" placeholder=\"fa fa-home\"></label></div>
    <div class=\"col-md-1 text-end">
      <button type=\"button\" class=\"btn btn-danger btn-sm remove-menu-item\" title=\"Hapus\"><i class=\"fa fa-trash\"></i></button>
      <button type=\"button\" class=\"btn btn-info btn-sm ms-1 add-sub-menu\" title=\"Tambah Sub Menu\"><i class=\"fa fa-level-down-alt\"></i></button>
    </div>
  `;
  // Add sub menu container
  const sub = document.createElement('div');
  sub.className = 'submenu-list ms-5';
  row.after(sub);
  return row;
}
// Enable drag-and-drop sorting
Sortable.create(menuList, {
  handle: '.handle',
  animation: 150,
  ghostClass: 'bg-warning',
  group: 'main',
  onEnd: function() {
    enableSubmenuSortable();
  }
});
function enableSubmenuSortable() {
  document.querySelectorAll('.submenu-list').forEach(function(sub) {
    if (!sub.classList.contains('sortable-enabled')) {
      Sortable.create(sub, { handle: '.handle', animation: 150, group: 'sub', ghostClass: 'bg-warning' });
      sub.classList.add('sortable-enabled');
    }
  });
}
enableSubmenuSortable();
// Serialize menu structure on submit
const menuForm = document.getElementById('menuForm');
menuForm.onsubmit = function(e) {
  e.preventDefault();
  const structure = buildMenuStructure(menuList);
  const input = document.createElement('input');
  input.type = 'hidden';
  input.name = 'menu_structure';
  input.value = JSON.stringify(structure);
  menuForm.appendChild(input);
  menuForm.submit();
};
function buildMenuStructure(list) {
  const rows = Array.from(list.children).filter(el => el.classList.contains('menu-item-row'));
  return rows.map(row => {
    const next = row.nextElementSibling;
    const obj = {
      label: row.querySelector('input[name="label[]"]').value,
      href: row.querySelector('input[name="href[]"]').value,
      class: row.querySelector('input[name="class[]"]').value,
      icon: row.querySelector('input[name="icon[]"]').value,
      children: []
    };
    if (next && next.classList.contains('submenu-list')) {
      obj.children = buildMenuStructure(next);
    }
    return obj;
  });
}
</script>
<?php include '_footer.php'; ?>
