<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Jadwal Ibadah</title>

<!-- HTML2Canvas -->
<script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>

<style>
  body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Arial, sans-serif;
    background: linear-gradient(135deg, #dfe9f3, #ffffff);
    padding: 20px;
    margin: 0;
    display: flex;
    justify-content: center;
  }

  .page {
    max-width: 900px;
    width: 100%;
  }

  /* ===================== PANEL KONTROL ===================== */
  .controls {
    background: #ffffffd9;
    border-radius: 10px;
    padding: 10px 14px;
    margin-bottom: 10px;
    box-shadow: 0 2px 6px rgba(0,0,0,0.08);
    font-size: 13px;
  }
  .controls label { font-weight: 600; margin-right: 4px; }
  .controls input,
  .controls select,
  .controls button {
    font-size: 13px;
    padding: 4px 7px;
    margin: 3px 4px 3px 0;
    border-radius: 6px;
    border: 1px solid #c7ced9;
  }
  .controls button {
    background: #007bff;
    color: #fff;
    border: none;
    font-weight: 600;
    cursor: pointer;
  }

  /* ===================== EDITOR LIST NAMA ===================== */
  .name-editor {
    display: none;
    background: #ffffffd9;
    border-radius: 10px;
    padding: 10px 14px;
    margin-bottom: 10px;
    box-shadow: 0 2px 6px rgba(0,0,0,0.08);
    font-size: 12px;
  }
  .name-editor.show { display: block; }

  #nameList {
    list-style: none;
    padding-left: 0;
    max-height: 160px;
    overflow-y: auto;
    margin: 6px 0;
  }
  #nameList li {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 3px;
    border-bottom: 1px dashed #eee;
    padding-bottom: 2px;
  }
  #nameList li span { flex: 1; }
  #nameList li button {
    font-size: 11px;
    padding: 2px 6px;
    border-radius: 4px;
    border: 1px solid #e06666;
    background: #ffdddd;
    cursor: pointer;
  }

  .name-editor-controls input {
    font-size: 12px;
    padding: 3px 6px;
    margin-right: 4px;
    border-radius: 6px;
    border: 1px solid #c7ced9;
  }

  .name-editor-controls button {
    font-size: 12px;
    padding: 3px 7px;
    margin-right: 4px;
    border-radius: 6px;
    border: none;
    background: #007bff;
    color: #fff;
    cursor: pointer;
    font-weight: 600;
  }

  /* ==================== KARTU JADWAL ==================== */
  #scheduleCard {
    background: #ffffff;
    margin: 0 auto;
    padding: 20px 20px 25px;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.15);
    max-width: 720px;
    width: 100%;
  }

  .title {
    font-size: 15px;
    font-weight: bold;
    text-align: center;
    text-transform: uppercase;
    margin-bottom: 3px;
  }
  .subtitle {
    font-size: 12px;
    font-weight: bold;
    text-align: center;
    text-transform: uppercase;
    margin-bottom: 8px;
  }

  /* ==================== TABEL ==================== */
  table {
    width: 100%;
    border-collapse: collapse;
    font-size: 11px;
    margin-bottom: 14px;
  }
  th {
    background: #bcd2ef;
    border: 1px solid #444;
    padding: 3px;
  }
  td {
    border: 1px solid #444;
    padding: 2px 3px;
    height: 26px;
    text-align: center;
  }

  td.tgl {
    width: 32px;
    font-weight: bold;
  }
  .tgl-text { display: inline-block; min-width: 22px; }
  .tgl-input {
    display: none;
    width: 26px;
    text-align: center;
    font-size: 11px;
    border: 1px solid #aaa;
  }

  td.tgl.editing .tgl-text { display: none; }
  td.tgl.editing .tgl-input { display: inline-block; }

  .cell-text {
    display: inline-block;
    min-height: 11px;
    text-align: left;
  }

  .cell-select {
    display: none;
    width: 100%;
    font-size: 11px;
  }

  td.editable.editing .cell-text { display: none; }
  td.editable.editing .cell-select { display: inline-block; }

  .two-line { display: inline-block; text-align: left; }
  .two-line div { margin-bottom: 2px; }

  .note {
    font-size: 10.5px;
    font-weight: bold;
    text-align: center;
    margin-top: 10px;
  }
  .note .red { color: #d40000; font-size: 12px; }
</style>
</head>

<body>
<div class="page">

  <!-- ================= PANEL KONTROL ================= -->
  <div class="controls">
    <label>Bulan:</label>
    <input id="bulan" style="width:90px; text-transform:uppercase;">
    <label>Tahun:</label>
    <input id="tahun" type="number" style="width:60px;">
    <label>Minggu:</label>
    <select id="minggu" style="width:60px;">
      <option value="4">4</option>
      <option value="5" selected>5</option>
    </select>

    <button onclick="downloadPNG()">Download PNG</button>
    <button id="toggleEditor">Edit Daftar Nama</button>
    <button id="btnReset">Reset Jadwal</button>
  </div>

  <!-- ================= EDITOR LIST NAMA ================= -->
  <div id="nameEditor" class="name-editor">
    <strong>Edit Daftar Nama</strong><br>

    <label>Kategori:
      <select id="categorySelect">
        <option value="leader">Worship Leader</option>
        <option value="singer">Singer</option>
        <option value="keyboard">Keyboardist</option>
        <option value="guitar">Guitarist</option>
        <option value="bass">Bassist</option>
        <option value="drum">Drummer</option>
        <option value="manager">Stage Manager</option>
        <option value="lighting">Lighting</option>
        <option value="multimedia">Multimedia</option>
        <option value="kamera">Kamera & Switcher</option>
      </select>
    </label>

    <ul id="nameList"></ul>

    <div class="name-editor-controls">
      <input id="newName" placeholder="Nama baru...">
      <!-- HANYA 1 TOMBOL: Tambah (auto save ke DB) -->
      <button id="btnAddName">Tambah</button>
    </div>
  </div>

  <!-- ================= KARTU JADWAL ================= -->
  <div id="scheduleCard">

    <div class="title">JADWAL WORSHIP LEADER, SINGERS, PEMAIN MUSIK</div>
    <div class="subtitle" id="judul-musik"></div>

    <!-- Table Musik -->
    <table>
      <thead>
        <tr>
          <th>TGL</th>
          <th>WORSHIP LEADER</th>
          <th>SINGER</th>
          <th>KEYBOARDIST</th>
          <th>GUITARIST</th>
          <th>BASSIST</th>
          <th>DRUMMER</th>
        </tr>
      </thead>
      <tbody id="tbody-musik"></tbody>
    </table>

    <div class="title">JADWAL STAGE MANAGER, MULTIMEDIA, LIGHTING, KAMERA</div>
    <div class="subtitle" id="judul-stage"></div>

    <!-- Table Stage -->
    <table>
      <thead>
        <tr>
          <th>TGL</th>
          <th>STAGE MANAGER</th>
          <th>LIGHTING</th>
          <th>MULTIMEDIA</th>
          <th>KAMERA</th>
          <th>SWITCHER</th>
        </tr>
      </thead>
      <tbody id="tbody-stage"></tbody>
    </table>

    <div class="note">
      <span class="red">LATIHAN TIAP JUMAT, PUKUL 19.00 WIB.</span><br>
      Semua pelayan wajib hadir 30 menit sebelum ibadah.<br>
      Bila berhalangan mohon cari pengganti sendiri.<br>
      Tuhan Yesus memberkati.
    </div>

  </div>

</div>

<!-- ================= JAVASCRIPT ================= -->
<script>
/* ================= DEFAULT LIST ================= */
const LIST = {
  leader:["-"],
  singer:["-"],
  keyboard:["-"],
  guitar:["-"],
  bass:["-"],
  drum:["-"],
  manager:["-"],
  lighting:["-"],
  multimedia:["-"],
  kamera:["-"]
};

/* ====== Load dari database ====== */
function loadListsFromServer(cb){
  fetch("load_names.php")
    .then(r=>r.json())
    .then(j=>{
      if(j.success && j.data){
        Object.keys(j.data).forEach(div=>{
          if (Array.isArray(j.data[div]) && j.data[div].length){
            LIST[div] = ["-"].concat(j.data[div]);
          }
        });
      }
    })
    .catch(()=>{})
    .finally(()=>{ if(typeof cb==="function") cb(); });
}

/* ========== AUTO SAVE TAMBAH NAMA ========== */
function addNameServer(div,name){
  const f=new FormData();
  f.append("division",div);
  f.append("name",name);
  fetch("add_name.php",{method:"POST",body:f})
    .then(r=>r.text())
    .then(t=>console.log("add_name.php:",t))
    .catch(e=>console.error(e));
}

/* ========== AUTO DELETE NAMA ========== */
function deleteNameServer(div,name){
  const f=new FormData();
  f.append("division",div);
  f.append("name",name);
  fetch("delete_name.php",{method:"POST",body:f})
    .then(r=>r.text())
    .then(t=>console.log("delete_name.php:",t))
    .catch(e=>console.error(e));
}

/* ========== TEMPLATE ========== */
function opt(role){ return LIST[role].map(n=>`<option>${n}</option>`).join(""); }

function cell(role){
  return `<td class="editable">
    <span class="cell-text">-</span>
    <select class="cell-select" data-role="${role}">${opt(role)}</select>
  </td>`;
}

function singerCell(){
  return `<td class="editable"><div class="two-line">
    <div><span class="cell-text">-</span> <select data-role="singer" class="cell-select">${opt("singer")}</select></div>
    <div><span class="cell-text">-</span> <select data-role="singer" class="cell-select">${opt("singer")}</select></div>
  </div></td>`;
}

function multimediaCell(){
  return `<td class="editable"><div class="two-line">
    <div><span class="cell-text">Laptop : -</span> <select data-role="multimedia" class="cell-select">${opt("multimedia")}</select></div>
    <div><span class="cell-text">PC : -</span> <select data-role="multimedia" class="cell-select">${opt("multimedia")}</select></div>
  </div></td>`;
}

function tglCell(v){
  return `<td class="tgl">
    <span class="tgl-text">${v}</span>
    <input class="tgl-input" value="${v}">
  </td>`;
}

/* ========== GENERATE ========== */
function generate(){
  const minggu = parseInt(document.getElementById("minggu").value);
  const b = bulan.value.toUpperCase();
  const t = tahun.value;

  document.getElementById("judul-musik").textContent = b+" "+t;
  document.getElementById("judul-stage").textContent = b+" "+t;

  let musik="", stage="";

  for(let i=1;i<=minggu;i++){
    let d = String(i).padStart(2,"0");

    musik += `<tr>
      ${tglCell(d)}
      ${cell("leader")}
      ${singerCell()}
      ${cell("keyboard")}
      ${cell("guitar")}
      ${cell("bass")}
      ${cell("drum")}
    </tr>`;

    stage += `<tr>
      ${tglCell(d)}
      ${cell("manager")}
      ${cell("lighting")}
      ${multimediaCell()}
      ${cell("kamera")}
      ${cell("kamera")}
    </tr>`;
  }

  document.getElementById("tbody-musik").innerHTML = musik;
  document.getElementById("tbody-stage").innerHTML = stage;

  initEdit();
}

/* ========== EDIT MODE ========== */
function initEdit(){
  document.querySelectorAll("td.editable").forEach(td=>{
    td.onclick = e=>{
      e.stopPropagation();
      clearEditing();
      td.classList.add("editing");
    };
    td.querySelectorAll("select").forEach(sel=>{
      sel.onchange = ()=>updateLabel(sel);
    });
  });

  document.querySelectorAll("td.tgl").forEach(td=>{
    const span = td.querySelector(".tgl-text");
    const inp = td.querySelector(".tgl-input");

    td.onclick = e=>{
      e.stopPropagation();
      clearEditing();
      td.classList.add("editing");
      inp.focus();
    };

    inp.onblur = ()=>{
      let v = inp.value.trim();
      if(v==="") v = span.textContent;
      v = v.padStart(2,"0");
      span.textContent = v;
      inp.value = v;
      td.classList.remove("editing");
    };
  });

  document.addEventListener("click",e=>{
    if(!e.target.closest("td.editable") && !e.target.closest("td.tgl")){
      clearEditing();
    }
  });
}

function updateLabel(sel){
  let s = sel.previousElementSibling;
  if(!s) return;
  if(s.textContent.includes("Laptop")) s.textContent="Laptop : "+sel.value;
  else if(s.textContent.includes("PC")) s.textContent="PC : "+sel.value;
  else s.textContent = sel.value;
}

function clearEditing(){
  document.querySelectorAll("td").forEach(td=>td.classList.remove("editing"));
}

/* ========== RESET ========== */
document.getElementById("btnReset").onclick = ()=>{
  const minggu = parseInt(document.getElementById("minggu").value) || 4;

  document.querySelectorAll("td.editable").forEach(td=>{
    td.querySelectorAll(".cell-text").forEach(x=>{
      if(x.textContent.includes("Laptop")) x.textContent="Laptop : -";
      else if(x.textContent.includes("PC")) x.textContent="PC : -";
      else x.textContent="-";
    });
    td.querySelectorAll("select").forEach(sel=>sel.selectedIndex=0);
  });

  const tglCells = document.querySelectorAll("td.tgl");
  tglCells.forEach((td,i)=>{
    let d=String((i%minggu)+1).padStart(2,"0");
    td.querySelector(".tgl-text").textContent=d;
    td.querySelector(".tgl-input").value=d;
  });
};

/* ========== DOWNLOAD PNG ========== */
function downloadPNG(){
  clearEditing();
  html2canvas(document.getElementById("scheduleCard"),{scale:3,backgroundColor:"#FFFFFF"}).then(canvas=>{
    let a=document.createElement("a");
    a.href=canvas.toDataURL("image/png");
    a.download="jadwal-ibadah.png";
    a.click();
  });
}

/* ========== EDITOR NAMA ========== */
const editor      = document.getElementById("nameEditor");
const toggleBtn   = document.getElementById("toggleEditor");
const categorySel = document.getElementById("categorySelect");
const nameListEl  = document.getElementById("nameList");
const newNameInp  = document.getElementById("newName");
const btnAddName  = document.getElementById("btnAddName");

toggleBtn.onclick = ()=>{
  editor.classList.toggle("show");
  if(editor.classList.contains("show")) refreshNameList();
};

categorySel.onchange = refreshNameList;

function refreshNameList(){
  const cat = categorySel.value;
  const arr = LIST[cat] || [];
  const slice = arr.slice(1); // skip "-"
  nameListEl.innerHTML = slice.length
    ? slice.map((name,idx)=>`
      <li>
        <span>${name}</span>
        <button type="button" data-index="${idx+1}" data-name="${name}">Hapus</button>
      </li>`).join("")
    : "<li><em>Belum ada nama.</em></li>";
}

/* ====== Tambah Nama (AUTO SAVE) ====== */
btnAddName.onclick = ()=>{
  const cat  = categorySel.value;
  const name = newNameInp.value.trim();
  if(!name) return;

  if(!LIST[cat].includes(name)){
    LIST[cat].push(name);
    addNameServer(cat,name);
  }

  newNameInp.value = "";
  refreshNameList();
  syncDropdowns();
};

/* ====== Hapus Nama (AUTO DELETE) ====== */
nameListEl.onclick = e=>{
  if(e.target.tagName !== "BUTTON") return;
  const cat  = categorySel.value;
  const idx  = parseInt(e.target.dataset.index,10);
  const name = e.target.dataset.name;

  LIST[cat].splice(idx,1);
  deleteNameServer(cat,name);

  refreshNameList();
  syncDropdowns();
};

/* ====== Sync Dropdown ====== */
function syncDropdowns(){
  Object.keys(LIST).forEach(role=>{
    document.querySelectorAll(`select.cell-select[data-role="${role}"]`).forEach(sel=>{
      const cur = sel.value;
      sel.innerHTML = opt(role);
      sel.value = LIST[role].includes(cur) ? cur : "-";
      updateLabel(sel);
    });
  });
}

/* ========== INIT ========== */
function initMonth(){
  const now = new Date();
  const arr = ["JANUARI","FEBRUARI","MARET","APRIL","MEI","JUNI","JULI","AGUSTUS","SEPTEMBER","OKTOBER","NOVEMBER","DESEMBER"];
  bulan.value = arr[now.getMonth()];
  tahun.value = now.getFullYear();
}

document.getElementById("bulan").oninput  = generate;
document.getElementById("tahun").oninput  = generate;
document.getElementById("minggu").onchange= generate;

window.onload = ()=>{
  initMonth();
  loadListsFromServer(()=> generate());
};
</script>

</body>
</html>