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

// Tampilkan notifikasi jika ada
if (isset($_SESSION['success'])) {
    echo "<script>
        Swal.fire({
            icon: 'success',
            title: 'Berhasil!',
            text: '{$_SESSION['success']}',
            timer: 3000
        });
    </script>";
    unset($_SESSION['success']);
}

if (isset($_SESSION['error'])) {
    echo "<script>
        Swal.fire({
            icon: 'error',
            title: 'Gagal!',
            text: '{$_SESSION['error']}',
            timer: 3000
        });
    </script>";
    unset($_SESSION['error']);
}

// 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 dari tabel documents saja
$stmt = $pdo->prepare("
  SELECT d.*, u.full_name AS author
  FROM documents d
  LEFT JOIN users u ON d.created_by = u.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-success:hover {
  background-color: #063527;
}
.btn-warning { 
  background-color: var(--coklat); 
  border: none; 
}
.btn-warning:hover {
  background-color: #b38629;
}
.pagination .page-item.active .page-link {
  background-color: var(--hijau);
  border-color: var(--hijau);
}
.file-info {
  font-size: 0.85rem;
  margin-top: 4px;
}
</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...">
        </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 type="submit" 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 width="50">No</th>
              <th>Judul & File</th>
              <th width="120">Kategori</th>
              <th width="150">Unit</th>
              <th width="100">Status</th>
              <th width="100">Visibilitas</th>
              <th width="120">Pembuat</th>
              <th width="120">Tanggal</th>
              <th width="120">Aksi</th>
            </tr>
          </thead>
          <tbody>
            <?php if ($documents): $no = $offset + 1; foreach ($documents as $doc): ?>
            <tr>
              <td><?= $no++ ?></td>
              <td>
                <strong><?= e($doc['title']) ?></strong>
                <?php if (!empty($doc['file_path']) && !empty($doc['file_name_original'])): ?>
                  <div class="file-info">
                    <a href="/<?= e($doc['file_path']) ?>" target="_blank" class="text-success text-decoration-none">
                      <i class="fa-solid fa-file-pdf"></i> <?= e($doc['file_name_original']) ?>
                    </a>
                    <?php if ($doc['file_size'] > 0): ?>
                      <span class="text-muted ms-2">(<?= number_format($doc['file_size']/1024, 2) ?> KB)</span>
                    <?php endif; ?>
                  </div>
                <?php else: ?>
                  <div class="file-info">
                    <small class="text-danger fst-italic">
                      <i class="fa-solid fa-exclamation-triangle"></i> Belum ada file
                    </small>
                  </div>
                <?php endif; ?>
              </td>
              <td>
                <span class="badge bg-success">
                  <?= ucfirst(e($doc['category'])) ?>
                </span>
              </td>
              <td><?= e($doc['unit_owner'] ?: '-') ?></td>
              <td>
                <span class="badge bg-<?= $doc['status']=='published'?'success':'secondary' ?>">
                  <?= ucfirst(e($doc['status'])) ?>
                </span>
              </td>
              <td>
                <span class="badge bg-<?= $doc['visibility']=='public'?'info':'warning' ?>">
                  <?= ucfirst(e($doc['visibility'])) ?>
                </span>
              </td>
              <td><?= e($doc['author'] ?: '-') ?></td>
              <td>
                <?= date('d M Y', strtotime($doc['created_at'])) ?>
                <?php if ($doc['effective_date']): ?>
                  <br><small class="text-muted">Efektif: <?= date('d/m/Y', strtotime($doc['effective_date'])) ?></small>
                <?php endif; ?>
              </td>
              <td>
                <button class="btn btn-warning btn-sm mb-1"
                  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-notes="<?= e($doc['notes']) ?>"
                  data-effective="<?= e($doc['effective_date']) ?>"
                  data-bs-toggle="modal" data-bs-target="#modalEdit">
                  <i class="fa-solid fa-pen"></i>
                </button>
                <button class="btn btn-danger btn-sm mb-1 btn-delete" data-id="<?= $doc['id'] ?>">
                  <i class="fa-solid fa-trash"></i>
                </button>
              </td>
            </tr>
            <?php endforeach; else: ?>
            <tr>
              <td colspan="9" class="text-center text-muted py-4">
                <i class="fa-solid fa-folder-open fa-3x mb-3"></i>
                <p>Belum ada dokumen.</p>
              </td>
            </tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>

      <!-- Paginasi -->
      <?php if ($totalPages > 1): ?>
      <nav class="mt-3">
        <ul class="pagination justify-content-center mb-0">
          <?php if ($page > 1): ?>
            <li class="page-item">
              <a class="page-link" href="?page=<?= $page-1 ?>&q=<?= urlencode($q) ?>&category=<?= urlencode($category) ?>&status=<?= urlencode($status) ?>">
                <i class="fa-solid fa-chevron-left"></i>
              </a>
            </li>
          <?php endif; ?>
          
          <?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; ?>
          
          <?php if ($page < $totalPages): ?>
            <li class="page-item">
              <a class="page-link" href="?page=<?= $page+1 ?>&q=<?= urlencode($q) ?>&category=<?= urlencode($category) ?>&status=<?= urlencode($status) ?>">
                <i class="fa-solid fa-chevron-right"></i>
              </a>
            </li>
          <?php endif; ?>
        </ul>
      </nav>
      <?php endif; ?>

    </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" enctype="multipart/form-data" class="modal-content" id="formTambah">
      <div class="modal-header bg-success text-white">
        <h5 class="modal-title">
          <i class="fa-solid fa-plus-circle"></i> Tambah Dokumen
        </h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="mb-3">
          <label class="form-label">Judul Dokumen <span class="text-danger">*</span></label>
          <input type="text" name="title" class="form-control" required placeholder="Masukkan judul dokumen">
        </div>
        
        <div class="mb-3">
          <label class="form-label">Kategori <span class="text-danger">*</span></label>
          <select name="category" class="form-select" required>
            <option value="">-- Pilih Kategori --</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>
        </div>
        
        <div class="mb-3">
          <label class="form-label">Unit Pemilik</label>
          <input type="text" name="unit_owner" class="form-control" placeholder="Contoh: Unit Mutu, Unit IT">
        </div>
        
        <div class="mb-3">
          <label class="form-label">Upload File (PDF) <span class="text-danger">*</span></label>
          <input type="file" name="file" class="form-control" accept=".pdf" required id="fileInput">
          <div class="form-text">
            <i class="fa-solid fa-info-circle"></i> Format: PDF | Maksimal: 10MB
          </div>
          <div id="filePreview" class="mt-2"></div>
        </div>
        
        <div class="mb-3">
          <label class="form-label">Tanggal Efektif</label>
          <input type="date" name="effective_date" class="form-control">
        </div>
        
        <div class="mb-3">
          <label class="form-label">Catatan</label>
          <textarea name="notes" class="form-control" rows="3" placeholder="Catatan tambahan (opsional)"></textarea>
        </div>
        
        <div class="row">
          <div class="col-md-6 mb-3">
            <label class="form-label">Status</label>
            <select name="status" class="form-select">
              <option value="draft">Draft</option>
              <option value="published">Published</option>
            </select>
          </div>
          
          <div class="col-md-6 mb-3">
            <label class="form-label">Visibilitas</label>
            <select name="visibility" class="form-select">
              <option value="internal">Internal</option>
              <option value="public">Publik</option>
            </select>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
          <i class="fa-solid fa-times"></i> Batal
        </button>
        <button type="submit" class="btn btn-success">
          <i class="fa-solid fa-save"></i> Simpan Dokumen
        </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" enctype="multipart/form-data" class="modal-content" id="formEdit">
      <div class="modal-header bg-warning text-white">
        <h5 class="modal-title">
          <i class="fa-solid fa-edit"></i> Edit Dokumen
        </h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="id" id="edit-id">
        
        <div class="mb-3">
          <label class="form-label">Judul Dokumen <span class="text-danger">*</span></label>
          <input type="text" name="title" id="edit-title" class="form-control" required>
        </div>
        
        <div class="mb-3">
          <label class="form-label">Kategori <span class="text-danger">*</span></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>
        </div>
        
        <div class="mb-3">
          <label class="form-label">Unit Pemilik</label>
          <input type="text" name="unit_owner" id="edit-unit" class="form-control">
        </div>
        
        <div class="mb-3">
          <label class="form-label">Upload File Baru (Opsional)</label>
          <input type="file" name="file" class="form-control" accept=".pdf" id="fileInputEdit">
          <div class="form-text">
            <i class="fa-solid fa-info-circle"></i> Kosongkan jika tidak ingin mengubah file
          </div>
          <div id="filePreviewEdit" class="mt-2"></div>
        </div>
        
        <div class="mb-3">
          <label class="form-label">Tanggal Efektif</label>
          <input type="date" name="effective_date" id="edit-effective" class="form-control">
        </div>
        
        <div class="mb-3">
          <label class="form-label">Catatan</label>
          <textarea name="notes" id="edit-notes" class="form-control" rows="3"></textarea>
        </div>
        
        <div class="row">
          <div class="col-md-6 mb-3">
            <label class="form-label">Status</label>
            <select name="status" id="edit-status" class="form-select">
              <option value="draft">Draft</option>
              <option value="published">Published</option>
            </select>
          </div>
          
          <div class="col-md-6 mb-3">
            <label class="form-label">Visibilitas</label>
            <select name="visibility" id="edit-visibility" class="form-select">
              <option value="internal">Internal</option>
              <option value="public">Publik</option>
            </select>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
          <i class="fa-solid fa-times"></i> Batal
        </button>
        <button type="submit" class="btn btn-warning text-white">
          <i class="fa-solid fa-save"></i> Perbarui Dokumen
        </button>
      </div>
    </form>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
// Preview file upload
document.getElementById('fileInput').addEventListener('change', function(e) {
  const file = e.target.files[0];
  const preview = document.getElementById('filePreview');
  
  if (file) {
    const size = (file.size / 1024).toFixed(2);
    preview.innerHTML = `
      <div class="alert alert-info mb-0 py-2">
        <i class="fa-solid fa-file-pdf"></i> 
        <strong>${file.name}</strong> (${size} KB)
      </div>
    `;
  } else {
    preview.innerHTML = '';
  }
});

document.getElementById('fileInputEdit').addEventListener('change', function(e) {
  const file = e.target.files[0];
  const preview = document.getElementById('filePreviewEdit');
  
  if (file) {
    const size = (file.size / 1024).toFixed(2);
    preview.innerHTML = `
      <div class="alert alert-info mb-0 py-2">
        <i class="fa-solid fa-file-pdf"></i> 
        <strong>${file.name}</strong> (${size} KB)
      </div>
    `;
  } else {
    preview.innerHTML = '';
  }
});

// Modal Edit - Isi data
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.getElementById('edit-notes').value = b.dataset.notes || '';
  document.getElementById('edit-effective').value = b.dataset.effective || '';
  document.getElementById('filePreviewEdit').innerHTML = '';
});

// Reset form saat modal ditutup
document.getElementById('modalTambah').addEventListener('hidden.bs.modal', function() {
  document.getElementById('formTambah').reset();
  document.getElementById('filePreview').innerHTML = '';
});

// Konfirmasi Hapus
document.querySelectorAll('.btn-delete').forEach(btn => {
  btn.addEventListener('click', function() {
    const id = this.dataset.id;
    
    Swal.fire({
      title: 'Hapus Dokumen?',
      text: "File dan data dokumen akan dihapus permanen!",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#d33',
      cancelButtonColor: '#999',
      confirmButtonText: '<i class="fa-solid fa-trash"></i> Ya, Hapus!',
      cancelButtonText: '<i class="fa-solid fa-times"></i> Batal'
    }).then(result => {
      if (result.isConfirmed) {
        window.location.href = 'proses/dokumen_hapus.php?id=' + id;
      }
    });
  });
});

// Validasi form sebelum submit
document.getElementById('formTambah').addEventListener('submit', function(e) {
  const fileInput = document.getElementById('fileInput');
  const file = fileInput.files[0];
  
  if (file) {
    const maxSize = 10 * 1024 * 1024; // 10MB
    if (file.size > maxSize) {
      e.preventDefault();
      Swal.fire({
        icon: 'error',
        title: 'File Terlalu Besar!',
        text: 'Ukuran file maksimal 10MB'
      });
      return false;
    }
    
    if (file.type !== 'application/pdf') {
      e.preventDefault();
      Swal.fire({
        icon: 'error',
        title: 'Format File Salah!',
        text: 'File harus berformat PDF'
      });
      return false;
    }
  }
});

document.getElementById('formEdit').addEventListener('submit', function(e) {
  const fileInput = document.getElementById('fileInputEdit');
  const file = fileInput.files[0];
  
  if (file) {
    const maxSize = 10 * 1024 * 1024; // 10MB
    if (file.size > maxSize) {
      e.preventDefault();
      Swal.fire({
        icon: 'error',
        title: 'File Terlalu Besar!',
        text: 'Ukuran file maksimal 10MB'
      });
      return false;
    }
    
    if (file.type !== 'application/pdf') {
      e.preventDefault();
      Swal.fire({
        icon: 'error',
        title: 'Format File Salah!',
        text: 'File harus berformat PDF'
      });
      return false;
    }
  }
});
</script>

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