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

error_reporting(E_ALL);
ini_set('display_errors', 1);

// === VARIABEL FILTER & PAGINASI ===
$filter_ppepp = $_GET['ppepp_id'] ?? '';
$filter_type = $_GET['action_type'] ?? '';
$filter_status = $_GET['status'] ?? '';
$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_ppepp) { $where[] = "a.ppepp_id = ?"; $params[] = $filter_ppepp; }
if ($filter_type) { $where[] = "a.action_type = ?"; $params[] = $filter_type; }
if ($filter_status) { $where[] = "a.status = ?"; $params[] = $filter_status; }
if ($search) {
  $where[] = "(a.action_plan LIKE ? OR a.notes LIKE ?)";
  $params = array_merge($params, ["%$search%", "%$search%"]);
}
$where_sql = $where ? "WHERE " . implode(" AND ", $where) : "";

// === DATA & PAGINASI ===
$count_stmt = $pdo->prepare("SELECT COUNT(*) FROM spmi_actions a $where_sql");
$count_stmt->execute($params);
$total_rows = $count_stmt->fetchColumn();
$total_pages = ceil($total_rows / $limit);

$stmt = $pdo->prepare("
  SELECT a.*, p.activity_title AS ppepp_title, u.full_name AS creator
  FROM spmi_actions a
  LEFT JOIN spmi_ppepp p ON a.ppepp_id = p.id
  LEFT JOIN users u ON a.created_by = u.id
  $where_sql
  ORDER BY a.created_at DESC
  LIMIT $limit OFFSET $offset
");
$stmt->execute($params);
$actions = $stmt->fetchAll(PDO::FETCH_ASSOC);

// === Dropdown data ===
$ppepp = $pdo->query("SELECT id, activity_title FROM spmi_ppepp ORDER BY id DESC")->fetchAll();

// === Upload folder ===
$upload_dir = __DIR__ . '/../uploads/actions/';
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_actions (ppepp_id, action_type, action_plan, due_date, status, evidence_file, notes, created_by)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([
      $_POST['ppepp_id'],
      $_POST['action_type'],
      $_POST['action_plan'],
      $_POST['due_date'],
      $_POST['status'],
      $file_name,
      $_POST['notes'],
      $_SESSION['user_id'] ?? null
    ]);

    echo "<script>Swal.fire('Berhasil', 'Tindakan berhasil ditambahkan', 'success').then(()=>location.href='spmi_actions.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_actions 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_actions 
      SET ppepp_id=?, action_type=?, action_plan=?, due_date=?, status=?, evidence_file=?, notes=? 
      WHERE id=?
    ");
    $stmt->execute([
      $_POST['edit_ppepp_id'],
      $_POST['edit_action_type'],
      $_POST['edit_action_plan'],
      $_POST['edit_due_date'],
      $_POST['edit_status'],
      $new_file,
      $_POST['edit_notes'],
      $id
    ]);

    echo "<script>Swal.fire('Berhasil', 'Tindakan berhasil diperbarui', 'success').then(()=>location.href='spmi_actions.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_actions 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_actions WHERE id=?");
  $stmt->execute([$id]);
  echo "<script>Swal.fire('Dihapus', 'Tindakan berhasil dihapus', 'success').then(()=>location.href='spmi_actions.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 flex-wrap gap-2">
      <h4 class="mb-0"><i class="fa-solid fa-arrow-trend-up text-success me-2"></i>Peningkatan Mutu (Tindakan 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 Tindakan
      </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">PPEPP</label>
        <select name="ppepp_id" class="form-select">
          <option value="">Semua PPEPP</option>
          <?php foreach ($ppepp as $p): ?>
          <option value="<?= $p['id'] ?>" <?= $filter_ppepp==$p['id']?'selected':'' ?>><?= htmlspecialchars($p['activity_title']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-2">
        <label class="form-label mb-1">Jenis Tindakan</label>
        <select name="action_type" class="form-select">
          <option value="">Semua</option>
          <?php foreach (['koreksi','pencegahan','peningkatan'] as $t): ?>
          <option value="<?= $t ?>" <?= $filter_type==$t?'selected':'' ?>><?= ucfirst($t) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-2">
        <label class="form-label mb-1">Status</label>
        <select name="status" class="form-select">
          <option value="">Semua</option>
          <?php foreach (['open','progress','done'] as $st): ?>
          <option value="<?= $st ?>" <?= $filter_status==$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 rencana aksi 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_actions.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 shadow-sm rounded">
      <table class="table table-bordered align-middle">
        <thead class="table-success text-center">
          <tr>
            <th>No</th>
            <th>PPEPP</th>
            <th>Jenis</th>
            <th>Rencana Aksi</th>
            <th>Batas Waktu</th>
            <th>Status</th>
            <th>Bukti</th>
            <th>Aksi</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($actions): foreach ($actions as $i => $a): ?>
          <tr>
            <td class="text-center"><?= $offset + $i + 1 ?></td>
            <td><?= htmlspecialchars($a['ppepp_title']) ?></td>
            <td class="text-capitalize text-center"><?= htmlspecialchars($a['action_type']) ?></td>
            <td><?= nl2br(htmlspecialchars($a['action_plan'])) ?></td>
            <td class="text-center"><?= htmlspecialchars($a['due_date']) ?></td>
            <td class="text-center">
              <span class="badge bg-<?=
                $a['status']=='done'?'success':($a['status']=='progress'?'warning':'secondary')
              ?>"><?= ucfirst($a['status']) ?></span>
            </td>
            <td class="text-center">
              <?php if ($a['evidence_file']): ?>
              <a href="../uploads/actions/<?= htmlspecialchars($a['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="<?= $a['id'] ?>"
                      data-ppepp="<?= $a['ppepp_id'] ?>"
                      data-type="<?= $a['action_type'] ?>"
                      data-plan="<?= htmlspecialchars($a['action_plan']) ?>"
                      data-date="<?= $a['due_date'] ?>"
                      data-status="<?= $a['status'] ?>"
                      data-notes="<?= htmlspecialchars($a['notes']) ?>"
                      data-file="<?= htmlspecialchars($a['evidence_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="8" class="text-center text-muted">Tidak ada data tindakan ditemukan.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>

    <!-- PAGINATION -->
    <?php if ($total_pages > 1): ?>
    <nav class="mt-3">
      <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 Tindakan Peningkatan Mutu</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">Terkait Tahapan PPEPP</label>
            <select name="ppepp_id" class="form-select" required>
              <option value="">Pilih PPEPP</option>
              <?php foreach ($ppepp as $p): ?>
              <option value="<?= $p['id'] ?>"><?= htmlspecialchars($p['activity_title']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="col-md-6">
            <label class="form-label">Jenis Tindakan</label>
            <select name="action_type" class="form-select" required>
              <option value="koreksi">Koreksi</option>
              <option value="pencegahan">Pencegahan</option>
              <option value="peningkatan">Peningkatan</option>
            </select>
          </div>
        </div>

        <label class="form-label mt-3">Rencana Aksi / Langkah Perbaikan</label>
        <textarea name="action_plan" class="form-control" rows="3" placeholder="Tuliskan langkah tindak lanjut atau perbaikan" required></textarea>

        <label class="form-label mt-3">Batas Waktu Penyelesaian</label>
        <input type="date" name="due_date" class="form-control">

        <label class="form-label mt-3">Status</label>
        <select name="status" class="form-select">
          <option value="open">Open</option>
          <option value="progress">Progress</option>
          <option value="done">Done</option>
        </select>

        <label class="form-label mt-3">Catatan / Hasil Pelaksanaan</label>
        <textarea name="notes" class="form-control" rows="3" placeholder="Tambahkan catatan hasil, tindak lanjut, atau kendala"></textarea>

        <label class="form-label mt-3">Upload Bukti Pelaksanaan (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 Tindakan Peningkatan Mutu</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">Terkait PPEPP</label>
            <select name="edit_ppepp_id" id="edit_ppepp_id" class="form-select" required>
              <?php foreach ($ppepp as $p): ?>
              <option value="<?= $p['id'] ?>"><?= htmlspecialchars($p['activity_title']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="col-md-6">
            <label class="form-label">Jenis Tindakan</label>
            <select name="edit_action_type" id="edit_action_type" class="form-select" required>
              <option value="koreksi">Koreksi</option>
              <option value="pencegahan">Pencegahan</option>
              <option value="peningkatan">Peningkatan</option>
            </select>
          </div>
        </div>

        <label class="form-label mt-3">Rencana Aksi / Langkah Perbaikan</label>
        <textarea name="edit_action_plan" id="edit_action_plan" class="form-control" rows="3" required></textarea>

        <label class="form-label mt-3">Batas Waktu Penyelesaian</label>
        <input type="date" name="edit_due_date" id="edit_due_date" class="form-control">

        <label class="form-label mt-3">Status</label>
        <select name="edit_status" id="edit_status" class="form-select">
          <option value="open">Open</option>
          <option value="progress">Progress</option>
          <option value="done">Done</option>
        </select>

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

        <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>
document.addEventListener('DOMContentLoaded', () => {
  // Edit
  document.querySelectorAll('.edit-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      document.getElementById('edit_id').value = btn.dataset.id;
      document.getElementById('edit_ppepp_id').value = btn.dataset.ppepp;
      document.getElementById('edit_action_type').value = btn.dataset.type;
      document.getElementById('edit_action_plan').value = btn.dataset.plan;
      document.getElementById('edit_due_date').value = btn.dataset.date;
      document.getElementById('edit_status').value = btn.dataset.status;
      document.getElementById('edit_notes').value = btn.dataset.notes;
      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
  document.querySelectorAll('.delete-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      Swal.fire({
        title: 'Hapus Data?',
        text: 'Data tindakan akan dihapus permanen!',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Ya, hapus!',
        cancelButtonText: 'Batal'
      }).then(r => {
        if (r.isConfirmed) location.href = 'spmi_actions.php?delete=' + btn.dataset.id;
      });
    });
  });
});
</script>

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