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

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

// === FILTER & PAGINASI ===
$filter_ppepp = $_GET['ppepp_id'] ?? '';
$search = trim($_GET['search'] ?? '');
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

// === KONDISI WHERE ===
$where = [];
$params = [];

if ($filter_ppepp) {
  $where[] = "e.ppepp_id = ?";
  $params[] = $filter_ppepp;
}
if ($search) {
  $where[] = "(e.file_name LIKE ? OR e.file_path LIKE ?)";
  $params = array_merge($params, ["%$search%", "%$search%"]);
}
$where_sql = $where ? "WHERE " . implode(" AND ", $where) : "";

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

// === DATA UTAMA ===
$stmt = $pdo->prepare("
  SELECT e.*, p.activity_title AS ppepp_title, u.full_name AS uploader
  FROM spmi_evidences e
  LEFT JOIN spmi_ppepp p ON e.ppepp_id = p.id
  LEFT JOIN users u ON e.uploaded_by = u.id
  $where_sql
  ORDER BY e.uploaded_at DESC
  LIMIT $limit OFFSET $offset
");
$stmt->execute($params);
$evidences = $stmt->fetchAll(PDO::FETCH_ASSOC);

// === DATA PPEPP UNTUK DROPDOWN ===
$ppepp = $pdo->query("SELECT id, activity_title FROM spmi_ppepp ORDER BY id DESC")->fetchAll();

// === UPLOAD DIRECTORY ===
$upload_dir = __DIR__ . '/../uploads/evidences/';
if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);

// === CRUD ===

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

    $stmt = $pdo->prepare("INSERT INTO spmi_evidences (ppepp_id, file_name, file_path, uploaded_by) VALUES (?, ?, ?, ?)");
    $stmt->execute([
      $_POST['ppepp_id'],
      $file_name,
      $file_path,
      $_SESSION['user_id'] ?? null
    ]);

    echo "<script>Swal.fire('Berhasil', 'Bukti berhasil ditambahkan', 'success').then(()=>location.href='spmi_evidences.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 file_path FROM spmi_evidences WHERE id=?");
    $stmt->execute([$id]);
    $old_file = $stmt->fetchColumn();

    $new_file = $old_file;
    $file_name = $_POST['edit_file_name'];
    if (!empty($_FILES['edit_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_file']['name']));
      $file_name = $base;
      $new_file = time() . '_' . $base;
      move_uploaded_file($_FILES['edit_file']['tmp_name'], $upload_dir . $new_file);
    }

    $stmt = $pdo->prepare("UPDATE spmi_evidences SET ppepp_id=?, file_name=?, file_path=? WHERE id=?");
    $stmt->execute([
      $_POST['edit_ppepp_id'],
      $file_name,
      $new_file,
      $id
    ]);

    echo "<script>Swal.fire('Berhasil', 'Bukti berhasil diperbarui', 'success').then(()=>location.href='spmi_evidences.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 file_path FROM spmi_evidences 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_evidences WHERE id=?");
  $stmt->execute([$id]);
  echo "<script>Swal.fire('Dihapus', 'Bukti berhasil dihapus', 'success').then(()=>location.href='spmi_evidences.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-paperclip text-success me-2"></i>Manajemen Bukti SPMI</h4>
      <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addModal">
        <i class="fa-solid fa-plus me-1"></i> Tambah Bukti
      </button>
    </div>

    <!-- FILTER & SEARCH -->
    <form method="get" class="row g-2 mb-3 align-items-end">
      <div class="col-md-4">
        <label class="form-label mb-1">Tahapan 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-5">
        <label class="form-label mb-1">Pencarian</label>
        <input type="text" name="search" class="form-control" placeholder="Cari nama file atau path..." 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_evidences.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>Tahapan PPEPP</th>
            <th>Nama File</th>
            <th>Uploader</th>
            <th>Tanggal Upload</th>
            <th>Preview</th>
            <th>Aksi</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($evidences): foreach ($evidences as $i => $e): ?>
          <tr>
            <td class="text-center"><?= $offset + $i + 1 ?></td>
            <td><?= htmlspecialchars($e['ppepp_title']) ?></td>
            <td><?= htmlspecialchars($e['file_name']) ?></td>
            <td><?= htmlspecialchars($e['uploader'] ?? '-') ?></td>
            <td class="text-center"><?= date('d/m/Y H:i', strtotime($e['uploaded_at'])) ?></td>
            <td class="text-center">
              <?php
              $path = '../uploads/evidences/' . htmlspecialchars($e['file_path']);
              $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
              if (in_array($ext, ['jpg', 'jpeg', 'png'])) {
                echo "<a href='$path' target='_blank'><img src='$path' width='60' height='60' style='object-fit:cover;border-radius:6px'></a>";
              } elseif ($ext === 'pdf') {
                echo "<a href='$path' target='_blank' class='text-danger'><i class='fa-solid fa-file-pdf fa-lg'></i> Lihat</a>";
              } else {
                echo "<a href='$path' target='_blank'><i class='fa-solid fa-file-lines'></i></a>";
              }
              ?>
            </td>
            <td class="text-center">
              <button class="btn btn-sm btn-primary edit-btn"
                      data-id="<?= $e['id'] ?>"
                      data-ppepp="<?= $e['ppepp_id'] ?>"
                      data-filename="<?= htmlspecialchars($e['file_name']) ?>"
                      data-filepath="<?= htmlspecialchars($e['file_path']) ?>">
                <i class="fa-solid fa-pen-to-square"></i>
              </button>
              <button class="btn btn-sm btn-danger delete-btn" data-id="<?= $e['id'] ?>">
                <i class="fa-solid fa-trash"></i>
              </button>
            </td>
          </tr>
          <?php endforeach; else: ?>
          <tr><td colspan="7" class="text-center text-muted">Tidak ada bukti 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">
    <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 Bukti</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <label class="form-label">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>

        <label class="form-label mt-3">File Bukti</label>
        <input type="file" name="file" class="form-control" accept=".pdf,.jpg,.jpeg,.png" required>
      </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" 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 Bukti</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">Tahapan 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>

        <label class="form-label mt-3">Nama File</label>
        <input type="text" name="edit_file_name" id="edit_file_name" class="form-control" required>

        <label class="form-label mt-3">Ganti File Bukti (Opsional)</label>
        <input type="file" name="edit_file" id="edit_file" class="form-control" accept=".pdf,.jpg,.jpeg,.png">
        <div id="current_file_info" class="small mt-2 text-muted 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 modal
  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_file_name').value = btn.dataset.filename;
      document.getElementById('current_file_info').innerHTML =
        `<small>File saat ini: ${btn.dataset.filepath}</small>`;
      new bootstrap.Modal(document.getElementById('editModal')).show();
    });
  });

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

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