<?php require 'auth.php'; require 'db.php'; require_login(); 

// Get notification count
$today = date('Y-m-d');
$notifStmt = $db->prepare("
    SELECT COUNT(*) as total_alerts
    FROM peminjaman 
    WHERE status = 'dipinjam' AND tanggal_kembali <= ?
");
$notifStmt->execute([$today]);
$notifCount = $notifStmt->fetchColumn();
?>
<!doctype html>
<html lang="id"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Buku Peminjaman Berkas</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
<style>
body{background:#f5f7fb}
.sortable-header a {
  color: #212529 !important;
  text-decoration: none !important;
  display: block;
  padding: 0;
}
.sortable-header a:hover {
  color: #0d6efd !important;
}
.sortable-header .fa-sort {
  opacity: 0.3;
}
.sortable-header .fa-sort-up,
.sortable-header .fa-sort-down {
  color: #0d6efd;
}
.highlight-row {
  background-color: #fff3cd !important;
  border: 2px solid #ffc107 !important;
}
.notification-pulse {
  animation: pulse 2s infinite;
}
@keyframes pulse {
  0% { box-shadow: 0 0 0 0 rgba(255, 193, 7, 0.7); }
  70% { box-shadow: 0 0 0 10px rgba(255, 193, 7, 0); }
  100% { box-shadow: 0 0 0 0 rgba(255, 193, 7, 0); }
}
.dropdown-menu {
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.dropdown-item {
  padding: 8px 20px;
}
.dropdown-item:hover {
  background-color: #f8f9fa;
}
.dropdown-divider {
  margin: 0.25rem 0;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
  <div class="container-fluid">
    <a class="navbar-brand d-flex align-items-center" href="#">
      <img src="gambar/Logo_pnwtp.png" alt="Logo PN Watampone" width="70" height="70" class="me-3">
      <span><i class="fa fa-book me-1"></i> DIPARKUM Digitalisasi Peminjaman Arsip Perkara Kepaniteraan Hukum<br><small>Pengadilan Negeri Watampone</small></span>
    </a>
    <div class="d-flex gap-2">
      <a class="btn btn-outline-light btn-sm position-relative" href="notifications.php">
        <i class="fa fa-bell"></i> Notifikasi
        <?php if($notifCount > 0): ?>
          <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
            <?= $notifCount ?>
          </span>
        <?php endif; ?>
      </a>
      <a class="btn btn-outline-light btn-sm" href="laporan.php">
        <i class="fa fa-chart-bar"></i> Laporan
      </a>
      
      <!-- Dropdown Menu Arsip SIPP -->
      <div class="btn-group">
        <button type="button" class="btn btn-outline-light btn-sm dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
          <i class="fa fa-archive"></i> Arsip SIPP
        </button>
        <ul class="dropdown-menu">
          <li><a class="dropdown-item" href="arsip-auto.php">
            <i class="fa fa-eye me-2"></i>Lihat Arsip (Auto)
            <small class="text-muted d-block">SIPP atau SQLite otomatis</small>
          </a></li>
          <li><hr class="dropdown-divider"></li>
          <li><a class="dropdown-item" href="arsip.php">
            <i class="fa fa-server me-2"></i>Arsip Online (SIPP)
          </a></li>
          <li><a class="dropdown-item" href="arsip-sqlite.php" data-sync-status>
            <i class="fa fa-database me-2"></i>Arsip Lokal (SQLite)
            <span class="sync-status badge bg-secondary ms-1">Loading...</span>
          </a></li>
          <li><hr class="dropdown-divider"></li>
          <li><a class="dropdown-item" href="sync-sipp-to-sqlite.php">
            <i class="fa fa-sync me-2"></i>Sinkronisasi Data
          </a></li>
          <li><a class="dropdown-item" href="test-sqlite-arsip.php" data-sync-status>
            <i class="fa fa-cog me-2"></i>Monitor SQLite
            <span class="sync-status badge bg-secondary ms-1">-</span>
          </a></li>
        </ul>
      </div>
      <?php if(is_admin()): ?>
        <a class="btn btn-outline-light btn-sm" href="admin.php"><i class="fa fa-cog"></i> Pengaturan</a>
        <a class="btn btn-outline-light btn-sm" href="admin/users.php"><i class="fa fa-users"></i> Akun</a>
      <?php endif; ?>
      <span class="navbar-text text-light">Hi, <?=htmlspecialchars(current_user()['nama_lengkap'] ?? current_user()['username'])?> (<?=current_user()['role']?>)</span>
      <a class="btn btn-outline-light btn-sm" href="logout.php"><i class="fa fa-sign-out-alt"></i> Logout</a>
    </div>
  </div>
</nav>

<div class="container-fluid py-3">
  <?php
  // Handle search and filters
  $q = trim($_GET['q'] ?? '');
  $status = trim($_GET['status'] ?? '');
  $from = $_GET['from'] ?? '';
  $to = $_GET['to'] ?? '';
  $sort = $_GET['sort'] ?? 'id';
  $order = $_GET['order'] ?? 'desc';
  $highlight = (int)($_GET['highlight'] ?? 0); // For highlighting specific row from notifications
  
  // Validate sort parameters
  $allowed_sorts = ['id', 'nama', 'nomor_perkara', 'tanggal_ambil', 'tanggal_kembali', 'status'];
  if (!in_array($sort, $allowed_sorts)) $sort = 'id';
  if (!in_array($order, ['asc', 'desc'])) $order = 'desc';
  
  // Build query with filters
  $sql = "SELECT * FROM peminjaman WHERE 1=1";
  $count_sql = "SELECT COUNT(*) FROM peminjaman WHERE 1=1";
  $params = [];
  
  if ($q !== '') {
    $sql .= " AND (nama LIKE ? OR nomor_perkara LIKE ? OR nama_pihak LIKE ? OR tujuan LIKE ?)";
    $count_sql .= " AND (nama LIKE ? OR nomor_perkara LIKE ? OR nama_pihak LIKE ? OR tujuan LIKE ?)";
    array_push($params, '%'.$q.'%', '%'.$q.'%', '%'.$q.'%', '%'.$q.'%');
  }
  
  if ($status !== '') {
    $sql .= " AND status = ?";
    $count_sql .= " AND status = ?";
    $params[] = $status;
  }
  
  if ($from !== '') {
    $sql .= " AND date(tanggal_ambil) >= date(?)";
    $count_sql .= " AND date(tanggal_ambil) >= date(?)";
    $params[] = $from;
  }
  
  if ($to !== '') {
    $sql .= " AND date(tanggal_ambil) <= date(?)";
    $count_sql .= " AND date(tanggal_ambil) <= date(?)";
    $params[] = $to;
  }

  // Get total count for pagination
  $count_stmt = $db->prepare($count_sql);
  $count_stmt->execute($params);
  $total_count = $count_stmt->fetchColumn();
  
  $sql .= " ORDER BY $sort $order LIMIT 1000";
  
  $stmt = $db->prepare($sql);
  $stmt->execute($params);
  $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  
  // Helper function to generate sort links
  function sort_link($column, $current_sort, $current_order) {
    $new_order = ($current_sort === $column && $current_order === 'asc') ? 'desc' : 'asc';
    $query_params = $_GET;
    $query_params['sort'] = $column;
    $query_params['order'] = $new_order;
    return '?' . http_build_query($query_params);
  }
  
  // Helper function to get sort icon
  function sort_icon($column, $current_sort, $current_order) {
    if ($current_sort === $column) {
      return $current_order === 'asc' ? 'fa-sort-up' : 'fa-sort-down';
    }
    return 'fa-sort';
  }
  ?>
  
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h3 class="mb-0"><i class="fa fa-list"></i> Buku Peminjaman Berkas</h3>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalAdd">
      <i class="fa fa-plus"></i> Tambah Peminjaman
    </button>
  </div>

  <!-- Search and Filter Form -->
  <div class="card mb-3">
    <div class="card-body">
      <form class="row g-2">
        <div class="col-md-3">
          <label class="form-label small">Pencarian</label>
          <input name="q" class="form-control" placeholder="Cari nama, nomor perkara, tujuan..." value="<?=htmlspecialchars($q)?>">
        </div>
        <div class="col-md-2">
          <label class="form-label small">Status</label>
          <select name="status" class="form-select">
            <option value="">Semua Status</option>
            <option value="dipinjam" <?=$status==='dipinjam'?'selected':''?>>Dipinjam</option>
            <option value="kembali" <?=$status==='kembali'?'selected':''?>>Dikembalikan</option>
          </select>
        </div>
        <div class="col-md-2">
          <label class="form-label small">Dari Tanggal</label>
          <input type="date" name="from" class="form-control" value="<?=htmlspecialchars($from)?>">
        </div>
        <div class="col-md-2">
          <label class="form-label small">Sampai Tanggal</label>
          <input type="date" name="to" class="form-control" value="<?=htmlspecialchars($to)?>">
        </div>
        <div class="col-md-1">
          <label class="form-label small">&nbsp;</label>
          <button type="submit" class="btn btn-outline-primary w-100">
            <i class="fa fa-search"></i> Filter
          </button>
        </div>
        <div class="col-md-1">
          <label class="form-label small">&nbsp;</label>
          <a href="index.php" class="btn btn-outline-secondary w-100">
            <i class="fa fa-undo"></i> Reset
          </a>
        </div>
        <?php foreach(['sort', 'order'] as $hidden): ?>
          <input type="hidden" name="<?=$hidden?>" value="<?=htmlspecialchars($_GET[$hidden] ?? '')?>">
        <?php endforeach; ?>
      </form>
    </div>
  </div>

  <?php if(isset($_GET['success'])): ?>
    <div class="alert alert-success alert-dismissible fade show">
      <i class="fa fa-check-circle"></i> Data berhasil disimpan!
      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
  <?php endif; ?>

  <!-- Info Fitur Baru Sinkronisasi SIPP -->
  <?php if(!isset($_SESSION['hide_sync_info'])): ?>
  <div class="alert alert-info alert-dismissible fade show">
    <div class="row align-items-center">
      <div class="col-md-1 text-center">
        <i class="fa fa-database fa-2x text-info"></i>
      </div>
      <div class="col-md-9">
        <h6 class="mb-1"><i class="fa fa-sparkles me-1"></i>Fitur Baru: Sinkronisasi Data SIPP</h6>
        <p class="mb-1">Kini data arsip SIPP bisa disinkronkan ke database lokal untuk akses lebih cepat dan tetap berfungsi meski server SIPP offline.</p>
        <small class="text-muted">Akses melalui menu "Arsip SIPP" → "Sinkronisasi Data"</small>
      </div>
      <div class="col-md-2 text-end">
        <a href="sync-sipp-to-sqlite.php" class="btn btn-info btn-sm">
          <i class="fa fa-sync me-1"></i>Coba Sekarang
        </a>
      </div>
    </div>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
  </div>
  <?php endif; ?>

  <!-- Data Table -->
  <div class="card">
    <div class="card-body">
      <div class="table-responsive">
        <table class="table table-striped align-middle">
          <thead class="table-light">
            <tr>
              <th class="sortable-header">
                <a href="<?=sort_link('id', $sort, $order)?>">
                  No <i class="fa <?=sort_icon('id', $sort, $order)?>"></i>
                </a>
              </th>
              <th class="sortable-header">
                <a href="<?=sort_link('nomor_perkara', $sort, $order)?>">
                  Nomor Perkara <i class="fa <?=sort_icon('nomor_perkara', $sort, $order)?>"></i>
                </a>
              </th>
              <th class="sortable-header">
                <a href="<?=sort_link('nama', $sort, $order)?>">
                  Peminjam <i class="fa <?=sort_icon('nama', $sort, $order)?>"></i>
                </a>
              </th>
              <th class="sortable-header">
                <a href="<?=sort_link('tanggal_ambil', $sort, $order)?>">
                  Tgl Ambil <i class="fa <?=sort_icon('tanggal_ambil', $sort, $order)?>"></i>
                </a>
              </th>
              <th class="sortable-header">
                <a href="<?=sort_link('tanggal_kembali', $sort, $order)?>">
                  Tgl Kembali <i class="fa <?=sort_icon('tanggal_kembali', $sort, $order)?>"></i>
                </a>
              </th>
              <th>Hari</th>
              <th>Perpanjangan</th>
              <th class="sortable-header">
                <a href="<?=sort_link('status', $sort, $order)?>">
                  Status <i class="fa <?=sort_icon('status', $sort, $order)?>"></i>
                </a>
              </th>
              <th class="text-center">Detail</th>
              <th class="text-end">Aksi</th>
            </tr>
          </thead>
          <tbody>
            <?php 
            // Calculate starting number based on sorting
            if ($sort === 'id' && $order === 'desc') {
              // For descending ID sort, start from total count and go down
              $no = $total_count;
            } else {
              // For ascending ID sort or other sorts, start from 1 and go up
              $no = 1;
            }
            ?>
            <?php foreach($rows as $r): ?>
              <?php
              // Calculate days difference
              $tanggal_ambil = new DateTime($r['tanggal_ambil']);
              $tanggal_kembali = new DateTime($r['tanggal_kembali']);
              $hari_difference = $tanggal_kembali->diff($tanggal_ambil)->days;
              
              // Check if this row should be highlighted
              $highlightClass = '';
              if ($highlight > 0 && $r['id'] == $highlight) {
                $highlightClass = 'highlight-row notification-pulse';
              }
              ?>
              <tr class="<?= $highlightClass ?>">
                <td><?= ($sort === 'id' && $order === 'desc') ? $no-- : $no++ ?></td>
                <td>
                  <strong><?=htmlspecialchars($r['nomor_perkara'])?></strong><br>
                  <small class="text-muted"><?=htmlspecialchars($r['nama_pihak'])?><?php if(!empty($r['nama_pihak_lain'])): ?> ✖ <?=htmlspecialchars($r['nama_pihak_lain'])?><?php endif; ?></small>
                </td>
                <td>
                  <?=htmlspecialchars($r['nama'])?><br>
                  <small class="text-muted"><?=htmlspecialchars($r['jabatan'])?></small><br>
                  <small class="text-info"><?=htmlspecialchars($r['tujuan'])?></small>
                </td>
                <td><?=htmlspecialchars($r['tanggal_ambil'])?></td>
                <td>
                  <?=htmlspecialchars($r['tanggal_kembali'])?>
                  <?php if($r['tanggal_kembali_real']): ?>
                    <br><small class="text-success">Aktual: <?=htmlspecialchars($r['tanggal_kembali_real'])?></small>
                  <?php endif; ?>
                </td>
                <td>
                  <span class="badge bg-info"><?=$hari_difference?> hari</span>
                </td>
                <td>
                  <?php if($r['perpanjangan_count'] > 0): ?>
                    <span class="badge bg-warning"><?=$r['perpanjangan_count']?> kali</span>
                  <?php else: ?>
                    <span class="badge bg-light text-dark">0 kali</span>
                  <?php endif; ?>
                </td>
                <td>
                  <span class="badge bg-<?=$r['status']==='kembali'?'success':'primary'?>">
                    <?=$r['status']==='kembali'?'Dikembalikan':'Dipinjam'?>
                  </span>
                </td>
                <td class="text-center">
                  <?php if(!empty($r['dokumen_path'])): ?>
                    <button class="btn btn-sm btn-outline-success" onclick="showDokumenDetail(<?=$r['id']?>, '<?=htmlspecialchars($r['nomor_perkara'], ENT_QUOTES)?>', '<?=htmlspecialchars($r['dokumen_upload_at'] ?? '', ENT_QUOTES)?>', '<?=htmlspecialchars($r['dokumen_keterangan'] ?? '', ENT_QUOTES)?>')" title="Lihat Detail Dokumen">
                      <i class="fa fa-file-pdf"></i>
                    </button>
                  <?php else: ?>
                    <span class="text-muted">-</span>
                  <?php endif; ?>
                </td>
                <td class="text-end">
                  <div class="btn-group btn-group-sm">
                    <?php 
                    $user = current_user();
                    $isPetugas = $user['role'] === 'petugas';
                    $isKembali = $r['status'] === 'kembali';
                    ?>
                    
                    <?php if ($isPetugas && $isKembali): ?>
                      <!-- Petugas: Print disabled untuk berkas yang sudah kembali -->
                      <button class="btn btn-outline-secondary" disabled title="Berkas sudah dikembalikan - Print tidak tersedia">
                        <i class="fa fa-print"></i>
                      </button>
                    <?php else: ?>
                      <!-- Admin atau berkas masih dipinjam: Print tersedia -->
                      <button class="btn btn-outline-primary" onclick="openPrintFormatModal(<?=$r['id']?>)" title="Cetak Surat">
                        <i class="fa fa-print"></i>
                      </button>
                    <?php endif; ?>
                    
                    <!-- Tombol Upload Dokumen -->
                    <button class="btn btn-outline-info" onclick="openUploadModal(<?=$r['id']?>, '<?=htmlspecialchars($r['nomor_perkara'], ENT_QUOTES)?>')" title="Upload Dokumen TTD">
                      <i class="fa fa-upload"></i>
                    </button>
                    
                    <?php if($r['status'] === 'dipinjam'): ?>
                      <?php if(is_admin()): ?>
                        <!-- Admin: Edit tanpa batasan -->
                        <button class="btn btn-outline-warning" onclick="editPeminjaman(<?=$r['id']?>, '<?=htmlspecialchars($r['nama'], ENT_QUOTES)?>', '<?=htmlspecialchars($r['jabatan'], ENT_QUOTES)?>', '<?=htmlspecialchars($r['tujuan'], ENT_QUOTES)?>', '<?=htmlspecialchars($r['nomor_perkara'], ENT_QUOTES)?>', '<?=htmlspecialchars($r['nama_pihak'], ENT_QUOTES)?>', '<?=htmlspecialchars($r['nama_pihak_lain'], ENT_QUOTES)?>', '<?=$r['tanggal_ambil']?>', '<?=$r['tanggal_kembali']?>', '<?=$r['penandatangan']?>', '<?=$r['status']?>', '<?=htmlspecialchars($r['tanggal_tanda_tangan'] ?? '', ENT_QUOTES)?>', 'admin')" title="Edit">
                          <i class="fa fa-edit"></i>
                        </button>
                        <button class="btn btn-outline-danger" onclick="deletePeminjaman(<?=$r['id']?>)" title="Hapus">
                          <i class="fa fa-trash"></i>
                        </button>
                      <?php elseif($user['role'] === 'petugas'): ?>
                        <?php 
                        $editCount = (int)($r['edit_count'] ?? 0);
                        $canEdit = $editCount < 1;
                        ?>
                        <?php if($canEdit): ?>
                          <!-- Petugas: Edit tersisa 1 kali -->
                          <button class="btn btn-outline-warning" onclick="editPetugasConfirm(<?=$r['id']?>, '<?=htmlspecialchars($r['nama'], ENT_QUOTES)?>', '<?=htmlspecialchars($r['jabatan'], ENT_QUOTES)?>', '<?=htmlspecialchars($r['tujuan'], ENT_QUOTES)?>', '<?=htmlspecialchars($r['nomor_perkara'], ENT_QUOTES)?>', '<?=htmlspecialchars($r['nama_pihak'], ENT_QUOTES)?>', '<?=htmlspecialchars($r['nama_pihak_lain'], ENT_QUOTES)?>', '<?=$r['tanggal_ambil']?>', '<?=$r['tanggal_kembali']?>', '<?=$r['penandatangan']?>', '<?=$r['status']?>', '<?=htmlspecialchars($r['tanggal_tanda_tangan'] ?? '', ENT_QUOTES)?>')" title="Edit (1 kali kesempatan tersisa)">
                            <i class="fa fa-edit"></i>
                          </button>
                        <?php else: ?>
                          <!-- Petugas: Sudah tidak bisa edit -->
                          <button class="btn btn-outline-secondary" disabled title="Anda sudah menggunakan 1 kali kesempatan edit">
                            <i class="fa fa-edit"></i>
                          </button>
                        <?php endif; ?>
                      <?php endif; ?>
                      
                      <button class="btn btn-outline-secondary" onclick="extendPeminjaman(<?=$r['id']?>, '<?=htmlspecialchars($r['nama'], ENT_QUOTES)?>', '<?=htmlspecialchars($r['nomor_perkara'], ENT_QUOTES)?>')" title="Perpanjang">
                        <i class="fa fa-calendar-plus"></i>
                      </button>
                      
                      <form action="return.php" method="post" class="d-inline">
                        <input type="hidden" name="id" value="<?=$r['id']?>">
                        <button type="submit" class="btn btn-success" title="Kembalikan" onclick="return confirm('Yakin ingin mengembalikan berkas ini?')">
                          <i class="fa fa-check"></i>
                        </button>
                      </form>
                    <?php else: ?>
                      <!-- Berkas sudah dikembalikan - perpanjangan dimatikan -->
                      <button class="btn btn-outline-secondary" disabled title="Berkas sudah dikembalikan - tidak dapat diperpanjang">
                        <i class="fa fa-calendar-plus"></i>
                      </button>
                      <!-- For returned items -->
                      <?php
                      $current_user = current_user();
                      $is_admin = is_admin();
                      $sudah_dicetak = $r['bukti_dicetak'] ?? 0;
                      ?>
                      
                      <?php if (!$sudah_dicetak): ?>
                        <!-- First time print -->
                        <a class="btn btn-primary" href="bukti.php?id=<?=$r['id']?>" target="_blank" title="Cetak Bukti Pengembalian" onclick="return confirmBukti('<?=htmlspecialchars($r['nomor_perkara'], ENT_QUOTES)?>', '<?=htmlspecialchars($r['nama'], ENT_QUOTES)?>')">
                          <i class="fa fa-certificate"></i> Bukti
                        </a>
                      <?php elseif ($is_admin): ?>
                        <!-- Admin can reprint -->
                        <a class="btn btn-warning" href="bukti.php?id=<?=$r['id']?>" target="_blank" title="Cetak Ulang Bukti (Admin)" onclick="return confirm('Bukti sudah pernah dicetak sebelumnya. Yakin ingin mencetak ulang sebagai admin?')">
                          <i class="fa fa-certificate"></i> Cetak Ulang
                        </a>
                      <?php else: ?>
                        <!-- Petugas cannot reprint -->
                        <button class="btn btn-secondary" disabled title="Bukti sudah dicetak">
                          <i class="fa fa-certificate"></i> Sudah Dicetak
                        </button>
                      <?php endif; ?>
                      
                      <?php if ($is_admin): ?>
                        <!-- Admin can delete returned items -->
                        <button class="btn btn-outline-danger" onclick="deleteReturnedItem(<?=$r['id']?>, '<?=htmlspecialchars($r['nomor_perkara'], ENT_QUOTES)?>', '<?=htmlspecialchars($r['nama'], ENT_QUOTES)?>')" title="Hapus Data (Admin Only)">
                          <i class="fa fa-trash"></i>
                        </button>
                      <?php endif; ?>
                    <?php endif; ?>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
            
            <?php if(empty($rows)): ?>
              <tr>
                <td colspan="9" class="text-center text-muted py-4">
                  <i class="fa fa-inbox fa-2x mb-2"></i><br>
                  Tidak ada data yang ditemukan
                </td>
              </tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
      
      <div class="mt-3 text-muted">
        Total: <?=count($rows)?> data
      </div>
    </div>
  </div>
</div>

<!-- Modal Pilihan Format Print -->
<div class="modal fade" id="modalPrintFormat" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title"><i class="fa fa-print"></i> Pilih Format Print</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <p class="text-muted mb-3">Silakan pilih format print yang ingin digunakan:</p>
        <div class="d-grid gap-3">
          <button type="button" class="btn btn-outline-primary btn-lg" onclick="printFormat(1)">
            <i class="fa fa-file-alt me-2"></i>
            <strong>Format Print 1</strong>
            <br>
            <small class="text-muted">Format standar dengan kop surat lengkap</small>
          </button>
          <button type="button" class="btn btn-outline-success btn-lg" onclick="printFormat(2)">
            <i class="fa fa-file-invoice me-2"></i>
            <strong>Format Print 2</strong>
            <br>
            <small class="text-muted">Format ringkas untuk arsip</small>
          </button>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
          <i class="fa fa-times"></i> Batal
        </button>
      </div>
    </div>
  </div>
</div>

<!-- Modal Upload Dokumen -->
<div class="modal fade" id="modalUploadDokumen" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header bg-info text-white">
        <h5 class="modal-title"><i class="fa fa-upload"></i> Upload Dokumen Tanda Tangan</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <form id="formUploadDokumen" enctype="multipart/form-data">
        <div class="modal-body">
          <input type="hidden" id="upload_id" name="id">
          
          <div class="mb-3">
            <label class="form-label"><strong>Nomor Perkara:</strong></label>
            <p id="upload_nomor_perkara" class="text-muted"></p>
          </div>
          
          <div class="mb-3">
            <label for="upload_file" class="form-label">Pilih File (PDF/JPG/PNG) *</label>
            <input type="file" class="form-control" id="upload_file" name="dokumen" accept=".pdf,.jpg,.jpeg,.png" required>
            <small class="text-muted">Maksimal 5MB. Format: PDF, JPG, PNG</small>
          </div>
          
          <div class="mb-3">
            <label for="upload_keterangan" class="form-label">Keterangan (Opsional)</label>
            <textarea class="form-control" id="upload_keterangan" name="keterangan" rows="3" placeholder="Tambahkan keterangan jika diperlukan"></textarea>
          </div>
          
          <div id="upload_progress" class="progress d-none" style="height: 25px;">
            <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" style="width: 0%"></div>
          </div>
          
          <div id="upload_message" class="alert d-none mt-3"></div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
            <i class="fa fa-times"></i> Batal
          </button>
          <button type="submit" class="btn btn-info" id="btnUpload">
            <i class="fa fa-upload"></i> Upload Dokumen
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Modal Detail Dokumen -->
<div class="modal fade" id="modalDetailDokumen" tabindex="-1">
  <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header bg-success text-white">
        <h5 class="modal-title"><i class="fa fa-file-pdf"></i> Riwayat Dokumen Tanda Tangan</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="mb-3">
          <label class="text-muted small">Nomor Perkara:</label>
          <h6 class="fw-bold" id="detail_nomor_perkara">-</h6>
        </div>
        
        <div class="table-responsive">
          <table class="table table-bordered table-hover">
            <thead class="table-light">
              <tr>
                <th width="5%">No</th>
                <th width="20%">Tanggal Upload</th>
                <th width="15%">Upload Oleh</th>
                <th width="25%">Keterangan</th>
                <th width="20%">Preview</th>
                <th width="15%">Aksi</th>
              </tr>
            </thead>
            <tbody id="detail_dokumen_list">
              <tr>
                <td colspan="6" class="text-center">
                  <div class="spinner-border spinner-border-sm" role="status">
                    <span class="visually-hidden">Loading...</span>
                  </div>
                  Memuat data...
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
          <i class="fa fa-times"></i> Tutup
        </button>
      </div>
    </div>
  </div>
</div>

<!-- Modal Add -->
<div class="modal fade" id="modalAdd" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <form class="modal-content" method="post" action="save.php">
      <div class="modal-header">
        <h5 class="modal-title"><i class="fa fa-plus"></i> Form Peminjaman Berkas</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label">Nama Peminjam *</label>
            <input name="nama" class="form-control" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">Jabatan *</label>
            <input name="jabatan" class="form-control" required>
          </div>
          <div class="col-12">
            <label class="form-label">Tujuan Peminjaman *</label>
            <textarea name="tujuan" class="form-control" rows="2" required placeholder="Jelaskan tujuan peminjaman berkas"></textarea>
          </div>
          <div class="col-md-6">
            <label class="form-label">Nomor Perkara *</label>
            <input name="nomor_perkara" id="add_nomor_perkara" class="form-control" required placeholder="contoh: 123/Pid.B/2025/PN.Wtp" autocomplete="off">
          </div>
          <div class="col-md-6">
            <label class="form-label">Nama Pihak *</label>
            <input name="nama_pihak" class="form-control" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">Nama Pihak Lain</label>
            <input name="nama_pihak_lain" class="form-control" placeholder="Opsional">
          </div>
          <div class="col-md-3">
            <label class="form-label">Tanggal Ambil *</label>
            <input type="date" name="tanggal_ambil" id="tanggal_ambil" class="form-control" required onchange="hitungKembali()" value="<?= date('Y-m-d') ?>">
          </div>
          <div class="col-md-3">
            <label class="form-label">Lama Peminjaman *</label>
            <select id="lama" name="lama" class="form-select" onchange="hitungKembali()" required>
              <option value="1">1 hari</option>
              <option value="2">2 hari</option>
              <option value="3" selected>3 hari</option>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">Penandatangan *</label>
            <select name="penandatangan" class="form-select" required>
              <option value="">-- Pilih Penandatangan --</option>
              <option value="ketua">Ketua Pengadilan</option>
              <option value="wakil">Wakil Ketua Pengadilan</option>
              <option value="plh">PLH Ketua Pengadilan</option>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">Tanggal Kembali</label>
            <input type="date" name="tanggal_kembali" id="tanggal_kembali" class="form-control" readonly>
          </div>
          <div class="col-md-6">
            <label class="form-label">Tanggal Tanda Tangan</label>
            <input type="date" name="tanggal_tanda_tangan" class="form-control" value="<?= date('Y-m-d') ?>" title="Tanggal tanda tangan untuk bukti peminjaman">
            <small class="form-text text-muted">Kosongkan untuk menggunakan tanggal saat cetak bukti</small>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
        <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> Simpan</button>
      </div>
    </form>
  </div>
</div>

<!-- Modal Edit -->
<div class="modal fade" id="modalEdit" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <form class="modal-content" method="post" action="update.php">
      <input type="hidden" name="id" id="edit_id">
      <div class="modal-header">
        <h5 class="modal-title"><i class="fa fa-edit"></i> Edit Peminjaman</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="row g-3">
          <div class="col-md-6">
            <label class="form-label">Nama Peminjam *</label>
            <input name="nama" id="edit_nama" class="form-control" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">Jabatan *</label>
            <input name="jabatan" id="edit_jabatan" class="form-control" required>
          </div>
          <div class="col-12">
            <label class="form-label">Tujuan Peminjaman *</label>
            <textarea name="tujuan" id="edit_tujuan" class="form-control" rows="2" required></textarea>
          </div>
          <div class="col-md-6">
            <label class="form-label">Nomor Perkara *</label>
            <input name="nomor_perkara" id="edit_nomor_perkara" class="form-control" required autocomplete="off">
          </div>
          <div class="col-md-6">
            <label class="form-label">Nama Pihak *</label>
            <input name="nama_pihak" id="edit_nama_pihak" class="form-control" required>
          </div>
          <div class="col-md-6">
            <label class="form-label">Nama Pihak Lain</label>
            <input name="nama_pihak_lain" id="edit_nama_pihak_lain" class="form-control">
          </div>
          <div class="col-md-3">
            <label class="form-label">Tanggal Ambil *</label>
            <input type="date" name="tanggal_ambil" id="edit_tanggal_ambil" class="form-control" required onchange="hitungKembaliEdit()">
          </div>
          <div class="col-md-3">
            <label class="form-label">Lama Peminjaman *</label>
            <select id="edit_lama" name="lama" class="form-select" onchange="hitungKembaliEdit()" required>
              <option value="1">1 hari</option>
              <option value="2">2 hari</option>
              <option value="3">3 hari</option>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">Penandatangan *</label>
            <select name="penandatangan" id="edit_penandatangan" class="form-select" required>
              <option value="">-- Pilih Penandatangan --</option>
              <option value="ketua">Ketua Pengadilan</option>
              <option value="wakil">Wakil Ketua Pengadilan</option>
              <option value="plh">PLH Ketua Pengadilan</option>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">Tanggal Kembali</label>
            <input type="date" name="tanggal_kembali" id="edit_tanggal_kembali" class="form-control" readonly>
          </div>
          <div class="col-md-6">
            <label class="form-label">Tanggal Tanda Tangan</label>
            <input type="date" name="tanggal_tanda_tangan" id="edit_tanggal_tanda_tangan" class="form-control" title="Tanggal tanda tangan untuk bukti peminjaman">
            <small class="form-text text-muted">Kosongkan untuk menggunakan tanggal saat cetak bukti</small>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
        <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> Update</button>
      </div>
    </form>
  </div>
</div>

<!-- Modal Extend -->
<div class="modal fade" id="modalExtend" tabindex="-1">
  <div class="modal-dialog">
    <form class="modal-content" method="post" action="extend.php">
      <input type="hidden" name="id" id="extend_id">
      <div class="modal-header">
        <h5 class="modal-title"><i class="fa fa-calendar-plus"></i> Perpanjangan Peminjaman</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="alert alert-info">
          <strong>Peminjam:</strong> <span id="extend_nama"></span><br>
          <strong>Nomor Perkara:</strong> <span id="extend_nomor"></span>
        </div>
        <div class="mb-3">
          <label class="form-label">Perpanjangan *</label>
          <select name="hari" class="form-select" required>
            <option value="1">1 hari</option>
            <option value="2">2 hari</option>
            <option value="3" selected>3 hari</option>
          </select>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
        <button type="submit" class="btn btn-warning"><i class="fa fa-calendar-plus"></i> Perpanjang</button>
      </div>
    </form>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="js/nomor-perkara-autocomplete.js"></script>
<script>
function hitungKembali() {
  const ambil = document.getElementById('tanggal_ambil').value;
  const lama = parseInt(document.getElementById('lama').value || '3', 10);
  
  if (ambil) {
    const t = new Date(ambil); t.setDate(t.getDate()+lama);
    const y=t.getFullYear(), m=String(t.getMonth()+1).padStart(2,'0'), d=String(t.getDate()).padStart(2,'0');
    document.getElementById('tanggal_kembali').value = `${y}-${m}-${d}`;
  }
}

function hitungKembaliEdit() {
  const ambil = document.getElementById('edit_tanggal_ambil').value;
  const lama = parseInt(document.getElementById('edit_lama').value || '3', 10);
  
  if (ambil) {
    const t = new Date(ambil); t.setDate(t.getDate()+lama);
    const y=t.getFullYear(), m=String(t.getMonth()+1).padStart(2,'0'), d=String(t.getDate()).padStart(2,'0');
    document.getElementById('edit_tanggal_kembali').value = `${y}-${m}-${d}`;
  }
}

// Confirmation for petugas edit (1 time only)
function editPetugasConfirm(id, nama, jabatan, tujuan, nomorPerkara, namaPihak, namaPihakLain, tanggalAmbil, tanggalKembali, penandatangan, status, tanggalTandaTangan = '') {
  const message = `⚠️ PERINGATAN PENTING!\n\nAnda hanya punya 1 kali kesempatan untuk melakukan edit!\n\nPastikan Anda melakukan edit dengan benar karena setelah ini tombol edit akan tidak aktif.\n\nApakah Anda yakin ingin melanjutkan edit untuk berkas "${nomorPerkara}"?`;
  
  if (confirm(message)) {
    editPeminjaman(id, nama, jabatan, tujuan, nomorPerkara, namaPihak, namaPihakLain, tanggalAmbil, tanggalKembali, penandatangan, status, tanggalTandaTangan, 'petugas');
  }
}

function editPeminjaman(id, nama, jabatan, tujuan, nomorPerkara, namaPihak, namaPihakLain, tanggalAmbil, tanggalKembali, penandatangan, status, tanggalTandaTangan = '', userType = 'admin') {
  console.log('editPeminjaman called with:', {id, nama, jabatan, tujuan, nomorPerkara, namaPihak, namaPihakLain, tanggalAmbil, tanggalKembali, penandatangan, status, tanggalTandaTangan});
  
  if (status !== 'dipinjam') {
    alert('Hanya peminjaman dengan status "dipinjam" yang bisa diedit');
    return;
  }
  
  // Set form values
  document.getElementById('edit_id').value = id;
  document.getElementById('edit_nama').value = nama;
  document.getElementById('edit_jabatan').value = jabatan;
  document.getElementById('edit_tujuan').value = tujuan;
  document.getElementById('edit_nomor_perkara').value = nomorPerkara;
  document.getElementById('edit_nama_pihak').value = namaPihak;
  document.getElementById('edit_nama_pihak_lain').value = namaPihakLain;
  document.getElementById('edit_tanggal_ambil').value = tanggalAmbil;
  document.getElementById('edit_tanggal_kembali').value = tanggalKembali;
  document.getElementById('edit_penandatangan').value = penandatangan;
  document.getElementById('edit_tanggal_tanda_tangan').value = tanggalTandaTangan || '';
  
  // Calculate days difference for lama selection
  if (tanggalAmbil && tanggalKembali) {
    try {
      const ambil = new Date(tanggalAmbil);
      const kembali = new Date(tanggalKembali);
      const diffTime = Math.abs(kembali - ambil);
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      
      const lamaSelect = document.getElementById('edit_lama');
      const lamaValue = Math.min(Math.max(diffDays, 1), 3); // Clamp between 1 and 3
      lamaSelect.value = lamaValue;
    } catch (e) {
      console.error('Error calculating days difference:', e);
      document.getElementById('edit_lama').value = '3'; // Default fallback
    }
  }
  
  // Show modal
  new bootstrap.Modal(document.getElementById('modalEdit')).show();
}

function extendPeminjaman(id, nama, nomor) {
  const confirmMessage = `Apakah Anda yakin ingin memperpanjang peminjaman untuk:\n\nPeminjam: ${nama}\nNomor Perkara: ${nomor}\n\nPerpanjangan ini akan menambah waktu peminjaman sesuai pilihan Anda.`;
  
  if (confirm(confirmMessage)) {
    document.getElementById('extend_id').value = id;
    document.getElementById('extend_nama').textContent = nama;
    document.getElementById('extend_nomor').textContent = nomor;
    new bootstrap.Modal(document.getElementById('modalExtend')).show();
  }
}

function deletePeminjaman(id) {
  if (confirm('Yakin ingin menghapus data peminjaman ini?')) {
    fetch('delete.php', {
      method: 'POST',
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      body: 'id=' + id
    })
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        location.reload();
      } else {
        alert('Gagal menghapus: ' + data.message);
      }
    })
    .catch(error => {
      console.error('Error:', error);
      alert('Terjadi kesalahan');
    });
  }
}

function deleteReturnedItem(id, nomorPerkara, namaPeminjam) {
  const message = `⚠️ PERINGATAN: Hapus Data Permanen!\n\nApakah Anda yakin ingin menghapus data peminjaman yang sudah dikembalikan?\n\nPeminjam: ${namaPeminjam}\nNomor Perkara: ${nomorPerkara}\n\n❌ AKSI INI TIDAK DAPAT DIBATALKAN!\n❌ Data akan dihapus permanen dari sistem!\n\nHanya admin yang dapat melakukan ini.`;
  
  if (confirm(message)) {
    fetch('delete.php', {
      method: 'POST',
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      body: 'id=' + id + '&type=returned'
    })
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        alert('Data berhasil dihapus permanen');
        location.reload();
      } else {
        alert('Gagal menghapus: ' + data.message);
      }
    })
    .catch(error => {
      console.error('Error:', error);
      alert('Terjadi kesalahan');
    });
  }
}

// Auto-calculate return date on page load
document.addEventListener('DOMContentLoaded', function() {
  hitungKembali();
});

// Confirmation for bukti printing
function confirmBukti(nomorPerkara, namaPeminjam) {
  const message = `Apakah Anda yakin dan telah memeriksa berkas "${nomorPerkara}" atas nama "${namaPeminjam}" sesuai dan telah dikembalikan?\n\n⚠️ PERHATIAN: Bukti hanya dapat dicetak 1 kali!\n\nSetelah dicetak, bukti tidak dapat dicetak ulang kecuali oleh admin.`;
  
  return confirm(message);
}

// Initialize autocomplete for nomor perkara inputs
document.addEventListener('DOMContentLoaded', function() {
  // Autocomplete for Add Form
  if (document.getElementById('add_nomor_perkara')) {
    new NomorPerkaraAutocomplete('#add_nomor_perkara', {
      showDetails: true,
      onSelect: function(data) {
        // Show info about selected case
        console.log('Selected nomor perkara:', data.nomor_perkara);
      }
    });
  }
  
  // Autocomplete for Edit Form
  if (document.getElementById('edit_nomor_perkara')) {
    new NomorPerkaraAutocomplete('#edit_nomor_perkara', {
      showDetails: true,
      onSelect: function(data) {
        // Show info about selected case
        console.log('Edited nomor perkara:', data.nomor_perkara);
      }
    });
  }
  
  // Check sync status and update dropdown
  checkSyncStatus();
});

// Check SQLite sync status
async function checkSyncStatus() {
  try {
    const response = await fetch('api/check-sync-status.php');
    const data = await response.json();
    
    // Find sync status elements in dropdown
    const syncItems = document.querySelectorAll('[data-sync-status]');
    
    syncItems.forEach(item => {
      const statusElement = item.querySelector('.sync-status');
      if (statusElement) {
        let badgeClass = 'bg-secondary';
        let statusText = 'Unknown';
        
        switch(data.status) {
          case 'fresh':
            badgeClass = 'bg-success';
            statusText = 'Fresh';
            break;
          case 'old':
            badgeClass = 'bg-warning';
            statusText = 'Lama';
            break;
          case 'outdated':
            badgeClass = 'bg-danger';
            statusText = 'Usang';
            break;
          case 'not_synced':
            badgeClass = 'bg-secondary';
            statusText = 'Belum Sync';
            break;
          case 'error':
            badgeClass = 'bg-danger';
            statusText = 'Error';
            break;
        }
        
        statusElement.className = `badge ${badgeClass} ms-1`;
        statusElement.textContent = statusText;
        statusElement.title = `${data.message} | Total: ${data.total_records || 0} records`;
      }
    });
    
  } catch (error) {
    console.error('Failed to check sync status:', error);
  }
}

// Print Format Modal Functions
let selectedPrintId = null;

function openPrintFormatModal(id) {
  selectedPrintId = id;
  const modal = new bootstrap.Modal(document.getElementById('modalPrintFormat'));
  modal.show();
}

function printFormat(format) {
  if (selectedPrintId) {
    const url = `print.php?id=${selectedPrintId}&format=${format}`;
    window.open(url, '_blank');
    
    // Close modal
    const modal = bootstrap.Modal.getInstance(document.getElementById('modalPrintFormat'));
    if (modal) {
      modal.hide();
    }
    
    selectedPrintId = null;
  }
}

// Upload Dokumen Functions
function openUploadModal(id, nomorPerkara) {
  document.getElementById('upload_id').value = id;
  document.getElementById('upload_nomor_perkara').textContent = nomorPerkara;
  document.getElementById('formUploadDokumen').reset();
  document.getElementById('upload_progress').classList.add('d-none');
  document.getElementById('upload_message').classList.add('d-none');
  
  const modal = new bootstrap.Modal(document.getElementById('modalUploadDokumen'));
  modal.show();
}

document.getElementById('formUploadDokumen').addEventListener('submit', function(e) {
  e.preventDefault();
  
  const formData = new FormData(this);
  const progressBar = document.querySelector('#upload_progress .progress-bar');
  const progressDiv = document.getElementById('upload_progress');
  const messageDiv = document.getElementById('upload_message');
  const btnUpload = document.getElementById('btnUpload');
  
  // Validate file size
  const fileInput = document.getElementById('upload_file');
  const file = fileInput.files[0];
  if (file && file.size > 5 * 1024 * 1024) {
    messageDiv.className = 'alert alert-danger mt-3';
    messageDiv.textContent = 'Ukuran file terlalu besar! Maksimal 5MB.';
    messageDiv.classList.remove('d-none');
    return;
  }
  
  // Show progress
  progressDiv.classList.remove('d-none');
  messageDiv.classList.add('d-none');
  btnUpload.disabled = true;
  
  const xhr = new XMLHttpRequest();
  
  // Upload progress
  xhr.upload.addEventListener('progress', function(e) {
    if (e.lengthComputable) {
      const percentComplete = (e.loaded / e.total) * 100;
      progressBar.style.width = percentComplete + '%';
      progressBar.textContent = Math.round(percentComplete) + '%';
    }
  });
  
  // Upload complete
  xhr.addEventListener('load', function() {
    btnUpload.disabled = false;
    
    if (xhr.status === 200) {
      try {
        const response = JSON.parse(xhr.responseText);
        if (response.success) {
          messageDiv.className = 'alert alert-success mt-3';
          messageDiv.innerHTML = '<i class="fa fa-check-circle"></i> ' + response.message;
          messageDiv.classList.remove('d-none');
          
          // Reload page after 1.5 seconds
          setTimeout(function() {
            location.reload();
          }, 1500);
        } else {
          messageDiv.className = 'alert alert-danger mt-3';
          messageDiv.textContent = response.message || 'Upload gagal!';
          messageDiv.classList.remove('d-none');
        }
      } catch (e) {
        messageDiv.className = 'alert alert-danger mt-3';
        messageDiv.textContent = 'Terjadi kesalahan pada server!';
        messageDiv.classList.remove('d-none');
      }
    } else {
      messageDiv.className = 'alert alert-danger mt-3';
      messageDiv.textContent = 'Upload gagal! Status: ' + xhr.status;
      messageDiv.classList.remove('d-none');
    }
    
    progressDiv.classList.add('d-none');
    progressBar.style.width = '0%';
  });
  
  // Upload error
  xhr.addEventListener('error', function() {
    btnUpload.disabled = false;
    messageDiv.className = 'alert alert-danger mt-3';
    messageDiv.textContent = 'Terjadi kesalahan jaringan!';
    messageDiv.classList.remove('d-none');
    progressDiv.classList.add('d-none');
  });
  
  xhr.open('POST', 'upload-dokumen.php');
  xhr.send(formData);
});

// Detail Dokumen Modal Functions
let currentDokumenId = null;

function showDokumenDetail(id, nomorPerkara, tanggalUpload, keterangan) {
  currentDokumenId = id;
  
  // Set nomor perkara
  document.getElementById('detail_nomor_perkara').textContent = nomorPerkara;
  
  // Show modal
  const modal = new bootstrap.Modal(document.getElementById('modalDetailDokumen'));
  modal.show();
  
  // Load dokumen list
  loadDokumenList(id);
}

function loadDokumenList(peminjaman_id) {
  const tbody = document.getElementById('detail_dokumen_list');
  tbody.innerHTML = '<tr><td colspan="6" class="text-center"><div class="spinner-border spinner-border-sm"></div> Memuat data...</td></tr>';
  
  fetch(`get-dokumen-list.php?id=${peminjaman_id}`)
    .then(response => response.json())
    .then(data => {
      if (data.success && data.documents.length > 0) {
        let html = '';
        data.documents.forEach((doc, index) => {
          const isAdmin = <?= is_admin() ? 'true' : 'false' ?>;
          const fileExt = doc.file_extension.toLowerCase();
          const isImage = ['jpg', 'jpeg', 'png'].includes(fileExt);
          
          html += `
            <tr>
              <td class="text-center">${index + 1}</td>
              <td>${doc.uploaded_at_formatted}</td>
              <td>${doc.uploaded_by}</td>
              <td>${doc.keterangan || '-'}</td>
              <td class="text-center">
                ${isImage ? 
                  `<img src="${doc.file_path}" style="max-width:100px; max-height:60px; cursor:pointer;" onclick="viewDokumen(${peminjaman_id}, ${doc.id})" class="img-thumbnail">` :
                  `<i class="fa fa-file-pdf fa-2x text-danger" style="cursor:pointer;" onclick="viewDokumen(${peminjaman_id}, ${doc.id})"></i>`
                }
              </td>
              <td class="text-center">
                <button class="btn btn-sm btn-primary" onclick="viewDokumen(${peminjaman_id}, ${doc.id})" title="Lihat">
                  <i class="fa fa-eye"></i>
                </button>
                <a href="download-dokumen.php?peminjaman_id=${peminjaman_id}&index=${doc.id}" class="btn btn-sm btn-success" title="Download">
                  <i class="fa fa-download"></i>
                </a>
                ${isAdmin ? 
                  `<button class="btn btn-sm btn-danger" onclick="hapusSingleDokumen(${peminjaman_id}, ${doc.id})" title="Hapus">
                    <i class="fa fa-trash"></i>
                  </button>` : ''
                }
              </td>
            </tr>
          `;
        });
        tbody.innerHTML = html;
      } else {
        tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">Belum ada dokumen yang diupload</td></tr>';
      }
    })
    .catch(error => {
      console.error('Error loading documents:', error);
      tbody.innerHTML = '<tr><td colspan="6" class="text-center text-danger">Gagal memuat data</td></tr>';
    });
}

function viewDokumen(peminjaman_id, index) {
  window.open(`view-dokumen-history.php?peminjaman_id=${peminjaman_id}&index=${index}`, '_blank');
}

function hapusSingleDokumen(peminjaman_id, index) {
  if (confirm('Yakin ingin menghapus dokumen ini?')) {
    fetch('hapus-dokumen-history.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: `peminjaman_id=${peminjaman_id}&index=${index}`
    })
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        alert(data.message);
        loadDokumenList(peminjaman_id); // Reload list
      } else {
        alert('Gagal menghapus: ' + data.message);
      }
    })
    .catch(error => {
      alert('Terjadi kesalahan: ' + error);
    });
  }
}

function hapusDokumenFromDetail() {
  if (!currentDokumenId) return;
  
  if (confirm('Yakin ingin menghapus SEMUA dokumen untuk peminjaman ini?')) {
    fetch('hapus-all-dokumen.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: 'id=' + currentDokumenId
    })
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        alert(data.message);
        location.reload();
      } else {
        alert('Gagal menghapus: ' + data.message);
      }
    })
    .catch(error => {
      alert('Terjadi kesalahan: ' + error);
    });
  }
}

// Hapus Dokumen Function (legacy, kept for compatibility)
function hapusDokumen(id, nomorPerkara) {
  if (confirm(`Yakin ingin menghapus dokumen untuk perkara ${nomorPerkara}?`)) {
    fetch('hapus-dokumen.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: 'id=' + id
    })
    .then(response => response.json())
    .then(data => {
      if (data.success) {
        alert(data.message);
        location.reload();
      } else {
        alert('Gagal menghapus: ' + data.message);
      }
    })
    .catch(error => {
      alert('Terjadi kesalahan: ' + error);
    });
  }
}
</script>

<!-- Footer -->
<footer class="bg-primary text-white text-center py-3 mt-5">
  <div class="container">
    <p class="mb-0">©2025 by Pn Watampone, Dibuat oleh Fahrurrasyid, A.Md.T CPNS Mahkamah Agung RI Angkatan 2024</p>
  </div>
</footer>

</body>
</html>
