<?php
require_once __DIR__ . '/../config/secure_bootstrap.php';
include __DIR__ . '/includes/header.php';

// ====== FILTER & PAGINATION ======
$category_filter = $_GET['category'] ?? '';
$search = trim($_GET['search'] ?? '');
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

// ====== BASE QUERY ======
$where = [];
$params = [];

if (!empty($category_filter)) {
  $where[] = "s.category = ?";
  $params[] = $category_filter;
}

if (!empty($search)) {
  $where[] = "(s.title LIKE ? OR s.code LIKE ? OR s.description LIKE ?)";
  $params = array_merge($params, ["%$search%", "%$search%", "%$search%"]);
}

$where_sql = $where ? "WHERE " . implode(" AND ", $where) : "";

// ====== CRUD HANDLING ======

// TAMBAH
if (isset($_POST['add'])) {
  $stmt = $pdo->prepare("INSERT INTO spmi_standards (code, title, description, category, document_id, created_by)
                         VALUES (?, ?, ?, ?, ?, ?)");
  $stmt->execute([
    $_POST['code'],
    $_POST['title'],
    $_POST['description'],
    $_POST['category'],
    $_POST['document_id'] ?: null,
    $_SESSION['user_id'] ?? null
  ]);
  echo "<script>Swal.fire('Berhasil', 'Standar mutu berhasil ditambahkan', 'success')
        .then(()=>location.href='spmi_standards.php');</script>";
  exit;
}

// UPDATE
if (isset($_POST['update'])) {
  $stmt = $pdo->prepare("UPDATE spmi_standards 
                         SET code=?, title=?, description=?, category=?, document_id=? 
                         WHERE id=?");
  $stmt->execute([
    $_POST['edit_code'],
    $_POST['edit_title'],
    $_POST['edit_description'],
    $_POST['edit_category'],
    $_POST['edit_document_id'] ?: null,
    $_POST['edit_id']
  ]);
  echo "<script>Swal.fire('Berhasil', 'Standar mutu berhasil diperbarui', 'success')
        .then(()=>location.href='spmi_standards.php');</script>";
  exit;
}

// HAPUS
if (isset($_GET['delete'])) {
  $stmt = $pdo->prepare("DELETE FROM spmi_standards WHERE id=?");
  $stmt->execute([$_GET['delete']]);
  echo "<script>Swal.fire('Dihapus', 'Standar mutu berhasil dihapus', 'success')
        .then(()=>location.href='spmi_standards.php');</script>";
  exit;
}

// ====== AMBIL DATA ======
$count_stmt = $pdo->prepare("SELECT COUNT(*) FROM spmi_standards s $where_sql");
$count_stmt->execute($params);
$total_rows = $count_stmt->fetchColumn();
$total_pages = ceil($total_rows / $limit);

$stmt = $pdo->prepare("
  SELECT 
    s.*, 
    u.full_name AS creator,
    d.title AS document_title,
    v.file_path,
    v.file_name_original
  FROM spmi_standards s
  LEFT JOIN users u ON s.created_by = u.id
  LEFT JOIN documents d ON s.document_id = d.id
  LEFT JOIN document_versions v ON d.current_version_id = v.id
  $where_sql
  ORDER BY s.code ASC
  LIMIT $limit OFFSET $offset
");
$stmt->execute($params);
$standards = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Dropdown dokumen
$documents = $pdo->query("SELECT id, title FROM documents ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="container-fluid mt-3">
  <div class="card shadow p-4">

    <!-- Header & Tombol -->
    <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
      <h4 class="mb-0"><i class="fa-solid fa-book-open text-success me-2"></i>Standar Mutu SPMI</h4>
      <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addModal">
        <i class="fa-solid fa-plus me-1"></i> Tambah Standar
      </button>
    </div>

    <!-- FILTER & SEARCH -->
    <form method="get" class="row g-2 mb-3 align-items-end">
      <div class="col-md-3">
        <label class="form-label mb-1">Kategori</label>
        <select name="category" class="form-select">
          <option value="">Semua Kategori</option>
          <option value="pendidikan" <?= $category_filter=='pendidikan'?'selected':'' ?>>Pendidikan</option>
          <option value="penelitian" <?= $category_filter=='penelitian'?'selected':'' ?>>Penelitian</option>
          <option value="pengabdian" <?= $category_filter=='pengabdian'?'selected':'' ?>>Pengabdian</option>
          <option value="tata kelola" <?= $category_filter=='tata kelola'?'selected':'' ?>>Tata Kelola</option>
        </select>
      </div>
      <div class="col-md-5">
        <label class="form-label mb-1">Pencarian</label>
        <input type="text" name="search" class="form-control" placeholder="Cari berdasarkan kode, judul, atau deskripsi..." value="<?= htmlspecialchars($search) ?>">
      </div>
      <div class="col-md-4 d-flex gap-2">
        <button type="submit" class="btn btn-outline-success mt-auto"><i class="fa-solid fa-search me-1"></i>Cari</button>
        <a href="spmi_standards.php" class="btn btn-outline-secondary mt-auto"><i class="fa-solid fa-rotate-left me-1"></i>Reset</a>
      </div>
    </form>

    <!-- TABEL -->
    <div class="table-responsive shadow-sm rounded">
      <table class="table table-bordered align-middle">
        <thead class="table-success text-center align-middle">
          <tr>
            <th>No</th>
            <th>Kode</th>
            <th>Judul Standar</th>
            <th>Kategori</th>
            <th>Dokumen</th>
            <th>Dibuat Oleh</th>
            <th>Tanggal Dibuat</th>
            <th>Aksi</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($standards): foreach ($standards as $i => $s): ?>
          <tr>
            <td class="text-center"><?= $offset + $i + 1 ?></td>
            <td class="text-center fw-bold"><?= htmlspecialchars($s['code']) ?></td>
            <td><?= htmlspecialchars($s['title']) ?></td>
            <td class="text-center"><?= ucfirst(htmlspecialchars($s['category'])) ?></td>
            <td class="text-center">
              <?php if ($s['file_path']): ?>
                <a href="../<?= htmlspecialchars($s['file_path']) ?>" target="_blank" class="text-success text-decoration-none">
                  <i class="fa-solid fa-file-pdf"></i> <?= htmlspecialchars($s['document_title']) ?>
                </a>
              <?php elseif ($s['document_title']): ?>
                <span class="text-muted"><i class="fa-solid fa-ban"></i> Tidak ada file aktif</span><br>
                <small><?= htmlspecialchars($s['document_title']) ?></small>
              <?php else: ?>
                <span class="text-muted">-</span>
              <?php endif; ?>
            </td>
            <td><?= htmlspecialchars($s['creator'] ?: '-') ?></td>
            <td class="text-center"><?= date('d/m/Y', strtotime($s['created_at'])) ?></td>
            <td class="text-center">
              <button class="btn btn-sm btn-primary edit-btn"
                      data-id="<?= $s['id'] ?>"
                      data-code="<?= htmlspecialchars($s['code']) ?>"
                      data-title="<?= htmlspecialchars($s['title']) ?>"
                      data-category="<?= htmlspecialchars($s['category']) ?>"
                      data-description="<?= htmlspecialchars($s['description']) ?>"
                      data-document="<?= $s['document_id'] ?>">
                <i class="fa-solid fa-pen-to-square"></i>
              </button>
              <button class="btn btn-sm btn-danger delete-btn" data-id="<?= $s['id'] ?>">
                <i class="fa-solid fa-trash"></i>
              </button>
            </td>
          </tr>
          <?php endforeach; else: ?>
          <tr><td colspan="8" class="text-center text-muted">Tidak ada data ditemukan.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>

    <!-- PAGINATION -->
    <?php if ($total_pages > 1): ?>
      <nav class="mt-3">
        <ul class="pagination justify-content-center">
          <?php for ($p = 1; $p <= $total_pages; $p++): ?>
            <li class="page-item <?= $p==$page?'active':'' ?>">
              <a class="page-link" href="?page=<?= $p ?>&category=<?= urlencode($category_filter) ?>&search=<?= urlencode($search) ?>"><?= $p ?></a>
            </li>
          <?php endfor; ?>
        </ul>
      </nav>
    <?php endif; ?>
  </div>
</div>

<!-- Modal Tambah -->
<div class="modal fade" id="addModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <form method="post" class="modal-content">
      <div class="modal-header bg-success text-white">
        <h5 class="modal-title"><i class="fa-solid fa-plus me-2"></i>Tambah Standar Mutu</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <label class="form-label">Kode Standar</label>
        <input type="text" name="code" class="form-control" required>

        <label class="form-label mt-2">Judul Standar</label>
        <input type="text" name="title" class="form-control" required>

        <label class="form-label mt-2">Kategori</label>
        <select name="category" class="form-select" required>
          <option value="pendidikan">Pendidikan</option>
          <option value="penelitian">Penelitian</option>
          <option value="pengabdian">Pengabdian</option>
          <option value="tata kelola">Tata Kelola</option>
        </select>

        <label class="form-label mt-2">Deskripsi</label>
        <textarea name="description" class="form-control" rows="3"></textarea>

        <label class="form-label mt-2">Dokumen Terkait</label>
        <select name="document_id" class="form-select">
          <option value="">Tidak ada</option>
          <?php foreach ($documents as $d): ?>
          <option value="<?= $d['id'] ?>"><?= htmlspecialchars($d['title']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
        <button type="submit" name="add" class="btn btn-success">Simpan</button>
      </div>
    </form>
  </div>
</div>

<!-- Modal Edit -->
<div class="modal fade" id="editModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <form method="post" class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title"><i class="fa-solid fa-pen-to-square me-2"></i>Edit Standar Mutu</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="edit_id" id="edit_id">
        <label class="form-label">Kode Standar</label>
        <input type="text" name="edit_code" id="edit_code" class="form-control" required>
        <label class="form-label mt-2">Judul Standar</label>
        <input type="text" name="edit_title" id="edit_title" class="form-control" required>
        <label class="form-label mt-2">Kategori</label>
        <select name="edit_category" id="edit_category" class="form-select">
          <option value="pendidikan">Pendidikan</option>
          <option value="penelitian">Penelitian</option>
          <option value="pengabdian">Pengabdian</option>
          <option value="tata kelola">Tata Kelola</option>
        </select>
        <label class="form-label mt-2">Deskripsi</label>
        <textarea name="edit_description" id="edit_description" class="form-control" rows="3"></textarea>
        <label class="form-label mt-2">Dokumen Terkait</label>
        <select name="edit_document_id" id="edit_document_id" class="form-select">
          <option value="">Tidak ada</option>
          <?php foreach ($documents as $d): ?>
          <option value="<?= $d['id'] ?>"><?= htmlspecialchars($d['title']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
        <button type="submit" name="update" class="btn btn-primary">Perbarui</button>
      </div>
    </form>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
  // Edit
  document.querySelectorAll('.edit-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      document.getElementById('edit_id').value = btn.dataset.id;
      document.getElementById('edit_code').value = btn.dataset.code;
      document.getElementById('edit_title').value = btn.dataset.title;
      document.getElementById('edit_category').value = btn.dataset.category;
      document.getElementById('edit_description').value = btn.dataset.description || '';
      document.getElementById('edit_document_id').value = btn.dataset.document || '';
      new bootstrap.Modal(document.getElementById('editModal')).show();
    });
  });

  // Hapus
  document.querySelectorAll('.delete-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      Swal.fire({
        title: 'Hapus Standar?',
        text: 'Data standar akan dihapus permanen!',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Ya, hapus!',
        cancelButtonText: 'Batal'
      }).then(r => {
        if (r.isConfirmed)
          window.location.href = 'spmi_standards.php?delete=' + btn.dataset.id;
      });
    });
  });
});
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>
