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

// tampilkan error (sementara biar debug mudah)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// === VARIABEL FILTER & PAGINASI ===
$filter_cycle = $_GET['cycle_id'] ?? '';
$filter_stage = $_GET['stage'] ?? '';
$filter_standard = $_GET['standard_id'] ?? '';
$search = trim($_GET['search'] ?? '');
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

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

if ($filter_cycle) { $where[] = "p.cycle_id = ?"; $params[] = $filter_cycle; }
if ($filter_standard) { $where[] = "p.standard_id = ?"; $params[] = $filter_standard; }
if ($filter_stage) { $where[] = "p.stage = ?"; $params[] = $filter_stage; }
if ($search) {
  $where[] = "(p.activity_title LIKE ? OR p.description LIKE ? OR p.notes LIKE ? OR p.responsible_unit LIKE ?)";
  $params = array_merge($params, array_fill(0, 4, "%$search%"));
}
$where_sql = $where ? "WHERE " . implode(" AND ", $where) : "";

// Hitung total data
$count_stmt = $pdo->prepare("SELECT COUNT(*) FROM spmi_ppepp p $where_sql");
$count_stmt->execute($params);
$total_rows = $count_stmt->fetchColumn();
$total_pages = ceil($total_rows / $limit);

// Ambil data PPEPP
$stmt = $pdo->prepare("
  SELECT p.*, c.cycle_name, s.title AS standard_name, u.full_name AS creator
  FROM spmi_ppepp p
  LEFT JOIN spmi_cycles c ON p.cycle_id = c.id
  LEFT JOIN spmi_standards s ON p.standard_id = s.id
  LEFT JOIN users u ON p.created_by = u.id
  $where_sql
  ORDER BY p.created_at DESC
  LIMIT $limit OFFSET $offset
");
$stmt->execute($params);
$ppepp = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Dropdown filter
$cycles = $pdo->query("SELECT id, cycle_name FROM spmi_cycles ORDER BY id DESC")->fetchAll();
$standards = $pdo->query("SELECT id, title FROM spmi_standards ORDER BY code ASC")->fetchAll();

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

// === CRUD HANDLING ===

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

    $stmt = $pdo->prepare("
      INSERT INTO spmi_ppepp 
      (cycle_id, standard_id, stage, activity_title, description, evidence_file, responsible_unit, status, notes, created_by)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([
      $_POST['cycle_id'],
      $_POST['standard_id'],
      $_POST['stage'],
      $_POST['activity_title'],
      $_POST['description'],
      $file_name,
      $_POST['responsible_unit'],
      $_POST['status'],
      $_POST['notes'],
      $_SESSION['user_id'] ?? null
    ]);

    echo "<script>Swal.fire('Berhasil', 'Data PPEPP berhasil ditambahkan', 'success').then(()=>location.href='spmi_ppepp.php');</script>";
    exit;
  } catch (Exception $e) {
    echo "<script>Swal.fire('Error', '".addslashes($e->getMessage())."', 'error');</script>";
  }
}

// Update
if (isset($_POST['update'])) {
  try {
    $id = (int)$_POST['edit_id'];
    $stmt = $pdo->prepare("SELECT evidence_file FROM spmi_ppepp WHERE id=?");
    $stmt->execute([$id]);
    $old_file = $stmt->fetchColumn();

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

    $stmt = $pdo->prepare("
      UPDATE spmi_ppepp 
      SET cycle_id=?, standard_id=?, stage=?, activity_title=?, description=?, evidence_file=?, responsible_unit=?, status=?, notes=?
      WHERE id=?
    ");
    $stmt->execute([
      $_POST['edit_cycle_id'],
      $_POST['edit_standard_id'],
      $_POST['edit_stage'],
      $_POST['edit_activity_title'],
      $_POST['edit_description'],
      $new_file,
      $_POST['edit_responsible_unit'],
      $_POST['edit_status'],
      $_POST['edit_notes'],
      $id
    ]);

    echo "<script>Swal.fire('Berhasil', 'Data PPEPP berhasil diperbarui', 'success').then(()=>location.href='spmi_ppepp.php');</script>";
    exit;
  } catch (Exception $e) {
    echo "<script>Swal.fire('Error', '".addslashes($e->getMessage())."', 'error');</script>";
  }
}

// Hapus
if (isset($_GET['delete'])) {
  $id = (int)$_GET['delete'];
  $stmt = $pdo->prepare("SELECT evidence_file FROM spmi_ppepp WHERE id=?");
  $stmt->execute([$id]);
  $file = $stmt->fetchColumn();
  if ($file && file_exists($upload_dir . $file)) unlink($upload_dir . $file);
  $stmt = $pdo->prepare("DELETE FROM spmi_ppepp WHERE id=?");
  $stmt->execute([$id]);
  echo "<script>Swal.fire('Dihapus', 'Data PPEPP berhasil dihapus', 'success').then(()=>location.href='spmi_ppepp.php');</script>";
  exit;
}
?>

<div class="container-fluid mt-3">
  <div class="card shadow p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4 class="mb-0"><i class="fa-solid fa-recycle text-success me-2"></i>Manajemen Tahapan PPEPP</h4>
      <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addModal">
        <i class="fa-solid fa-plus me-1"></i> Tambah PPEPP
      </button>
    </div>

    <!-- FILTER -->
    <form method="get" class="row g-2 mb-3 align-items-end">
      <div class="col-md-3">
        <label class="form-label mb-1">Siklus</label>
        <select name="cycle_id" class="form-select">
          <option value="">Semua Siklus</option>
          <?php foreach ($cycles as $c): ?>
            <option value="<?= $c['id'] ?>" <?= $filter_cycle==$c['id']?'selected':'' ?>><?= htmlspecialchars($c['cycle_name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label mb-1">Standar</label>
        <select name="standard_id" class="form-select">
          <option value="">Semua Standar</option>
          <?php foreach ($standards as $s): ?>
            <option value="<?= $s['id'] ?>" <?= $filter_standard==$s['id']?'selected':'' ?>><?= htmlspecialchars($s['title']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-2">
        <label class="form-label mb-1">Tahapan</label>
        <select name="stage" class="form-select">
          <option value="">Semua</option>
          <?php foreach (['penetapan','pelaksanaan','evaluasi','pengendalian','peningkatan'] as $st): ?>
            <option value="<?= $st ?>" <?= $filter_stage==$st?'selected':'' ?>><?= ucfirst($st) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label mb-1">Pencarian</label>
        <input type="text" name="search" class="form-control" placeholder="Cari kegiatan, unit, atau catatan..." value="<?= htmlspecialchars($search) ?>">
      </div>
      <div class="col-md-1 d-grid">
        <button type="submit" class="btn btn-outline-success"><i class="fa-solid fa-search"></i></button>
      </div>
      <div class="col-md-12 mt-2 text-end">
        <a href="spmi_ppepp.php" class="btn btn-outline-secondary btn-sm"><i class="fa-solid fa-rotate-left me-1"></i>Reset</a>
      </div>
    </form>

    <!-- TABLE -->
    <div class="table-responsive">
      <table class="table table-bordered align-middle">
        <thead class="table-success text-center">
          <tr>
            <th>No</th>
            <th>Siklus</th>
            <th>Standar</th>
            <th>Tahapan</th>
            <th>Judul Kegiatan</th>
            <th>Unit</th>
            <th>Status</th>
            <th>Bukti</th>
            <th>Aksi</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($ppepp): foreach ($ppepp as $i => $p): ?>
            <tr>
              <td class="text-center"><?= $offset + $i + 1 ?></td>
              <td><?= htmlspecialchars($p['cycle_name']) ?></td>
              <td><?= htmlspecialchars($p['standard_name']) ?></td>
              <td class="text-capitalize text-center"><?= htmlspecialchars($p['stage']) ?></td>
              <td><?= htmlspecialchars($p['activity_title']) ?></td>
              <td><?= htmlspecialchars($p['responsible_unit']) ?></td>
              <td class="text-center">
                <span class="badge bg-<?=
                  $p['status']=='selesai'?'success':($p['status']=='proses'?'warning':'secondary')
                ?>"><?= ucfirst($p['status']) ?></span>
              </td>
              <td class="text-center">
                <?php if ($p['evidence_file']): ?>
                  <a href="../uploads/ppepp/<?= htmlspecialchars($p['evidence_file']) ?>" target="_blank"><i class="fa-solid fa-file-lines"></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="<?= $p['id'] ?>"
                  data-cycle="<?= $p['cycle_id'] ?>"
                  data-standard="<?= $p['standard_id'] ?>"
                  data-stage="<?= $p['stage'] ?>"
                  data-title="<?= htmlspecialchars($p['activity_title']) ?>"
                  data-description="<?= htmlspecialchars($p['description']) ?>"
                  data-notes="<?= htmlspecialchars($p['notes']) ?>"
                  data-unit="<?= htmlspecialchars($p['responsible_unit']) ?>"
                  data-status="<?= $p['status'] ?>"
                  data-file="<?= htmlspecialchars($p['evidence_file']) ?>">
                  <i class="fa-solid fa-pen-to-square"></i></button>
                <button class="btn btn-sm btn-danger delete-btn" data-id="<?= $p['id'] ?>"><i class="fa-solid fa-trash"></i></button>
              </td>
            </tr>
          <?php endforeach; else: ?>
            <tr><td colspan="9" class="text-center text-muted">Belum ada data PPEPP.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>

    <!-- PAGINATION -->
    <?php if ($total_pages > 1): ?>
    <nav><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 ?>"><?= $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" 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 Tahapan PPEPP</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body">
        <div class="row">
          <div class="col-md-6">
            <label class="form-label">Siklus SPMI</label>
            <select name="cycle_id" class="form-select" required>
              <option value="">Pilih Siklus</option>
              <?php foreach ($cycles as $c): ?>
              <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['cycle_name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="col-md-6">
            <label class="form-label">Standar Mutu</label>
            <select name="standard_id" class="form-select" required>
              <option value="">Pilih Standar</option>
              <?php foreach ($standards as $s): ?>
              <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['title']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>

        <label class="form-label mt-3">Tahapan PPEPP</label>
        <select name="stage" class="form-select" required>
          <option value="penetapan">Penetapan</option>
          <option value="pelaksanaan">Pelaksanaan</option>
          <option value="evaluasi">Evaluasi</option>
          <option value="pengendalian">Pengendalian</option>
          <option value="peningkatan">Peningkatan</option>
        </select>

        <label class="form-label mt-3">Judul Kegiatan</label>
        <input type="text" name="activity_title" class="form-control" placeholder="Judul kegiatan PPEPP" required>

        <label class="form-label mt-3">Deskripsi / Uraian Kegiatan</label>
        <textarea name="description" class="form-control" rows="3" placeholder="Deskripsi singkat kegiatan"></textarea>

        <label class="form-label mt-3">Catatan / Hasil / Evaluasi</label>
        <textarea name="notes" class="form-control" rows="3" placeholder="Catatan hasil kegiatan, temuan, atau tindak lanjut"></textarea>

        <label class="form-label mt-3">Unit Penanggung Jawab</label>
        <input type="text" name="responsible_unit" class="form-control" placeholder="Contoh: LPM, Prodi, Fakultas">

        <label class="form-label mt-3">Status</label>
        <select name="status" class="form-select">
          <option value="draft">Draft</option>
          <option value="proses">Proses</option>
          <option value="selesai">Selesai</option>
        </select>

        <label class="form-label mt-3">Upload Bukti Kegiatan (PDF/JPG/PNG)</label>
        <input type="file" name="evidence_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 Tahapan PPEPP</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">

        <div class="row">
          <div class="col-md-6">
            <label class="form-label">Siklus SPMI</label>
            <select name="edit_cycle_id" id="edit_cycle_id" class="form-select" required>
              <?php foreach ($cycles as $c): ?>
              <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['cycle_name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="col-md-6">
            <label class="form-label">Standar Mutu</label>
            <select name="edit_standard_id" id="edit_standard_id" class="form-select" required>
              <?php foreach ($standards as $s): ?>
              <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['title']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>

        <label class="form-label mt-3">Tahapan PPEPP</label>
        <select name="edit_stage" id="edit_stage" class="form-select" required>
          <option value="penetapan">Penetapan</option>
          <option value="pelaksanaan">Pelaksanaan</option>
          <option value="evaluasi">Evaluasi</option>
          <option value="pengendalian">Pengendalian</option>
          <option value="peningkatan">Peningkatan</option>
        </select>

        <label class="form-label mt-3">Judul Kegiatan</label>
        <input type="text" name="edit_activity_title" id="edit_activity_title" class="form-control" required>

        <label class="form-label mt-3">Deskripsi / Uraian Kegiatan</label>
        <textarea name="edit_description" id="edit_description" class="form-control" rows="3"></textarea>

        <label class="form-label mt-3">Catatan / Hasil / Evaluasi</label>
        <textarea name="edit_notes" id="edit_notes" class="form-control" rows="3"></textarea>

        <label class="form-label mt-3">Unit Penanggung Jawab</label>
        <input type="text" name="edit_responsible_unit" id="edit_responsible_unit" class="form-control">

        <label class="form-label mt-3">Status</label>
        <select name="edit_status" id="edit_status" class="form-select">
          <option value="draft">Draft</option>
          <option value="proses">Proses</option>
          <option value="selesai">Selesai</option>
        </select>

        <label class="form-label mt-3">Upload Bukti Baru (PDF/JPG/PNG)</label>
        <input type="file" name="edit_evidence_file" id="edit_evidence_file" class="form-control" accept=".pdf,.jpg,.jpeg,.png">
        <div id="current_file_info" class="mt-2 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>


<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
  // edit modal
  document.querySelectorAll('.edit-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      document.getElementById('edit_id').value = btn.dataset.id;
      document.getElementById('edit_cycle_id').value = btn.dataset.cycle;
      document.getElementById('edit_standard_id').value = btn.dataset.standard;
      document.getElementById('edit_stage').value = btn.dataset.stage;
      document.getElementById('edit_activity_title').value = btn.dataset.title;
      document.getElementById('edit_description').value = btn.dataset.description;
      document.getElementById('edit_notes').value = btn.dataset.notes;
      document.getElementById('edit_responsible_unit').value = btn.dataset.unit;
      document.getElementById('edit_status').value = btn.dataset.status;
      document.getElementById('current_file_info').innerHTML = btn.dataset.file
        ? `<small class='text-muted'>File saat ini: ${btn.dataset.file}</small>`
        : `<small class='text-muted fst-italic'>Belum ada file.</small>`;
      new bootstrap.Modal(document.getElementById('editModal')).show();
    });
  });

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

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

