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

// === CRUD HANDLING ===

// Tambah Siklus
if (isset($_POST['add'])) {
  $stmt = $pdo->prepare("INSERT INTO spmi_cycles (cycle_name, period_start, period_end, notes, status, created_by)
                         VALUES (?, ?, ?, ?, 'aktif', ?)");
  $stmt->execute([
    $_POST['cycle_name'],
    $_POST['period_start'],
    $_POST['period_end'],
    $_POST['notes'],
    $_SESSION['user_id'] ?? null
  ]);
  echo "<script>Swal.fire('Berhasil', 'Siklus SPMI berhasil ditambahkan', 'success')
        .then(()=>location.href='spmi_cycles.php');</script>";
  exit;
}

// Update Siklus
if (isset($_POST['update'])) {
  $stmt = $pdo->prepare("UPDATE spmi_cycles 
                         SET cycle_name=?, period_start=?, period_end=?, notes=?, status=? 
                         WHERE id=?");
  $stmt->execute([
    $_POST['edit_cycle_name'],
    $_POST['edit_period_start'],
    $_POST['edit_period_end'],
    $_POST['edit_notes'],
    $_POST['edit_status'],
    $_POST['edit_id']
  ]);
  echo "<script>Swal.fire('Berhasil', 'Siklus SPMI berhasil diperbarui', 'success')
        .then(()=>location.href='spmi_cycles.php');</script>";
  exit;
}

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

// === Ambil data semua siklus ===
$stmt = $pdo->query("SELECT c.*, u.full_name AS creator 
                     FROM spmi_cycles c 
                     LEFT JOIN users u ON c.created_by = u.id 
                     ORDER BY c.created_at DESC");
$cycles = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<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-recycle text-success me-2"></i>Siklus SPMI (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 Siklus
      </button>
    </div>

    <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>Nama Siklus</th>
            <th>Periode</th>
            <th>Status</th>
            <th>Keterangan</th>
            <th>Dibuat Oleh</th>
            <th>Tanggal Dibuat</th>
            <th>Aksi</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($cycles): foreach ($cycles as $i => $c): ?>
          <tr>
            <td class="text-center"><?= $i + 1 ?></td>
            <td><?= htmlspecialchars($c['cycle_name']) ?></td>
            <td class="text-center">
              <?= htmlspecialchars($c['period_start']) ?> s.d <?= htmlspecialchars($c['period_end']) ?>
            </td>
            <td class="text-center">
              <span class="badge bg-<?= $c['status']=='aktif'?'success':($c['status']=='selesai'?'secondary':'dark') ?>">
                <?= ucfirst($c['status']) ?>
              </span>
            </td>
            <td><?= htmlspecialchars($c['notes'] ?: '-') ?></td>
            <td><?= htmlspecialchars($c['creator'] ?: '-') ?></td>
            <td class="text-center"><?= date('d/m/Y', strtotime($c['created_at'])) ?></td>
            <td class="text-center">
              <button class="btn btn-sm btn-primary edit-btn"
                      data-id="<?= $c['id'] ?>"
                      data-name="<?= htmlspecialchars($c['cycle_name']) ?>"
                      data-start="<?= $c['period_start'] ?>"
                      data-end="<?= $c['period_end'] ?>"
                      data-status="<?= $c['status'] ?>"
                      data-notes="<?= htmlspecialchars($c['notes']) ?>">
                <i class="fa-solid fa-pen-to-square"></i>
              </button>
              <button class="btn btn-sm btn-danger delete-btn" data-id="<?= $c['id'] ?>">
                <i class="fa-solid fa-trash"></i>
              </button>
            </td>
          </tr>
          <?php endforeach; else: ?>
          <tr><td colspan="8" class="text-center text-muted">Belum ada data siklus.</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" 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 Siklus SPMI</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <label class="form-label">Nama Siklus</label>
        <input type="text" name="cycle_name" class="form-control" placeholder="Contoh: Siklus SPMI 2025" required>

        <div class="row mt-2">
          <div class="col-md-6">
            <label class="form-label">Periode Mulai</label>
            <input type="date" name="period_start" class="form-control" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">Periode Selesai</label>
            <input type="date" name="period_end" class="form-control" required>
          </div>
        </div>

        <label class="form-label mt-2">Catatan / Deskripsi</label>
        <textarea name="notes" class="form-control" rows="3" placeholder="Catatan tambahan..."></textarea>
      </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 Siklus SPMI</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">Nama Siklus</label>
        <input type="text" name="edit_cycle_name" id="edit_cycle_name" class="form-control" required>

        <div class="row mt-2">
          <div class="col-md-6">
            <label class="form-label">Periode Mulai</label>
            <input type="date" name="edit_period_start" id="edit_period_start" class="form-control" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">Periode Selesai</label>
            <input type="date" name="edit_period_end" id="edit_period_end" class="form-control" required>
          </div>
        </div>

        <label class="form-label mt-2">Status Siklus</label>
        <select name="edit_status" id="edit_status" class="form-select">
          <option value="aktif">Aktif</option>
          <option value="selesai">Selesai</option>
          <option value="arsip">Arsip</option>
        </select>

        <label class="form-label mt-2">Catatan / Deskripsi</label>
        <textarea name="edit_notes" id="edit_notes" class="form-control" rows="3"></textarea>
      </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 Data ===
  document.querySelectorAll('.edit-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      document.getElementById('edit_id').value = btn.dataset.id;
      document.getElementById('edit_cycle_name').value = btn.dataset.name;
      document.getElementById('edit_period_start').value = btn.dataset.start;
      document.getElementById('edit_period_end').value = btn.dataset.end;
      document.getElementById('edit_status').value = btn.dataset.status;
      document.getElementById('edit_notes').value = btn.dataset.notes || '';
      new bootstrap.Modal(document.getElementById('editModal')).show();
    });
  });

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

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