const api = '../api/site/';
const modal = document.getElementById('modal');

function loadSite() {
  fetch(api + 'list.php')
    .then(res => res.json())
    .then(data => {
      const tbody = document.querySelector('#siteTable tbody');
      tbody.innerHTML = '';

      data.forEach(s => {
        tbody.innerHTML += `
          <tr>
            <td>${s.nama_site}</td>
            <td>${s.code_site}</td>
            <td>${s.alamat || '-'}</td>
            <td>
              <button onclick='edit(${JSON.stringify(s)})'>✏️</button>
              <button onclick='hapus(${s.id})'>🗑️</button>
            </td>
          </tr>
        `;
      });
    });
}

function openForm() {
  document.getElementById('formTitle').innerText = 'Tambah Site';
  modal.style.display = 'flex';
  document.querySelectorAll('#modal input, #modal textarea')
    .forEach(el => el.value = '');
}

function closeForm() {
  modal.style.display = 'none';
}

function edit(s) {
  openForm();
  document.getElementById('formTitle').innerText = 'Edit Site';

  for (let k in s) {
    if (document.getElementById(k)) {
      document.getElementById(k).value = s[k];
    }
  }
}

function save() {
  const form = new FormData();
  ['id','nama_site','code_site','lat','lon','alamat','email','no_tlp']
    .forEach(id => form.append(id, document.getElementById(id).value));

  const url = form.get('id') ? 'update.php' : 'create.php';

  fetch(api + url, { method:'POST', body:form })
    .then(() => {
      closeForm();
      loadSite();
    });
}

function hapus(id) {
  if (!confirm('Hapus site ini?')) return;

  const f = new FormData();
  f.append('id', id);

  fetch(api + 'delete.php', { method:'POST', body:f })
    .then(() => loadSite());
}

loadSite();
