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

// === FILTER & SEARCH HANDLING ===
$filter_type = $_GET['filter_type'] ?? '';
$filter_status = $_GET['filter_status'] ?? '';
$search = trim($_GET['search'] ?? '');

$query = "SELECT a.*, u.full_name AS creator 
          FROM accreditation a
          LEFT JOIN users u ON a.created_by = u.id
          WHERE 1";
$params = [];

if (!empty($filter_type)) {
  $query .= " AND a.type = ?";
  $params[] = $filter_type;
}
if (!empty($filter_status)) {
  if ($filter_status === 'aktif') $query .= " AND a.valid_until >= CURDATE()";
  elseif ($filter_status === 'kadaluarsa') $query .= " AND a.valid_until < CURDATE()";
}
if (!empty($search)) {
  $query .= " AND (a.institution_name LIKE ? OR a.program_studi LIKE ? OR a.accreditation_body LIKE ? OR a.rating LIKE ? OR a.strata LIKE ?)";
  $search_term = "%$search%";
  $params = array_merge($params, [$search_term, $search_term, $search_term, $search_term, $search_term]);
}

$query .= " ORDER BY a.created_at DESC";
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$akreditasi = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Folder upload
$upload_dir = __DIR__ . '/../uploads/akreditasi/';
if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);

// Fungsi hitung sisa waktu
function hitungSisaWaktu($valid_until) {
  if (empty($valid_until)) return ['Kadaluarsa', 'Kadaluarsa'];
  $now = new DateTime();
  $end = new DateTime($valid_until);
  if ($end < $now) return ['Kadaluarsa', 'Kadaluarsa'];
  $diff = $now->diff($end);
  return ['Aktif', "{$diff->y} Tahun {$diff->m} Bulan {$diff->d} Hari"];
}
?>

<div class="container-fluid mt-3">
  <div class="card shadow p-4">
    <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-award text-success me-2"></i>Manajemen Data Akreditasi
      </h4>
      <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addModal">
        <i class="fa-solid fa-plus me-1"></i> Tambah Akreditasi
      </button>
    </div>

    <!-- FILTER & SEARCH -->
    <form method="get" class="row g-3 mb-3 align-items-end">
    
      <div class="col-lg-3 col-md-4 col-12">
        <label class="form-label mb-1">Jenis</label>
        <select name="filter_type" class="form-select">
          <option value="">Semua Jenis</option>
          <option value="universitas" <?= $filter_type === 'universitas' ? 'selected' : '' ?>>Universitas</option>
          <option value="prodi" <?= $filter_type === 'prodi' ? 'selected' : '' ?>>Program Studi</option>
        </select>
      </div>
    
      <div class="col-lg-3 col-md-4 col-12">
        <label class="form-label mb-1">Status</label>
        <select name="filter_status" class="form-select">
          <option value="">Semua Status</option>
          <option value="aktif" <?= $filter_status === 'aktif' ? 'selected' : '' ?>>Aktif</option>
          <option value="kadaluarsa" <?= $filter_status === 'kadaluarsa' ? 'selected' : '' ?>>Kadaluarsa</option>
        </select>
      </div>
    
      <div class="col-lg-4 col-md-6 col-12">
        <label class="form-label mb-1">Pencarian</label>
        <input type="text" name="search" class="form-control"
               placeholder="Cari akreditasi..."
               value="<?= htmlspecialchars($search) ?>">
      </div>
    
      <div class="col-lg-2 col-md-4 col-12 d-flex gap-2">
        <button type="submit" class="btn btn-success w-100">
          <i class="fa-solid fa-search me-1"></i> Cari
        </button>
        <a href="akreditasi.php" class="btn btn-secondary w-100">
          <i class="fa-solid fa-rotate-left me-1"></i> Reset
        </a>
      </div>
    
    </form>

    <!-- Export Button -->
    <form action="export/akreditasi_export_excel.php" method="post" class="mb-3">
      <input type="hidden" name="filter_type" value="<?= htmlspecialchars($filter_type) ?>">
      <input type="hidden" name="filter_status" value="<?= htmlspecialchars($filter_status) ?>">
      <input type="hidden" name="search" value="<?= htmlspecialchars($search) ?>">
      <button class="btn btn-success"><i class="fa-solid fa-file-excel me-1"></i> Export Spreadsheet</button>
    </form>

    <!-- TABLE -->
    <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>Jenis</th>
            <th>Nama Institusi / Prodi</th>
            <th>Strata</th>
            <th>Lembaga</th>
            <th>Peringkat</th>
            <th>Status</th>
            <th>Sisa Waktu</th>
            <th>Masa Berlaku</th>
            <th>Dokumen</th>
            <th>Aksi</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($akreditasi): foreach ($akreditasi as $i => $a): 
            [$status, $sisa] = hitungSisaWaktu($a['valid_until']);
          ?>
          <tr>
            <td class="text-center"><?= $i + 1 ?></td>
            <td class="text-capitalize text-center"><?= htmlspecialchars($a['type']) ?></td>
            <td><?= $a['type'] === 'universitas' ? htmlspecialchars($a['institution_name']) : htmlspecialchars($a['program_studi']) ?></td>
            <td class="text-center"><?= htmlspecialchars($a['strata']) ?></td>
            <td><?= htmlspecialchars($a['accreditation_body']) ?></td>
            <td class="text-center"><?= htmlspecialchars($a['rating']) ?></td>
            <td class="text-center">
              <span class="badge bg-<?= strtolower($status) == 'aktif' ? 'success' : 'secondary' ?>"><?= $status ?></span>
            </td>
            <td class="text-center"><?= htmlspecialchars($sisa) ?></td>
            <td class="text-center"><?= htmlspecialchars($a['valid_from']) ?> s.d <?= htmlspecialchars($a['valid_until']) ?></td>
            <td class="text-center">
              <?php if ($a['document_file']): ?>
                <a href="../uploads/akreditasi/<?= htmlspecialchars($a['document_file']) ?>" target="_blank" class="text-success text-decoration-none">
                  <i class="fa-solid fa-file-lines me-1"></i>Lihat
                </a>
              <?php else: ?><span class="text-muted">-</span><?php endif; ?>
            </td>
            <td class="text-center">
              <button class="btn btn-sm btn-primary edit-btn"
                      data-id="<?= $a['id'] ?>"
                      data-type="<?= $a['type'] ?>"
                      data-inst="<?= htmlspecialchars($a['institution_name']) ?>"
                      data-prodi="<?= htmlspecialchars($a['program_studi']) ?>"
                      data-strata="<?= htmlspecialchars($a['strata']) ?>"
                      data-body="<?= htmlspecialchars($a['accreditation_body']) ?>"
                      data-rating="<?= htmlspecialchars($a['rating']) ?>"
                      data-number="<?= htmlspecialchars($a['decision_number']) ?>"
                      data-from="<?= $a['valid_from'] ?>"
                      data-until="<?= $a['valid_until'] ?>"
                      data-file="<?= htmlspecialchars($a['document_file']) ?>">
                <i class="fa-solid fa-pen-to-square"></i>
              </button>
              <button class="btn btn-sm btn-danger delete-btn" data-id="<?= $a['id'] ?>">
                <i class="fa-solid fa-trash"></i>
              </button>
            </td>
          </tr>
          <?php endforeach; else: ?>
          <tr><td colspan="12" class="text-center text-muted">Tidak ada data ditemukan.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- Modal Tambah -->
<div class="modal fade" id="addModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <form method="post" enctype="multipart/form-data" 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 Akreditasi</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <label class="form-label">Jenis Akreditasi</label>
        <select name="type" class="form-select" required>
          <option value="universitas">Universitas</option>
          <option value="prodi">Program Studi</option>
        </select>

        <label class="form-label mt-2">Nama Institusi / Program Studi</label>
        <input type="text" name="name" class="form-control" required>

        <label class="form-label mt-2">Strata</label>
        <input type="text" name="strata" class="form-control" placeholder="Contoh: S1, D3, Magister">

        <label class="form-label mt-2">Lembaga Akreditasi</label>
        <input type="text" name="accreditation_body" class="form-control" value="BAN-PT">

        <label class="form-label mt-2">Nomor SK</label>
        <input type="text" name="decision_number" class="form-control">

        <label class="form-label mt-2">Peringkat / Nilai Akreditasi</label>
        <input type="text" name="rating" class="form-control" placeholder="Contoh: Unggul / B / C">

        <div class="row mt-2">
          <div class="col-md-6">
            <label class="form-label">Berlaku Dari</label>
            <input type="date" name="valid_from" class="form-control">
          </div>
          <div class="col-md-6">
            <label class="form-label">Sampai</label>
            <input type="date" name="valid_until" class="form-control">
          </div>
        </div>

        <label class="form-label mt-2">Upload Dokumen Akreditasi (PDF/JPG/PNG)</label>
        <input type="file" name="document_file" class="form-control" accept=".pdf,.jpg,.jpeg,.png">
      </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" enctype="multipart/form-data" 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 Akreditasi</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">Jenis Akreditasi</label>
        <select name="edit_type" id="edit_type" class="form-select" required>
          <option value="universitas">Universitas</option>
          <option value="prodi">Program Studi</option>
        </select>

        <label class="form-label mt-2">Nama Institusi / Program Studi</label>
        <input type="text" name="edit_name" id="edit_name" class="form-control" required>

        <label class="form-label mt-2">Strata</label>
        <input type="text" name="edit_strata" id="edit_strata" class="form-control">

        <label class="form-label mt-2">Lembaga Akreditasi</label>
        <input type="text" name="edit_body" id="edit_body" class="form-control">

        <label class="form-label mt-2">Nomor SK</label>
        <input type="text" name="edit_number" id="edit_number" class="form-control">

        <label class="form-label mt-2">Peringkat / Nilai Akreditasi</label>
        <input type="text" name="edit_rating" id="edit_rating" class="form-control">

        <div class="row mt-2">
          <div class="col-md-6">
            <label class="form-label">Berlaku Dari</label>
            <input type="date" name="edit_from" id="edit_from" class="form-control">
          </div>
          <div class="col-md-6">
            <label class="form-label">Sampai</label>
            <input type="date" name="edit_until" id="edit_until" class="form-control">
          </div>
        </div>

        <label class="form-label mt-2">Upload Dokumen Baru (PDF/JPG/PNG)</label>
        <input type="file" name="edit_document_file" id="edit_document_file" class="form-control" accept=".pdf,.jpg,.jpeg,.png">
        <div id="current_file_info" class="mt-1 text-muted small fst-italic"></div>
      </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>

<?php
// ===== CRUD AKREDITASI =====

// === TAMBAH ===
if (isset($_POST['add'])) {
  $type = $_POST['type'];
  $name = $_POST['name'];
  $file_name = null;
  if (!empty($_FILES['document_file']['name'])) {
    $file_base = preg_replace('/[^A-Za-z0-9_\.-]/', '_', basename($_FILES['document_file']['name']));
    $file_name = time() . '_' . $file_base;
    move_uploaded_file($_FILES['document_file']['tmp_name'], $upload_dir . $file_name);
  }

  $stmt = $pdo->prepare("INSERT INTO accreditation 
    (type, institution_name, program_studi, strata, accreditation_body, decision_number, rating, valid_from, valid_until, document_file, created_by)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
  $stmt->execute([
    $type,
    $type === 'universitas' ? $name : null,
    $type === 'prodi' ? $name : null,
    $_POST['strata'],
    $_POST['accreditation_body'],
    $_POST['decision_number'],
    $_POST['rating'],
    $_POST['valid_from'],
    $_POST['valid_until'],
    $file_name,
    $_SESSION['user_id'] ?? null
  ]);

  echo "<script>Swal.fire('Berhasil', 'Data akreditasi berhasil ditambahkan', 'success').then(()=>location.href='akreditasi.php');</script>";
  exit;
}

// === UPDATE ===
if (isset($_POST['update'])) {
  $id = (int)$_POST['edit_id'];
  $type = $_POST['edit_type'];
  $name = $_POST['edit_name'];

  $stmt = $pdo->prepare("SELECT document_file FROM accreditation WHERE id=?");
  $stmt->execute([$id]);
  $old_file = $stmt->fetchColumn();
  $new_file = $old_file;

  if (!empty($_FILES['edit_document_file']['name'])) {
    if ($old_file && file_exists($upload_dir . $old_file)) unlink($upload_dir . $old_file);
    $file_base = preg_replace('/[^A-Za-z0-9_\.-]/', '_', basename($_FILES['edit_document_file']['name']));
    $new_file = time() . '_' . $file_base;
    move_uploaded_file($_FILES['edit_document_file']['tmp_name'], $upload_dir . $new_file);
  }

  $stmt = $pdo->prepare("UPDATE accreditation 
    SET type=?, institution_name=?, program_studi=?, strata=?, accreditation_body=?, decision_number=?, rating=?, valid_from=?, valid_until=?, document_file=? 
    WHERE id=?");
  $stmt->execute([
    $type,
    $type === 'universitas' ? $name : null,
    $type === 'prodi' ? $name : null,
    $_POST['edit_strata'],
    $_POST['edit_body'],
    $_POST['edit_number'],
    $_POST['edit_rating'],
    $_POST['edit_from'],
    $_POST['edit_until'],
    $new_file,
    $id
  ]);

  echo "<script>Swal.fire('Berhasil', 'Data akreditasi berhasil diperbarui', 'success').then(()=>location.href='akreditasi.php');</script>";
  exit;
}

// === HAPUS ===
if (isset($_GET['delete'])) {
  $id = (int)$_GET['delete'];
  $stmt = $pdo->prepare("SELECT document_file FROM accreditation WHERE id=?");
  $stmt->execute([$id]);
  $file = $stmt->fetchColumn();
  if ($file && file_exists($upload_dir . $file)) unlink($upload_dir . $file);

  $stmt = $pdo->prepare("DELETE FROM accreditation WHERE id=?");
  $stmt->execute([$id]);

  echo "<script>Swal.fire('Dihapus', 'Data akreditasi berhasil dihapus', 'success').then(()=>location.href='akreditasi.php');</script>";
  exit;
}
?>

<script>
document.addEventListener('DOMContentLoaded', () => {
  // === Edit Data ===
  document.querySelectorAll('.edit-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      document.getElementById('edit_id').value = btn.dataset.id;
      document.getElementById('edit_type').value = btn.dataset.type;
      document.getElementById('edit_name').value = (btn.dataset.type === 'universitas') 
        ? btn.dataset.inst 
        : btn.dataset.prodi;
      document.getElementById('edit_strata').value = btn.dataset.strata || '';
      document.getElementById('edit_body').value = btn.dataset.body || '';
      document.getElementById('edit_number').value = btn.dataset.number || '';
      document.getElementById('edit_rating').value = btn.dataset.rating || '';
      document.getElementById('edit_from').value = btn.dataset.from || '';
      document.getElementById('edit_until').value = btn.dataset.until || '';
      const info = btn.dataset.file 
        ? `<small class='text-muted'>File saat ini: ${btn.dataset.file}</small>`
        : `<small class='text-muted fst-italic'>Belum ada file diunggah.</small>`;
      document.getElementById('current_file_info').innerHTML = info;
      new bootstrap.Modal(document.getElementById('editModal')).show();
    });
  });

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

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