<?php
require_once '../../includes/functions.php';
requireAdmin();

// Handle AJAX save urutan
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_urutan'])) {
    header('Content-Type: application/json');
    $id     = intval($_POST['id'] ?? 0);
    $urutan = intval($_POST['urutan'] ?? 0);
    if ($id > 0) {
        db_update('mata_pelajaran', array('urutan' => $urutan), 'id = :id', array('id' => $id));
        echo json_encode(array('ok' => true));
    } else {
        echo json_encode(array('ok' => false));
    }
    exit;
}

$pageTitle  = 'Mata Pelajaran';
$activeMenu = 'mapel';
$mapels     = db_fetchAll("SELECT * FROM mata_pelajaran ORDER BY kelompok, urutan, nama_mapel");
include '../../templates/header.php';
?>

<div class="card">
  <div class="card-header">
    <span class="card-title">
      <i class="fas fa-book" style="color:var(--primary);margin-right:8px;"></i>
      Mata Pelajaran
      <span class="badge badge-blue" style="margin-left:8px;"><?= count($mapels) ?></span>
    </span>
    <div style="display:flex;gap:8px;align-items:center;">
      <span id="sort-info" style="font-size:12px;color:var(--text-muted);display:none;">
        <i class="fas fa-info-circle"></i> Klik nomor urut untuk mengedit
      </span>
      <a href="add.php" class="btn btn-primary btn-sm"><i class="fas fa-plus"></i> Tambah Mapel</a>
    </div>
  </div>

  <div class="table-responsive">
    <table class="table" id="mapelTable">
      <thead>
        <tr>
          <th width="50" style="text-align:center;">No</th>
          <th width="100" style="text-align:center;">
            Urutan
            <i class="fas fa-sort" style="font-size:10px;color:var(--text-light);margin-left:3px;" title="Klik nomor untuk edit"></i>
          </th>
          <th width="90">Kode</th>
          <th>Nama Mata Pelajaran</th>
          <th width="80" style="text-align:center;">Status</th>
          <th width="80" style="text-align:center;">Aksi</th>
        </tr>
      </thead>
      <tbody>
        <?php if (empty($mapels)): ?>
        <tr>
          <td colspan="7" class="text-center" style="padding:32px;color:var(--text-muted);">
            Belum ada mata pelajaran
          </td>
        </tr>
        <?php else: ?>

        <?php foreach ($mapels as $i => $m): ?>
        <tr id="row-<?= $m['id'] ?>">
          <td style="text-align:center;color:var(--text-muted);"><?= $i + 1 ?></td>

          <!-- Kolom Urutan - inline edit -->
          <td style="text-align:center;">
            <div class="urutan-display" id="disp-<?= $m['id'] ?>"
                 onclick="startEdit(<?= $m['id'] ?>, <?= intval($m['urutan']) ?>)"
                 title="Klik untuk edit urutan"
                 style="display:inline-flex;align-items:center;gap:5px;cursor:pointer;padding:4px 10px;border-radius:6px;border:1px dashed var(--border);background:var(--bg);font-weight:700;font-size:13px;color:var(--primary);transition:all .15s;min-width:50px;justify-content:center;">
              <span id="val-<?= $m['id'] ?>"><?= intval($m['urutan']) ?></span>
              <i class="fas fa-pencil-alt" style="font-size:9px;color:var(--text-light);"></i>
            </div>
            <div class="urutan-edit" id="edit-<?= $m['id'] ?>" style="display:none;align-items:center;gap:4px;">
              <input type="number" id="inp-<?= $m['id'] ?>"
                     min="0" max="999" step="1"
                     value="<?= intval($m['urutan']) ?>"
                     style="width:58px;padding:4px 6px;text-align:center;border:2px solid var(--primary);border-radius:6px;font-size:13px;font-weight:700;color:var(--primary);outline:none;"
                     onkeydown="handleKey(event, <?= $m['id'] ?>)">
              <button onclick="saveUrutan(<?= $m['id'] ?>)"
                      style="background:var(--success);color:#fff;border:none;border-radius:5px;width:26px;height:26px;cursor:pointer;font-size:11px;"
                      title="Simpan">
                <i class="fas fa-check"></i>
              </button>
              <button onclick="cancelEdit(<?= $m['id'] ?>, <?= intval($m['urutan']) ?>)"
                      style="background:var(--danger);color:#fff;border:none;border-radius:5px;width:26px;height:26px;cursor:pointer;font-size:11px;"
                      title="Batal">
                <i class="fas fa-times"></i>
              </button>
            </div>
          </td>

          <td><code style="font-size:12px;"><?= htmlspecialchars($m['kode_mapel']) ?></code></td>
          <td><strong><?= htmlspecialchars($m['nama_mapel']) ?></strong></td>
          <td style="text-align:center;">
            <span class="badge badge-<?= $m['status'] === 'aktif' ? 'success' : 'gray' ?>">
              <?= ucfirst($m['status']) ?>
            </span>
          </td>
          <td style="text-align:center;">
            <a href="edit.php?id=<?= $m['id'] ?>" class="btn btn-outline btn-xs" title="Edit">
              <i class="fas fa-edit"></i>
            </a>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php endif; ?>
      </tbody>
    </table>
  </div>

  <div style="padding:10px 16px;background:var(--surface-2);border-top:1px solid var(--border);font-size:12px;color:var(--text-muted);">
    <i class="fas fa-lightbulb" style="color:var(--accent);"></i>
    Klik angka pada kolom <strong>Urutan</strong> untuk mengedit langsung. Urutan menentukan tampilan di laporan dan cetak daftar nilai.
  </div>
</div>

<script>
var BASE = '<?= BASE_URL ?>';

function startEdit(id, current) {
    document.getElementById('disp-' + id).style.display = 'none';
    var editDiv = document.getElementById('edit-' + id);
    editDiv.style.display = 'inline-flex';
    var inp = document.getElementById('inp-' + id);
    inp.value = current;
    inp.focus();
    inp.select();
}

function cancelEdit(id, original) {
    document.getElementById('edit-' + id).style.display = 'none';
    var disp = document.getElementById('disp-' + id);
    disp.style.display = 'inline-flex';
    document.getElementById('val-' + id).textContent = original;
    document.getElementById('inp-' + id).value = original;
}

function handleKey(e, id) {
    if (e.key === 'Enter')  saveUrutan(id);
    if (e.key === 'Escape') cancelEdit(id, parseInt(document.getElementById('inp-'+id).defaultValue));
}

function saveUrutan(id) {
    var inp    = document.getElementById('inp-' + id);
    var newVal = parseInt(inp.value);
    if (isNaN(newVal) || newVal < 0) { inp.focus(); return; }

    var btn = inp.nextElementSibling;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
    btn.disabled  = true;

    var fd = new FormData();
    fd.append('save_urutan', '1');
    fd.append('id', id);
    fd.append('urutan', newVal);

    fetch(window.location.pathname, { method: 'POST', body: fd })
      .then(function(r){ return r.json(); })
      .then(function(data) {
        if (data.ok) {
            // Update tampilan
            document.getElementById('val-' + id).textContent = newVal;
            inp.defaultValue = newVal;

            // Flash hijau singkat di baris
            var row = document.getElementById('row-' + id);
            row.style.transition = 'background .2s';
            row.style.background = '#d1fae5';
            setTimeout(function(){ row.style.background = ''; }, 800);

            cancelEdit(id, newVal);
        } else {
            alert('Gagal menyimpan urutan.');
            btn.innerHTML = '<i class="fas fa-check"></i>';
            btn.disabled = false;
        }
      })
      .catch(function(){
        alert('Error koneksi.');
        btn.innerHTML = '<i class="fas fa-check"></i>';
        btn.disabled = false;
      });
}

// Hover effect untuk tombol display urutan
document.querySelectorAll('.urutan-display').forEach(function(el) {
    el.addEventListener('mouseenter', function(){
        this.style.borderColor = 'var(--primary)';
        this.style.background  = 'rgba(26,74,122,.06)';
    });
    el.addEventListener('mouseleave', function(){
        this.style.borderColor = 'var(--border)';
        this.style.background  = 'var(--bg)';
    });
});

// Tampilkan info hint
document.getElementById('sort-info').style.display = 'inline';
</script>

<?php include '../../templates/footer.php'; ?>
