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

// Konfigurasi paginasi
$limit = 10;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $limit;

// Ambil filter
$q = trim($_GET['q'] ?? '');
$category = $_GET['category'] ?? '';
$status = $_GET['status'] ?? '';

// Filter query
$where = [];
$params = [];

if ($q !== '') {
  $where[] = "(d.title LIKE :q OR d.unit_owner LIKE :q)";
  $params[':q'] = "%$q%";
}
if ($category !== '') {
  $where[] = "d.category = :category";
  $params[':category'] = $category;
}
if ($status !== '') {
  $where[] = "d.status = :status";
  $params[':status'] = $status;
}

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

// Hitung total data
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM documents d $whereSql");
$countStmt->execute($params);
$totalData = $countStmt->fetchColumn();
$totalPages = ceil($totalData / $limit);

// Ambil data utama + versi aktif
$stmt = $pdo->prepare("
  SELECT d.*, u.full_name AS author, 
         v.file_path, v.file_name_original, v.version_number
  FROM documents d
  LEFT JOIN users u ON d.created_by = u.id
  LEFT JOIN document_versions v ON d.current_version_id = v.id
  $whereSql
  ORDER BY d.created_at DESC
  LIMIT $limit OFFSET $offset
");
$stmt->execute($params);
$documents = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
:root {
  --hijau: #084D36;
  --coklat: #CC9933;
}
.table thead {
  background-color: var(--hijau);
  color: #fff;
}
.btn-success { background-color: var(--hijau); border: none; }
.btn-warning { background-color: var(--coklat); border: none; }
.pagination .page-item.active .page-link {
  background-color: var(--hijau);
  border-color: var(--hijau);
}
</style>

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

      <!-- Header dan Tombol Aksi -->
      <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="fw-bold text-success mb-0">
          <i class="fa-solid fa-folder-open me-2"></i> Manajemen Dokumen Mutu
        </h4>
        <div>
          <a href="export/dokumen_excel.php" class="btn btn-success btn-sm me-1">
            <i class="fa-solid fa-file-excel"></i> Excel
          </a>
          <a href="export/dokumen_pdf.php" class="btn btn-danger btn-sm me-1">
            <i class="fa-solid fa-file-pdf"></i> PDF
          </a>
          <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#modalTambah">
            <i class="fa-solid fa-plus"></i> Tambah
          </button>
        </div>
      </div>

      <!-- Form Filter -->
      <form method="get" class="row g-2 mb-4">
        <div class="col-md-4">
          <input type="text" name="q" id="searchInput" value="<?= e($q) ?>" 
                 class="form-control" placeholder="Cari dokumen..." list="datalistDocs">
          <datalist id="datalistDocs"></datalist>
        </div>
        <div class="col-md-3">
          <select name="category" class="form-select">
            <option value="">-- Semua Kategori --</option>
            <?php
            $cats = ['kebijakan','standar','implementasi','formulir','sop','evaluasi'];
            foreach ($cats as $c) {
              $sel = $c == $category ? 'selected' : '';
              echo "<option value='$c' $sel>" . ucfirst($c) . "</option>";
            }
            ?>
          </select>
        </div>
        <div class="col-md-3">
          <select name="status" class="form-select">
            <option value="">-- Semua Status --</option>
            <option value="draft" <?= $status=='draft'?'selected':'' ?>>Draft</option>
            <option value="published" <?= $status=='published'?'selected':'' ?>>Published</option>
          </select>
        </div>
        <div class="col-md-1">
          <button class="btn btn-success w-100"><i class="fa-solid fa-filter"></i></button>
        </div>
        <div class="col-md-1">
          <a href="dokumen.php" class="btn btn-secondary w-100"><i class="fa-solid fa-rotate-left"></i></a>
        </div>
      </form>

      <!-- Tabel Data -->
      <div class="table-responsive">
        <table class="table table-hover align-middle">
          <thead>
            <tr>
              <th>No</th>
              <th>Judul</th>
              <th>Kategori</th>
              <th>Unit</th>
              <th>Versi Aktif</th>
              <th>Status</th>
              <th>Visibilitas</th>
              <th>Pembuat</th>
              <th>Tanggal</th>
              <th>Aksi</th>
            </tr>
          </thead>
          <tbody>
            <?php if ($documents): $no = $offset + 1; foreach ($documents as $doc): ?>
            <tr>
              <td><?= $no++ ?></td>
              <td>
                <?= e($doc['title']) ?><br>
                <?php if ($doc['file_path']): ?>
                  <a href="../<?= e($doc['file_path']) ?>" target="_blank" class="small text-success">
                    <i class="fa-solid fa-file-pdf"></i> <?= e($doc['file_name_original']) ?>
                  </a>
                <?php else: ?>
                  <small class="text-muted fst-italic">Belum ada file</small>
                <?php endif; ?>
              </td>
              <td><span class="badge bg-success"><?= e($doc['category']) ?></span></td>
              <td><?= e($doc['unit_owner'] ?: '-') ?></td>
              <td class="text-center"><?= $doc['version_number'] ? 'v' . e($doc['version_number']) : '-' ?></td>
              <td>
                <span class="badge bg-<?= $doc['status']=='published'?'success':'secondary' ?>">
                  <?= e($doc['status']) ?>
                </span>
              </td>
              <td><?= e($doc['visibility']) ?></td>
              <td><?= e($doc['author'] ?: '-') ?></td>
              <td><?= date('d M Y', strtotime($doc['created_at'])) ?></td>
              <td>
                <button class="btn btn-warning btn-sm"
                  data-id="<?= $doc['id'] ?>"
                  data-title="<?= e($doc['title']) ?>"
                  data-category="<?= e($doc['category']) ?>"
                  data-unit="<?= e($doc['unit_owner']) ?>"
                  data-status="<?= e($doc['status']) ?>"
                  data-visibility="<?= e($doc['visibility']) ?>"
                  data-bs-toggle="modal" data-bs-target="#modalEdit">
                  <i class="fa-solid fa-pen"></i>
                </button>
                <button class="btn btn-danger btn-sm btn-delete" data-id="<?= $doc['id'] ?>">
                  <i class="fa-solid fa-trash"></i>
                </button>
              </td>
            </tr>
            <?php endforeach; else: ?>
            <tr>
              <td colspan="10" class="text-center text-muted">Belum ada dokumen.</td>
            </tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>

      <!-- Paginasi -->
      <nav class="mt-3">
        <ul class="pagination justify-content-center mb-0">
          <?php for ($i = 1; $i <= $totalPages; $i++): ?>
            <li class="page-item <?= $i == $page ? 'active' : '' ?>">
              <a class="page-link" href="?page=<?= $i ?>&q=<?= urlencode($q) ?>&category=<?= urlencode($category) ?>&status=<?= urlencode($status) ?>">
                <?= $i ?>
              </a>
            </li>
          <?php endfor; ?>
        </ul>
      </nav>

    </div>
  </div>
</div>

<!-- Modal Tambah -->
<div class="modal fade" id="modalTambah" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <form action="proses/dokumen_tambah.php" method="POST" class="modal-content">
      <div class="modal-header bg-success text-white">
        <h5 class="modal-title">Tambah Dokumen</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <label>Judul Dokumen</label>
        <input type="text" name="title" class="form-control" required>
        <label class="mt-2">Kategori</label>
        <select name="category" class="form-select" required>
          <option value="">-- Pilih --</option>
          <option value="kebijakan">Kebijakan</option>
          <option value="standar">Standar</option>
          <option value="implementasi">Implementasi</option>
          <option value="formulir">Formulir</option>
          <option value="sop">SOP</option>
          <option value="evaluasi">Evaluasi</option>
        </select>
        <label class="mt-2">Unit Pemilik</label>
        <input type="text" name="unit_owner" class="form-control">
        <label class="mt-2">Status</label>
        <select name="status" class="form-select">
          <option value="draft">Draft</option>
          <option value="published">Published</option>
        </select>
        <label class="mt-2">Visibilitas</label>
        <select name="visibility" class="form-select">
          <option value="internal">Internal</option>
          <option value="public">Publik</option>
        </select>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
        <button class="btn btn-success">Simpan</button>
      </div>
    </form>
  </div>
</div>

<!-- Modal Edit -->
<div class="modal fade" id="modalEdit" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <form action="proses/dokumen_edit.php" method="POST" class="modal-content">
      <div class="modal-header bg-warning text-white">
        <h5 class="modal-title">Edit Dokumen</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="id" id="edit-id">
        <label>Judul Dokumen</label>
        <input type="text" name="title" id="edit-title" class="form-control" required>
        <label class="mt-2">Kategori</label>
        <select name="category" id="edit-category" class="form-select" required>
          <option value="kebijakan">Kebijakan</option>
          <option value="standar">Standar</option>
          <option value="implementasi">Implementasi</option>
          <option value="formulir">Formulir</option>
          <option value="sop">SOP</option>
          <option value="evaluasi">Evaluasi</option>
        </select>
        <label class="mt-2">Unit Pemilik</label>
        <input type="text" name="unit_owner" id="edit-unit" class="form-control">
        <label class="mt-2">Status</label>
        <select name="status" id="edit-status" class="form-select">
          <option value="draft">Draft</option>
          <option value="published">Published</option>
        </select>
        <label class="mt-2">Visibilitas</label>
        <select name="visibility" id="edit-visibility" class="form-select">
          <option value="internal">Internal</option>
          <option value="public">Publik</option>
        </select>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
        <button class="btn btn-warning text-white">Perbarui</button>
      </div>
    </form>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
const editModal = document.getElementById('modalEdit');
editModal.addEventListener('show.bs.modal', e => {
  const b = e.relatedTarget;
  document.getElementById('edit-id').value = b.dataset.id;
  document.getElementById('edit-title').value = b.dataset.title;
  document.getElementById('edit-category').value = b.dataset.category;
  document.getElementById('edit-unit').value = b.dataset.unit;
  document.getElementById('edit-status').value = b.dataset.status;
  document.getElementById('edit-visibility').value = b.dataset.visibility;
});

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

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