<?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> Sistem Peminjaman Berkas<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-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-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 -->
                      <a class="btn btn-outline-primary" href="print.php?id=<?=$r['id']?>" target="_blank" title="Cetak Surat">
                        <i class="fa fa-print"></i>
                      </a>
                    <?php endif; ?>
                    
                    <?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']?>', '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']?>')" 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 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>
            </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>
      </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>
            </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>
      </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) {
  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, 'petugas');
  }
}

function editPeminjaman(id, nama, jabatan, tujuan, nomorPerkara, namaPihak, namaPihakLain, tanggalAmbil, tanggalKembali, penandatangan, status, userType = 'admin') {
  console.log('editPeminjaman called with:', {id, nama, jabatan, tujuan, nomorPerkara, namaPihak, namaPihakLain, tanggalAmbil, tanggalKembali, penandatangan, status});
  
  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;
  
  // 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);
  }
}
</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>
