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

// Konfigurasi pagination
$limit = 10;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $limit;

// Filter & search
$search = trim($_GET['search'] ?? '');
$where = [];
$params = [];

if ($search !== '') {
  $where[] = "(d.title LIKE ? OR v.file_name_original LIKE ?)";
  $params = array_fill(0, 2, "%$search%");
}
$where_sql = $where ? "WHERE " . implode(" AND ", $where) : "";

// Hitung total data
$count_stmt = $pdo->prepare("
  SELECT COUNT(*) 
  FROM document_versions v 
  JOIN documents d ON v.document_id = d.id 
  $where_sql
");
$count_stmt->execute($params);
$total_rows = $count_stmt->fetchColumn();
$total_pages = ceil($total_rows / $limit);

// Ambil data versi
$stmt = $pdo->prepare("
  SELECT v.*, d.title AS document_title, u.full_name AS uploader
  FROM document_versions v
  JOIN documents d ON v.document_id = d.id
  LEFT JOIN users u ON v.uploaded_by = u.id
  $where_sql
  ORDER BY v.uploaded_at DESC
  LIMIT $limit OFFSET $offset
");
$stmt->execute($params);
$versions = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Ambil daftar dokumen untuk dropdown
$docs = $pdo->query("SELECT id, title FROM documents ORDER BY title ASC")->fetchAll(PDO::FETCH_ASSOC);

// === CRUD ===

// Tambah
if (isset($_POST['add'])) {
  $document_id = $_POST['document_id'];
  $version_number = (int)$_POST['version_number'];
  $notes = $_POST['notes'];
  $effective_date = $_POST['effective_date'] ?: null;
  $uploaded_by = $_SESSION['user_id'] ?? null;

  if (!empty($_FILES['file']['name'])) {
    $file = $_FILES['file'];
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $target_dir = "../uploads/documents/";
    if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);

    $new_name = uniqid('DOCV_') . '.' . $ext;
    $target_file = $target_dir . $new_name;

    if (move_uploaded_file($file['tmp_name'], $target_file)) {
      $file_path = "uploads/documents/" . $new_name;
      $file_name_original = $file['name'];
      $mime_type = $file['type'];
      $file_hash = hash_file('sha256', $target_file);

      $stmt = $pdo->prepare("
          INSERT INTO document_versions 
          (document_id, version_number, file_path, file_name_original, mime_type, file_hash, notes, uploaded_by, effective_date)
          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([$document_id, $version_number, $file_path, $file_name_original, $mime_type, $file_hash, $notes, $uploaded_by, $effective_date]);
        
        $new_version_id = $pdo->lastInsertId();
        
        // ✅ Set versi ini sebagai versi aktif dokumen
        $updateDoc = $pdo->prepare("UPDATE documents SET current_version_id = ? WHERE id = ?");
        $updateDoc->execute([$new_version_id, $document_id]);
        
        echo "<script>
          Swal.fire('Berhasil', 'Versi dokumen berhasil ditambahkan', 'success')
          .then(()=>location.href='dokumen_version.php');
        </script>";
        exit;
    }
  }
}

// Edit
if (isset($_POST['update'])) {
  $id = $_POST['edit_id'];
  $notes = $_POST['edit_notes'];
  $effective_date = $_POST['edit_effective_date'];
  $version_number = (int)$_POST['edit_version_number'];
  $document_id = $_POST['edit_document_id'];

  // Ambil data lama untuk hapus file kalau diganti
  $old = $pdo->prepare("SELECT file_path FROM document_versions WHERE id=?");
  $old->execute([$id]);
  $old_file = $old->fetchColumn();

  // Siapkan update dasar
  $file_path = null;
  $file_name_original = null;
  $mime_type = null;
  $file_hash = null;

  // Cek kalau user upload file baru
  if (!empty($_FILES['edit_file']['name'])) {
    $file = $_FILES['edit_file'];
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $target_dir = "../uploads/documents/";
    if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);

    $new_name = uniqid('DOCV_') . '.' . $ext;
    $target_file = $target_dir . $new_name;

    if (move_uploaded_file($file['tmp_name'], $target_file)) {
      $file_path = "uploads/documents/" . $new_name;
      $file_name_original = $file['name'];
      $mime_type = $file['type'];
      $file_hash = hash_file('sha256', $target_file);

      // hapus file lama jika ada
      if ($old_file && file_exists("../" . $old_file)) {
        unlink("../" . $old_file);
      }

      $stmt = $pdo->prepare("UPDATE document_versions 
        SET document_id=?, version_number=?, file_path=?, file_name_original=?, mime_type=?, file_hash=?, notes=?, effective_date=? 
        WHERE id=?");
      $stmt->execute([$document_id, $version_number, $file_path, $file_name_original, $mime_type, $file_hash, $notes, $effective_date, $id]);
    }
  } else {
    // Tidak ganti file
    $stmt = $pdo->prepare("UPDATE document_versions 
      SET document_id=?, version_number=?, notes=?, effective_date=? WHERE id=?");
    $stmt->execute([$document_id, $version_number, $notes, $effective_date, $id]);
  }

  echo "<script>
    Swal.fire('Berhasil', 'Versi dokumen berhasil diperbarui', 'success')
    .then(()=>location.href='dokumen_version.php');
  </script>";
  exit;
}


// Hapus
if (isset($_GET['delete'])) {
  $id = (int)$_GET['delete'];
  $stmt = $pdo->prepare("DELETE FROM document_versions WHERE id=?");
  $stmt->execute([$id]);

  echo "<script>
    Swal.fire('Dihapus', 'Versi dokumen berhasil dihapus', 'success')
    .then(()=>location.href='dokumen_version.php');
  </script>";
  exit;
}

// Set versi aktif
if (isset($_GET['set_active'])) {
  $id = (int)$_GET['set_active'];
  $doc_stmt = $pdo->prepare("SELECT document_id FROM document_versions WHERE id=?");
  $doc_stmt->execute([$id]);
  $doc_id = $doc_stmt->fetchColumn();

  if ($doc_id) {
    $update = $pdo->prepare("UPDATE documents SET current_version_id=? WHERE id=?");
    $update->execute([$id, $doc_id]);
  }

  echo "<script>
    Swal.fire('Berhasil', 'Versi aktif berhasil diperbarui', 'success')
    .then(()=>location.href='dokumen_version.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-file-lines text-success me-2"></i>Versi Dokumen</h4>
      <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addModal">
        <i class="fa-solid fa-plus me-1"></i> Tambah Versi
      </button>
    </div>

    <!-- Filter -->
    <form method="get" class="row g-2 mb-3">
      <div class="col-md-6">
        <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" class="form-control" placeholder="Cari dokumen atau nama file...">
      </div>
      <div class="col-md-2 d-flex gap-2">
        <button class="btn btn-outline-success"><i class="fa-solid fa-search"></i></button>
        <a href="dokumen_version.php" class="btn btn-outline-secondary"><i class="fa-solid fa-rotate-left"></i></a>
      </div>
    </form>

    <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>Dokumen</th>
            <th>Versi</th>
            <th>File</th>
            <th>Catatan</th>
            <th>Uploader</th>
            <th>Tgl Upload</th>
            <th>Tgl Efektif</th>
            <th>Aksi</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($versions): foreach ($versions as $i => $v): ?>
          <tr>
            <td class="text-center"><?= $offset + $i + 1 ?></td>
            <td><?= htmlspecialchars($v['document_title']) ?></td>
            <td class="text-center">v<?= htmlspecialchars($v['version_number']) ?></td>
            <td>
              <a href="../<?= htmlspecialchars($v['file_path']) ?>" target="_blank">
                <i class="fa-solid fa-file-pdf text-danger me-1"></i><?= htmlspecialchars($v['file_name_original']) ?>
              </a>
            </td>
            <td><?= htmlspecialchars($v['notes'] ?: '-') ?></td>
            <td><?= htmlspecialchars($v['uploader'] ?: '-') ?></td>
            <td class="text-center"><?= date('d/m/Y', strtotime($v['uploaded_at'])) ?></td>
            <td class="text-center"><?= $v['effective_date'] ? date('d/m/Y', strtotime($v['effective_date'])) : '-' ?></td>
            <td class="text-center">
              <a href="?set_active=<?= $v['id'] ?>" class="btn btn-sm btn-success" title="Set Aktif">
                <i class="fa-solid fa-check"></i>
              </a>
              <button class="btn btn-sm btn-primary edit-btn"
                data-id="<?= $v['id'] ?>"
                data-notes="<?= htmlspecialchars($v['notes']) ?>"
                data-effective="<?= $v['effective_date'] ?>">
                <i class="fa-solid fa-pen-to-square"></i>
              </button>
              <button class="btn btn-sm btn-danger delete-btn" data-id="<?= $v['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 versi dokumen.</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 ?>&search=<?= urlencode($search) ?>"><?= $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 Versi Dokumen</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <label>Dokumen</label>
        <select name="document_id" class="form-select" required>
          <option value="">-- Pilih Dokumen --</option>
          <?php foreach ($docs as $d): ?>
            <option value="<?= $d['id'] ?>"><?= htmlspecialchars($d['title']) ?></option>
          <?php endforeach; ?>
        </select>
        <label class="mt-2">Nomor Versi</label>
        <input type="number" name="version_number" class="form-control" required>
        <label class="mt-2">File</label>
        <input type="file" name="file" class="form-control" accept=".pdf,.doc,.docx" required>
        <label class="mt-2">Catatan</label>
        <textarea name="notes" class="form-control" rows="2"></textarea>
        <label class="mt-2">Tanggal Efektif</label>
        <input type="date" name="effective_date" class="form-control">
      </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 Versi Dokumen</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>Dokumen</label>
        <select name="edit_document_id" id="edit_document_id" class="form-select" required>
          <option value="">-- Pilih Dokumen --</option>
          <?php foreach ($docs as $d): ?>
            <option value="<?= $d['id'] ?>"><?= htmlspecialchars($d['title']) ?></option>
          <?php endforeach; ?>
        </select>

        <label class="mt-2">Nomor Versi</label>
        <input type="number" name="edit_version_number" id="edit_version_number" class="form-control" required>

        <label class="mt-2">Ganti File (opsional)</label>
        <input type="file" name="edit_file" class="form-control" accept=".pdf,.doc,.docx">

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

        <label class="mt-2">Tanggal Efektif</label>
        <input type="date" name="edit_effective_date" id="edit_effective_date" class="form-control">
      </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_notes').value = btn.dataset.notes || '';
      document.getElementById('edit_effective_date').value = btn.dataset.effective || '';
      new bootstrap.Modal(document.getElementById('editModal')).show();
    });
  });

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

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