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

// ==== KONFIGURASI ====
$limit = 10;
$page = max(1, intval($_GET['page'] ?? 1));
$offset = ($page - 1) * $limit;
$q = trim($_GET['q'] ?? '');
$status = $_GET['status'] ?? '';

// ==== FILTER ====
$where = [];
$params = [];

if ($q !== '') {
  $where[] = "a.audit_title LIKE :q";
  $params[':q'] = "%$q%";
}
if ($status !== '') {
  $where[] = "a.status = :status";
  $params[':status'] = $status;
}
$whereSql = $where ? "WHERE " . implode(" AND ", $where) : "";

// ==== PAGINASI & DATA ====
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM audits a $whereSql");
$countStmt->execute($params);
$totalData = $countStmt->fetchColumn();
$totalPages = ceil($totalData / $limit);

// Query audit + temuan (efisien pakai LEFT JOIN + GROUP)
$sql = "
  SELECT 
    a.*,
    u.full_name AS creator,
    COALESCE(COUNT(f.id), 0) AS total_findings,
    COALESCE(SUM(f.status = 'closed'), 0) AS closed_findings,
    CASE
      WHEN COUNT(f.id) = 0 AND a.status = 'completed' THEN 100
      WHEN COUNT(f.id) = 0 THEN 0
      ELSE ROUND(SUM(f.status = 'closed') / COUNT(f.id) * 100)
    END AS progress
  FROM audits a
  LEFT JOIN users u ON a.created_by = u.id
  LEFT JOIN audit_findings f ON f.audit_id = a.id
  $whereSql
  GROUP BY a.id
  ORDER BY a.created_at DESC
  LIMIT $limit OFFSET $offset
";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$audits = $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-warning { background-color: var(--coklat); border: none; }
.progress { height: 8px; border-radius: 6px; }
.progress-bar { transition: width 0.4s ease; }
</style>

<div class="container-fluid mt-4">
  <div class="card shadow-sm">
    <div class="card-body">
      <div class="d-flex justify-content-between align-items-center mb-3">
        <h4 class="fw-bold text-success"><i class="fa-solid fa-clipboard-check me-2"></i>Manajemen Audit Mutu Internal</h4>
        <div>
          <a href="export/audit_excel.php" class="btn btn-success btn-sm me-1"><i class="fa-solid fa-file-excel"></i> Excel</a>
          <a href="export/audit_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="#addModal">
            <i class="fa-solid fa-plus"></i> Tambah
          </button>
        </div>
      </div>

      <!-- Filter -->
      <form method="get" class="row g-2 mb-3">
        <div class="col-md-6">
          <input type="text" name="q" class="form-control" placeholder="Cari audit..." value="<?= htmlspecialchars($q) ?>">
        </div>
        <div class="col-md-4">
          <select name="status" class="form-select">
            <option value="">-- Semua Status --</option>
            <option value="draft" <?= $status=='draft'?'selected':'' ?>>Draft</option>
            <option value="ongoing" <?= $status=='ongoing'?'selected':'' ?>>Ongoing</option>
            <option value="completed" <?= $status=='completed'?'selected':'' ?>>Completed</option>
          </select>
        </div>
        <div class="col-md-1">
          <button class="btn btn-success w-100"><i class="fa-solid fa-filter"></i></button>
        </div>
        <div class="col-md-1">
          <a href="audit.php" class="btn btn-secondary w-100"><i class="fa-solid fa-rotate-left"></i></a>
        </div>
      </form>

      <!-- Table -->
      <div class="table-responsive">
        <table class="table table-hover align-middle text-center">
          <thead>
            <tr>
              <th>No</th>
              <th>Judul Audit</th>
              <th>Periode</th>
              <th>Status</th>
              <th>Progress</th>
              <th>Pembuat</th>
              <th>Dibuat</th>
              <th>Aksi</th>
            </tr>
          </thead>
          <tbody>
            <?php if ($audits): $no = $offset + 1; foreach ($audits as $row): ?>
            <?php
              $progress = (int)$row['progress'];
              $barColor = $progress == 100 ? 'bg-success' : ($progress > 50 ? 'bg-warning' : 'bg-danger');
            ?>
            <tr>
              <td><?= $no++ ?></td>
              <td class="text-start"><?= htmlspecialchars($row['audit_title']) ?></td>
              <td><?= date('d M Y', strtotime($row['audit_period_start'])) ?> s.d <?= date('d M Y', strtotime($row['audit_period_end'])) ?></td>
              <td>
                <span class="badge bg-<?= $row['status']=='completed'?'success':($row['status']=='ongoing'?'warning':'secondary') ?>">
                  <?= ucfirst($row['status']) ?>
                </span>
              </td>
              <td>
                <div class="progress">
                  <div class="progress-bar <?= $barColor ?>" style="width: <?= $progress ?>%"></div>
                </div>
                <small><?= $progress ?>%</small>
              </td>
              <td><?= htmlspecialchars($row['creator'] ?? '-') ?></td>
              <td><?= date('d M Y', strtotime($row['created_at'])) ?></td>
              <td>
                <button class="btn btn-sm btn-info findings-btn" data-id="<?= $row['id'] ?>" data-title="<?= htmlspecialchars($row['audit_title']) ?>">
                  <i class="fa-solid fa-list-check"></i>
                </button>
                <button class="btn btn-sm btn-primary edit-btn"
                  data-id="<?= $row['id'] ?>"
                  data-title="<?= htmlspecialchars($row['audit_title']) ?>"
                  data-start="<?= $row['audit_period_start'] ?>"
                  data-end="<?= $row['audit_period_end'] ?>"
                  data-status="<?= $row['status'] ?>"
                  data-summary="<?= htmlspecialchars($row['summary']) ?>">
                  <i class="fa-solid fa-pen-to-square"></i>
                </button>
                <button class="btn btn-sm btn-danger delete-btn" data-id="<?= $row['id'] ?>">
                  <i class="fa-solid fa-trash"></i>
                </button>
              </td>
            </tr>
            <?php endforeach; else: ?>
            <tr><td colspan="8" class="text-muted">Belum ada audit.</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>

      <!-- Paginasi -->
      <nav>
        <ul class="pagination justify-content-center">
          <?php for ($i = 1; $i <= $totalPages; $i++): ?>
          <li class="page-item <?= $i == $page ? 'active' : '' ?>">
            <a class="page-link" href="?page=<?= $i ?>&q=<?= urlencode($q) ?>&status=<?= urlencode($status) ?>"><?= $i ?></a>
          </li>
          <?php endfor; ?>
        </ul>
      </nav>

    </div>
  </div>
</div>

<!-- Modal Tambah -->
<div class="modal fade" id="addModal" tabindex="-1">
  <div class="modal-dialog">
    <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 Audit</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <label class="form-label">Judul Audit</label>
        <input type="text" name="audit_title" class="form-control" required>

        <label class="form-label mt-2">Periode Mulai</label>
        <input type="date" name="audit_period_start" class="form-control">

        <label class="form-label mt-2">Periode Selesai</label>
        <input type="date" name="audit_period_end" class="form-control">

        <label class="form-label mt-2">Status</label>
        <select name="status" class="form-select">
          <option value="draft">Draft</option>
          <option value="ongoing">Ongoing</option>
          <option value="completed">Completed</option>
        </select>

        <label class="form-label mt-2">Ringkasan</label>
        <textarea name="summary" 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="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">
    <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 Audit</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">Judul Audit</label>
        <input type="text" name="edit_title" id="edit_title" class="form-control" required>

        <label class="form-label mt-2">Periode Mulai</label>
        <input type="date" name="edit_start" id="edit_start" class="form-control">

        <label class="form-label mt-2">Periode Selesai</label>
        <input type="date" name="edit_end" id="edit_end" class="form-control">

        <label class="form-label mt-2">Status</label>
        <select name="edit_status" id="edit_status" class="form-select">
          <option value="draft">Draft</option>
          <option value="ongoing">Ongoing</option>
          <option value="completed">Completed</option>
        </select>

        <label class="form-label mt-2">Ringkasan</label>
        <textarea name="edit_summary" id="edit_summary" 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>

<!-- Modal Temuan Audit -->
<div class="modal fade" id="findingsModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header bg-info text-white">
        <h5 class="modal-title">
          <i class="fa-solid fa-list-check me-2"></i>
          Temuan Audit: <span id="findingsAuditTitle"></span>
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body">
        <!-- Tombol tambah + counter -->
        <div class="mb-3 d-flex justify-content-between align-items-center">
          <button class="btn btn-success btn-sm" id="btnAddFinding">
            <i class="fa-solid fa-plus me-1"></i> Tambah Temuan
          </button>
          <div id="findingsCount" class="text-muted small"></div>
        </div>

        <!-- List temuan -->
        <div id="findingsList" class="mb-3">
          <div class="text-center text-muted">Belum ada temuan.</div>
        </div>

        <!-- Form Tambah/Edit (hidden, di-toggle via JS) -->
        <div id="findingFormWrap" style="display:none; margin-top:1rem;">
          <form id="findingForm">
            <input type="hidden" name="id" id="finding_id">
            <input type="hidden" name="audit_id" id="finding_audit_id">

            <div class="mb-2">
              <label class="form-label">Judul Temuan</label>
              <input type="text" id="finding_title" name="finding_title" class="form-control" required>
            </div>

            <div class="mb-2">
              <label class="form-label">Deskripsi</label>
              <textarea id="finding_description" name="description" class="form-control" rows="3"></textarea>
            </div>

            <div class="row">
              <div class="col-md-4 mb-2">
                <label class="form-label">Keparahan</label>
                <select id="finding_severity" name="severity" class="form-select">
                  <option value="minor">Minor</option>
                  <option value="major">Major</option>
                  <option value="critical">Critical</option>
                </select>
              </div>
              <div class="col-md-4 mb-2">
                <label class="form-label">Unit Bertanggungjawab</label>
                <input type="text" id="finding_unit" name="responsible_unit" class="form-control">
              </div>
              <div class="col-md-4 mb-2">
                <label class="form-label">Batas Waktu</label>
                <input type="date" id="finding_due" name="due_date" class="form-control">
              </div>
            </div>

            <div class="mb-2">
              <label class="form-label">Rekomendasi</label>
              <textarea id="finding_recommendation" name="recommendation" class="form-control" rows="2"></textarea>
            </div>

            <div class="mb-2">
              <label class="form-label">Status Temuan</label>
              <select id="finding_status" name="status" class="form-select">
                <option value="open">Open</option>
                <option value="in_progress">In Progress</option>
                <option value="closed">Closed</option>
              </select>
            </div>

            <div class="d-flex justify-content-end gap-2">
              <button type="button" class="btn btn-secondary" id="cancelFinding">Batal</button>
              <button type="submit" class="btn btn-primary" id="saveFinding">Simpan</button>
            </div>
          </form>
        </div>

      </div>
    </div>
  </div>
</div>

<?php
// ==== Proses CRUD ====

// Tambah
if (isset($_POST['add'])) {
  $stmt = $pdo->prepare("INSERT INTO audits (audit_title, audit_period_start, audit_period_end, status, summary, created_by) VALUES (?, ?, ?, ?, ?, ?)");
  $stmt->execute([
    $_POST['audit_title'],
    $_POST['audit_period_start'],
    $_POST['audit_period_end'],
    $_POST['status'],
    $_POST['summary'],
    $_SESSION['user_id'] ?? null
  ]);
  echo "<script>Swal.fire('Berhasil', 'Audit berhasil ditambahkan', 'success').then(()=>location.href='audit.php');</script>";
}

// Update
if (isset($_POST['update'])) {
  $stmt = $pdo->prepare("UPDATE audits SET audit_title=?, audit_period_start=?, audit_period_end=?, status=?, summary=? WHERE id=?");
  $stmt->execute([
    $_POST['edit_title'],
    $_POST['edit_start'],
    $_POST['edit_end'],
    $_POST['edit_status'],
    $_POST['edit_summary'],
    $_POST['edit_id']
  ]);
  echo "<script>Swal.fire('Berhasil', 'Data audit diperbarui', 'success').then(()=>location.href='audit.php');</script>";
}

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

<script>
document.addEventListener('DOMContentLoaded', () => {
  // ==== UTILITAS AMAN ====
  function escapeHtml(str) {
    if (!str) return '';
    return String(str)
      .replaceAll('&', '&amp;')
      .replaceAll('<', '&lt;')
      .replaceAll('>', '&gt;')
      .replaceAll('"', '&quot;')
      .replaceAll("'", '&#039;');
  }

  // ==== MODAL TEMUAN ====
  document.querySelectorAll('.findings-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      const auditId = btn.dataset.id;
      const title = btn.dataset.title;

      const modalEl = document.getElementById('findingsModal');
      const titleEl = document.getElementById('findingsAuditTitle');
      const auditInput = document.getElementById('finding_audit_id');
      const formWrap = document.getElementById('findingFormWrap');

      // Cek elemen modal ada
      if (!modalEl || !titleEl || !auditInput) {
        console.error('Modal Temuan belum dimuat di halaman.');
        Swal.fire('Error', 'Modal temuan tidak ditemukan di halaman.', 'error');
        return;
      }

      // Siapkan modal
      titleEl.textContent = title;
      auditInput.value = auditId;
      document.getElementById('findingForm').reset();
      formWrap.style.display = 'none';

      // Tampilkan modal & muat temuan
      new bootstrap.Modal(modalEl).show();
      loadFindings(auditId);
    });
  });

  // ==== LOAD DAFTAR TEMUAN ====
  function loadFindings(auditId) {
    const listContainer = document.getElementById('findingsList');
    const countEl = document.getElementById('findingsCount');

    listContainer.innerHTML = '<div class="text-center text-muted">Memuat...</div>';

    fetch('proses/audit_findings_list.php?audit_id=' + encodeURIComponent(auditId))
      .then(r => r.json())
      .then(data => {
        if (!data.success) {
          listContainer.innerHTML = '<div class="text-danger">Gagal memuat temuan.</div>';
          return;
        }

        const list = data.data;
        countEl.textContent = list.length + ' temuan';

        if (list.length === 0) {
          listContainer.innerHTML = '<div class="text-muted">Belum ada temuan.</div>';
          return;
        }

        let html = '<div class="list-group">';
        list.forEach(f => {
          const badge = f.status === 'closed'
            ? '<span class="badge bg-success ms-2">Closed</span>'
            : f.status === 'in_progress'
              ? '<span class="badge bg-warning ms-2">In Progress</span>'
              : '<span class="badge bg-secondary ms-2">Open</span>';

          html += `
            <div class="list-group-item">
              <div class="d-flex justify-content-between align-items-start">
                <div class="me-3">
                  <strong>${escapeHtml(f.finding_title)}</strong> ${badge}
                  <div class="small text-muted mt-1">${f.severity} • ${f.responsible_unit || '-'} • due ${f.due_date || '-'}</div>
                  <div class="mt-2">${escapeHtml(f.description || '')}</div>
                  <div class="mt-1"><em>Rekomendasi:</em> ${escapeHtml(f.recommendation || '')}</div>
                </div>
                <div class="text-end">
                  <button class="btn btn-sm btn-primary btnEditFinding" data-id="${f.id}" title="Edit"><i class="fa-solid fa-pen-to-square"></i></button>
                  <button class="btn btn-sm btn-danger btnDeleteFinding" data-id="${f.id}" title="Hapus"><i class="fa-solid fa-trash"></i></button>
                </div>
              </div>
            </div>`;
        });
        html += '</div>';
        listContainer.innerHTML = html;

        // Event tombol edit dan hapus
        document.querySelectorAll('.btnEditFinding').forEach(b => {
          b.addEventListener('click', () => editFinding(b.dataset.id));
        });
        document.querySelectorAll('.btnDeleteFinding').forEach(b => {
          b.addEventListener('click', () => deleteFinding(b.dataset.id));
        });
      })
      .catch(err => {
        console.error(err);
        listContainer.innerHTML = '<div class="text-danger">Terjadi kesalahan.</div>';
      });
  }

  // ==== TAMBAH TEMUAN ====
  const btnAdd = document.getElementById('btnAddFinding');
  if (btnAdd) {
    btnAdd.addEventListener('click', () => {
      const form = document.getElementById('findingForm');
      form.reset();
      document.getElementById('finding_id').value = '';
      document.getElementById('finding_status').value = 'open';
      document.getElementById('findingFormWrap').style.display = 'block';
    });
  }

  // ==== BATAL ====
  const cancelBtn = document.getElementById('cancelFinding');
  if (cancelBtn) {
    cancelBtn.addEventListener('click', () => {
      document.getElementById('findingFormWrap').style.display = 'none';
    });
  }

  // ==== SUBMIT FORM (ADD / EDIT) ====
  const form = document.getElementById('findingForm');
  if (form) {
    form.addEventListener('submit', e => {
      e.preventDefault();
      const data = new FormData(form);
      const url = data.get('id') ? 'proses/audit_findings_edit.php' : 'proses/audit_findings_add.php';

      fetch(url, { method: 'POST', body: data })
        .then(r => r.json())
        .then(res => {
          if (res.success) {
            Swal.fire('Berhasil', res.message, 'success');
            document.getElementById('findingFormWrap').style.display = 'none';
            loadFindings(data.get('audit_id'));
          } else {
            Swal.fire('Error', res.message || 'Gagal menyimpan', 'error');
          }
        })
        .catch(err => {
          console.error(err);
          Swal.fire('Error', 'Terjadi kesalahan saat menyimpan', 'error');
        });
    });
  }

  // ==== EDIT TEMUAN ====
  function editFinding(id) {
    fetch('proses/audit_findings_get.php?id=' + encodeURIComponent(id))
      .then(r => r.json())
      .then(res => {
        if (!res.success) {
          Swal.fire('Error', 'Data tidak ditemukan', 'error');
          return;
        }

        const f = res.data;
        document.getElementById('findingFormWrap').style.display = 'block';
        document.getElementById('finding_id').value = f.id;
        document.getElementById('finding_audit_id').value = f.audit_id;
        document.getElementById('finding_title').value = f.finding_title;
        document.getElementById('finding_description').value = f.description;
        document.getElementById('finding_severity').value = f.severity;
        document.getElementById('finding_unit').value = f.responsible_unit;
        document.getElementById('finding_due').value = f.due_date;
        document.getElementById('finding_recommendation').value = f.recommendation;
        document.getElementById('finding_status').value = f.status;
      })
      .catch(err => {
        console.error(err);
        Swal.fire('Error', 'Gagal memuat data', 'error');
      });
  }

  // ==== HAPUS TEMUAN ====
  function deleteFinding(id) {
    Swal.fire({
      title: 'Hapus temuan?',
      text: 'Data temuan akan dihapus permanen!',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: 'Ya, hapus!'
    }).then(result => {
      if (!result.isConfirmed) return;

      fetch('proses/audit_findings_delete.php?id=' + encodeURIComponent(id))
        .then(r => r.json())
        .then(res => {
          if (res.success) {
            Swal.fire('Dihapus', res.message, 'success');
            const aid = document.getElementById('finding_audit_id').value;
            if (aid) loadFindings(aid);
          } else {
            Swal.fire('Error', res.message || 'Gagal menghapus', 'error');
          }
        })
        .catch(err => {
          console.error(err);
          Swal.fire('Error', 'Terjadi kesalahan', 'error');
        });
    });
  }

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

  // ==== EDIT AUDIT ====
  document.querySelectorAll('.edit-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      const modal = new bootstrap.Modal(document.getElementById('editModal'));
      document.getElementById('edit_id').value = btn.dataset.id;
      document.getElementById('edit_title').value = btn.dataset.title;
      document.getElementById('edit_start').value = btn.dataset.start;
      document.getElementById('edit_end').value = btn.dataset.end;
      document.getElementById('edit_status').value = btn.dataset.status;
      document.getElementById('edit_summary').value = btn.dataset.summary;
      modal.show();
    });
  });
});
</script>

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