<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <title>Preparation — JPN Helpdesk</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css">
  <style>
    body{padding:16px;background:#f4f6fb;font-family:system-ui,Segoe UI,Roboto}
    .card{border-radius:12px;padding:12px}
    .tools-list label{display:flex;align-items:center;gap:10px}
    .spare-row{display:flex;gap:8px;margin-bottom:8px}
    @media(min-width:768px){.container{max-width:720px;margin:0 auto}}
  </style>
</head>
<body>
  <div class="container">
    <div class="card">
      <h5>Preparation for Visit #{{ $visit->id }}</h5>
      <p class="small text-muted">Isi minimal H-1 sebelum jadwal</p>
      <form id="prepForm">
        <div class="mb-3">
          <label class="form-label">Perlu bawa alat/part?</label>
          <select name="need_tools" class="form-select" required>
            <option value="0">Tidak perlu alat</option>
            <option value="1">Ya, perlu bawa</option>
          </select>
        </div>

        <div id="toolsArea" style="display:none">
          <div class="mb-2 tools-list">
            <label><input type="checkbox" name="tools[]" value="Toolkit"> Toolkit standar</label>
            <label><input type="checkbox" name="tools[]" value="Kabel LAN"> Kabel LAN</label>
            <label><input type="checkbox" name="tools[]" value="Kabel Power"> Kabel Power</label>
            <label><input type="checkbox" name="tools[]" value="Tester Kabel"> Tester kabel</label>
            <label><input type="checkbox" name="tools[]" value="Laptop"> Laptop teknisi</label>
            <label><input type="checkbox" name="tools[]" value="HDMI"> HDMI/adapter</label>
          </div>

          <div class="mb-3">
            <label class="form-label">Spareparts (opsional)</label>
            <div id="spareList"></div>
            <button type="button" class="btn btn-sm btn-outline-primary" id="addSpare">Tambah Part</button>
          </div>
        </div>

        <div class="mb-3">
          <label class="form-label">Catatan persiapan</label>
          <textarea name="notes" class="form-control" rows="3"></textarea>
        </div>

        <button class="btn btn-primary w-100" type="submit">Simpan Preparation</button>
      </form>
      <div id="msg" class="mt-3"></div>
    </div>
  </div>

  <script>
    const needTools = document.querySelector('select[name="need_tools"]');
    const toolsArea = document.getElementById('toolsArea');
    needTools.addEventListener('change', e=>{
      toolsArea.style.display = e.target.value==1 ? 'block' : 'none';
    });

    document.getElementById('addSpare').addEventListener('click', ()=>{
      const div = document.createElement('div'); div.className='spare-row';
      div.innerHTML = `<input name="spareparts[][name]" class="form-control" placeholder="Nama part"><input name="spareparts[][qty]" type="number" value="1" min="1" class="form-control" style="width:80px"><select name="spareparts[][source]" class="form-select" style="width:140px"><option value="stock">Ambil dari stok</option><option value="buy">Beli dulu</option></select><button type="button" class="btn btn-sm btn-danger">Hapus</button>`;
      div.querySelector('button').addEventListener('click', ()=>div.remove());
      document.getElementById('spareList').appendChild(div);
    });

    document.getElementById('prepForm').addEventListener('submit', async (ev)=>{
      ev.preventDefault();
      const form = ev.target;
      const data = new FormData(form);
      // convert to JSON-ish payload
      const payload = {};
      for (const [k,v] of data.entries()){
        if (k.endsWith('[]')) continue;
      }
      // gather tools
      payload.need_tools = form.querySelector('select[name="need_tools"]').value==1?1:0;
      payload.tools = Array.from(form.querySelectorAll('input[name="tools[]"]:checked')).map(i=>i.value);
      payload.notes = form.querySelector('textarea[name="notes"]').value;
      // spareparts
      payload.spareparts = Array.from(document.querySelectorAll('#spareList .spare-row')).map(r=>({
        name: r.querySelector('input[name^="spareparts"]').value,
        qty: r.querySelector('input[type="number"]').value,
        source: r.querySelector('select').value
      }));

      const visitId = {{ $visit->id }};
      const resp = await fetch(`/admin/visits/${visitId}/preparation`,{
        method:'POST',
        headers:{'Content-Type':'application/json','X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?document.querySelector('meta[name="csrf-token"]').getAttribute('content'):'',},
        body: JSON.stringify(payload)
      });
      const json = await resp.json();
      document.getElementById('msg').innerText = json.status=='ok' ? 'Preparation tersimpan' : 'Gagal';
    });
  </script>
</body>
</html>
