<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<div class="mb-4">
  <a href="<?= base_url('my-works') ?>" class="btn btn-sm btn-outline-secondary">
    <i class="bi bi-arrow-left me-1"></i>Kembali
  </a>
  <h1 class="section-title mt-2 mb-0"><?= esc($title) ?></h1>
</div>

<?php if (session()->has('errors')): ?>
  <div class="alert alert-danger small py-2 mb-3">
    <?php foreach (session('errors') as $err): ?>
      <div><i class="bi bi-dot"></i><?= esc($err) ?></div>
    <?php endforeach; ?>
  </div>
<?php endif; ?>
<?php if (session()->has('error')): ?>
  <div class="alert alert-danger small py-2 mb-3">
    <i class="bi bi-exclamation-circle me-1"></i><?= esc(session('error')) ?>
  </div>
<?php endif; ?>

<?php
  $action = $doc ? base_url('submit/' . $doc['id'] . '/update') : base_url('submit');
?>
<form method="post" action="<?= $action ?>" enctype="multipart/form-data">
  <?= csrf_field() ?>

  <div class="row g-4">
    <!-- Left column: metadata -->
    <div class="col-lg-8">
      <div class="card-stt p-4 mb-4">
        <h6 class="fw-semibold mb-3 border-bottom pb-2">Informasi Dokumen</h6>

        <div class="mb-3">
          <label class="form-label small fw-semibold">Judul <span class="text-danger">*</span></label>
          <input type="text" name="title" class="form-control"
                 value="<?= old('title', $doc['title'] ?? '') ?>" required maxlength="255">
        </div>

        <div class="row g-3 mb-3">
          <div class="col-md-6">
            <label class="form-label small fw-semibold">Jenis Dokumen <span class="text-danger">*</span></label>
            <select name="document_type_id" class="form-select" required>
              <option value="">-- Pilih Jenis --</option>
              <?php foreach ($types as $t): ?>
                <option value="<?= $t['id'] ?>"
                  <?= old('document_type_id', $doc['document_type_id'] ?? '') == $t['id'] ? 'selected' : '' ?>>
                  <?= esc($t['name']) ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="col-md-3">
            <label class="form-label small fw-semibold">Tahun <span class="text-danger">*</span></label>
            <input type="number" name="year" class="form-control"
                   min="1900" max="<?= date('Y') ?>"
                   value="<?= old('year', $doc['year'] ?? date('Y')) ?>" required>
          </div>
          <div class="col-md-3">
            <label class="form-label small fw-semibold">Program Studi</label>
            <select name="study_program_id" class="form-select">
              <option value="">-- Pilih --</option>
              <?php foreach ($programs as $p): ?>
                <option value="<?= $p['id'] ?>"
                  <?= old('study_program_id', $doc['study_program_id'] ?? '') == $p['id'] ? 'selected' : '' ?>>
                  <?= esc($p['name']) ?>
                </option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>

        <div class="row g-3 mb-3">
          <div class="col-md-6">
            <label class="form-label small fw-semibold">Nama Pembimbing</label>
            <input type="text" name="supervisor" class="form-control" maxlength="255"
                   value="<?= old('supervisor', $doc['supervisor'] ?? '') ?>"
                   placeholder="Dosen pembimbing">
          </div>
          <div class="col-md-6">
            <label class="form-label small fw-semibold">Penerbit / Institusi</label>
            <input type="text" name="publisher" class="form-control" maxlength="255"
                   value="<?= old('publisher', $doc['publisher'] ?? '') ?>">
          </div>
        </div>

        <div class="mb-3">
          <label class="form-label small fw-semibold">Kata Kunci</label>
          <input type="text" name="keywords" class="form-control" maxlength="500"
                 value="<?= old('keywords', $doc['keywords'] ?? '') ?>"
                 placeholder="Pisahkan dengan koma, contoh: teologi, kristologi, soterologi">
        </div>

        <div class="mb-0">
          <label class="form-label small fw-semibold">Abstrak</label>
          <textarea name="abstract" class="form-control" rows="6"
                    placeholder="Ringkasan isi karya..."><?= old('abstract', $doc['abstract'] ?? '') ?></textarea>
        </div>
      </div>

      <!-- References section -->
      <div class="card-stt p-4">
        <h6 class="fw-semibold mb-1 border-bottom pb-2">Daftar Referensi</h6>
        <p class="text-muted small mb-3">
          Tambahkan referensi dari repositori ini (internal) atau sumber lain (eksternal).
        </p>

        <div id="refList">
          <?php $existingRefs = $refs ?? []; ?>
          <?php foreach ($existingRefs as $i => $ref): ?>
            <?= view('student/_ref_row', ['i' => $i, 'ref' => $ref]) ?>
          <?php endforeach; ?>
        </div>

        <div class="d-flex gap-2 mt-3">
          <button type="button" class="btn btn-sm btn-outline-primary" onclick="addRef('internal')">
            <i class="bi bi-database me-1"></i>+ Referensi Internal
          </button>
          <button type="button" class="btn btn-sm btn-outline-secondary" onclick="addRef('external')">
            <i class="bi bi-globe me-1"></i>+ Referensi Eksternal
          </button>
        </div>
      </div>
    </div>

    <!-- Right column: file upload + actions -->
    <div class="col-lg-4">
      <div class="card-stt p-4 mb-3">
        <h6 class="fw-semibold mb-3 border-bottom pb-2">File PDF <span class="text-danger"><?= $doc ? '' : '*' ?></span></h6>
        <?php if ($doc): ?>
          <p class="small text-muted mb-2">
            <i class="bi bi-file-earmark-pdf me-1 text-danger"></i>
            File PDF sudah ada. Unggah ulang hanya jika ingin menggantinya.
          </p>
        <?php endif; ?>
        <input type="file" name="file" class="form-control form-control-sm" accept=".pdf"
               <?= $doc ? '' : 'required' ?>>
        <div class="form-text">Maks. 50 MB · Hanya PDF</div>
      </div>

      <div class="card-stt p-4 mb-3">
        <h6 class="fw-semibold mb-3 border-bottom pb-2">Gambar Sampul</h6>
        <?php if (!empty($doc['cover_img'])): ?>
          <img src="<?= base_url('covers/' . esc($doc['cover_img'])) ?>"
               class="img-fluid rounded mb-2" style="max-height:120px;">
        <?php endif; ?>
        <input type="file" name="cover_img" class="form-control form-control-sm"
               accept=".jpg,.jpeg,.png,.gif,.webp">
        <div class="form-text">Maks. 2 MB · JPG, PNG, WebP</div>
      </div>

      <div class="card-stt p-4">
        <button type="submit" name="action" value="draft" class="btn btn-outline-secondary w-100 mb-2">
          <i class="bi bi-save me-2"></i>Simpan sebagai Draft
        </button>
        <p class="text-muted small text-center mb-0">
          Anda dapat mengirim karya untuk ditinjau dari halaman detail setelah menyimpan.
        </p>
      </div>
    </div>
  </div>
</form>

<!-- Internal ref template -->
<template id="tplInternal">
  <div class="ref-row border rounded p-3 mb-2 bg-light" data-type="internal">
    <input type="hidden" name="refs[__i__][reference_type]" value="internal">
    <input type="hidden" name="refs[__i__][cited_document_id]" class="ref-doc-id" value="">
    <div class="d-flex align-items-start gap-2">
      <div class="flex-grow-1">
        <div class="input-group input-group-sm mb-1">
          <input type="text" class="form-control ref-search-input" placeholder="Cari judul di repositori..."
                 autocomplete="off">
          <span class="input-group-text bg-gold border-0"><i class="bi bi-database"></i></span>
        </div>
        <div class="ref-search-results list-group" style="display:none;position:absolute;z-index:200;width:90%;"></div>
        <div class="ref-selected-label small text-success fw-semibold mt-1" style="display:none;"></div>
        <input type="hidden" name="refs[__i__][title]" class="ref-title-hidden">
      </div>
      <button type="button" class="btn btn-sm btn-outline-danger" onclick="this.closest('.ref-row').remove()">
        <i class="bi bi-trash"></i>
      </button>
    </div>
  </div>
</template>

<!-- External ref template -->
<template id="tplExternal">
  <div class="ref-row border rounded p-3 mb-2" data-type="external">
    <input type="hidden" name="refs[__i__][reference_type]" value="external">
    <div class="d-flex gap-2 align-items-start">
      <div class="flex-grow-1 row g-2">
        <div class="col-12">
          <input type="text" name="refs[__i__][raw_text]" class="form-control form-control-sm"
                 placeholder="Teks referensi lengkap (APA/Turabian)...">
        </div>
        <div class="col-md-6">
          <input type="text" name="refs[__i__][doi]" class="form-control form-control-sm"
                 placeholder="DOI (opsional, contoh: 10.1234/...)">
        </div>
        <div class="col-md-6">
          <input type="url" name="refs[__i__][url]" class="form-control form-control-sm"
                 placeholder="URL (opsional)">
        </div>
      </div>
      <button type="button" class="btn btn-sm btn-outline-danger" onclick="this.closest('.ref-row').remove()">
        <i class="bi bi-trash"></i>
      </button>
    </div>
  </div>
</template>

<?= $this->endSection() ?>
<?= $this->section('scripts') ?>
<script>
const CURRENT_DOC_ID = <?= json_encode($doc['id'] ?? 0) ?>;
const API_URL = <?= json_encode(base_url('api/documents/search')) ?>;

let refCount = <?= count($existingRefs ?? []) ?>;

function addRef(type) {
  const tpl = document.getElementById('tpl' + (type === 'internal' ? 'Internal' : 'External'));
  let html = tpl.innerHTML.replaceAll('__i__', refCount++);
  const el = document.createElement('div');
  el.innerHTML = html;
  const row = el.firstElementChild;
  document.getElementById('refList').appendChild(row);
  if (type === 'internal') bindSearch(row);
}

function bindSearch(row) {
  const input   = row.querySelector('.ref-search-input');
  const results = row.querySelector('.ref-search-results');
  const idInput = row.querySelector('.ref-doc-id');
  const label   = row.querySelector('.ref-selected-label');
  const titleH  = row.querySelector('.ref-title-hidden');

  let timer;
  input.addEventListener('input', () => {
    clearTimeout(timer);
    const q = input.value.trim();
    if (q.length < 2) { results.style.display = 'none'; return; }
    timer = setTimeout(() => {
      fetch(API_URL + '?q=' + encodeURIComponent(q) + '&exclude=' + CURRENT_DOC_ID)
        .then(r => r.json())
        .then(data => {
          results.innerHTML = '';
          if (!data.length) { results.style.display = 'none'; return; }
          data.forEach(doc => {
            const a = document.createElement('button');
            a.type = 'button';
            a.className = 'list-group-item list-group-item-action small py-2';
            a.innerHTML = `<strong>${escHtml(doc.title)}</strong><br>
                           <span class="text-muted">${escHtml(doc.author_name)} · ${escHtml(doc.year)} · ${escHtml(doc.type_name)}</span>`;
            a.addEventListener('click', () => {
              idInput.value  = doc.id;
              titleH.value   = doc.title;
              label.textContent = '✓ ' + doc.title;
              label.style.display = 'block';
              input.style.display = 'none';
              results.style.display = 'none';
            });
            results.appendChild(a);
          });
          results.style.display = 'block';
        });
    }, 300);
  });

  document.addEventListener('click', e => {
    if (!row.contains(e.target)) results.style.display = 'none';
  });
}

function escHtml(str) {
  const d = document.createElement('div');
  d.appendChild(document.createTextNode(str ?? ''));
  return d.innerHTML;
}

// Bind existing internal rows on page load
document.querySelectorAll('.ref-row[data-type="internal"]').forEach(bindSearch);
</script>
<?= $this->endSection() ?>
