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

// Konfigurasi database SIPP
$sipp_config = [
    'host' => '192.168.1.240',
    'dbname' => 'sippbaco',
    'username' => 'pnwtp',
    'password' => 'pnwtp2019',
    'port' => 3306
];

// Koneksi ke database SIPP
$sipp_db = null;
$connection_error = null;

try {
    $dsn = "mysql:host={$sipp_config['host']};port={$sipp_config['port']};dbname={$sipp_config['dbname']};charset=utf8mb4";
    $sipp_db = new PDO($dsn, $sipp_config['username'], $sipp_config['password']);
    $sipp_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    $connection_error = "Gagal terhubung ke database SIPP: " . $e->getMessage();
}

// Get notification count for navbar
$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();

// Handle search and pagination
$q = trim($_GET['q'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$limit = 20;
$offset = ($page - 1) * $limit;

$arsip_data = [];
$total_records = 0;

if ($sipp_db && !$connection_error) {
    try {
        // Query untuk data arsip
        $sql = "SELECT * FROM arsip WHERE 1=1";
        $count_sql = "SELECT COUNT(*) FROM arsip WHERE 1=1";
        $params = [];
        
        if ($q !== '') {
            $sql .= " AND (nomor_perkara LIKE ? OR nomor_arsip LIKE ? OR nomor_ruang LIKE ? OR nomor_rak LIKE ?)";
            $count_sql .= " AND (nomor_perkara LIKE ? OR nomor_arsip LIKE ? OR nomor_ruang LIKE ? OR nomor_rak LIKE ?)";
            array_push($params, '%'.$q.'%', '%'.$q.'%', '%'.$q.'%', '%'.$q.'%');
        }
        
        // Get total count
        $count_stmt = $sipp_db->prepare($count_sql);
        $count_stmt->execute($params);
        $total_records = $count_stmt->fetchColumn();
        
        // Get data with pagination
        $sql .= " ORDER BY id DESC LIMIT $limit OFFSET $offset";
        $stmt = $sipp_db->prepare($sql);
        $stmt->execute($params);
        $arsip_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
    } catch (PDOException $e) {
        $connection_error = "Error query: " . $e->getMessage();
    }
}

// Calculate pagination
$total_pages = ceil($total_records / $limit);
?>
<!doctype html>
<html lang="id"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Daftar Arsip Perkara - DIPARKUM Digitalisasi Peminjaman Arsip Perkara Kepaniteraan Hukum</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:#f8f9fa;font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif}
.header-title{background:linear-gradient(135deg, #28a745, #20c997);color:white;padding:15px 20px;border-radius:8px 8px 0 0;margin:0}
.search-container{background:white;padding:15px 20px;border-bottom:2px solid #e9ecef}
.table-container{background:white;border-radius:0 0 8px 8px;overflow:hidden;box-shadow:0 4px 6px rgba(0,0,0,0.1)}
.table thead th{background:#28a745;color:white;font-weight:600;border:none;padding:12px 8px;text-align:center;font-size:13px}
.table tbody td{padding:8px;border-color:#e9ecef;font-size:13px;text-align:center}
.table tbody tr:nth-child(even){background:#f8f9fa}
.table tbody tr:hover{background:#e8f5e8}
.btn-search{background:#28a745;border:#28a745;padding:8px 20px}
.btn-search:hover{background:#1e7e34;border:#1e7e34}
.btn-add{background:#17a2b8;border:#17a2b8;padding:8px 20px}
.btn-add:hover{background:#138496;border:#138496}
.pagination{justify-content:center;margin-top:20px}
.pagination .page-link{color:#28a745;border-color:#28a745}
.pagination .page-item.active .page-link{background:#28a745;border-color:#28a745}
.total-badge{background:#17a2b8;color:white;padding:5px 10px;border-radius:15px;font-size:12px;margin-left:10px}
.status-ada{background:#28a745;color:white;padding:2px 8px;border-radius:12px;font-size:11px}
.card-arsip{border:none;box-shadow:0 4px 6px rgba(0,0,0,0.1);margin-bottom:20px}
</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="index.php">
      <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" href="index.php">
        <i class="fa fa-home"></i> Beranda
      </a>
      <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-medium 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>
      <a class="btn btn-light btn-sm" href="arsip.php">
        <i class="fa fa-archive"></i> Arsip SIPP
      </a>
      <?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 if($connection_error): ?>
    <div class="alert alert-danger">
      <i class="fa fa-exclamation-triangle"></i> <strong>Error:</strong> <?= htmlspecialchars($connection_error) ?>
    </div>
  <?php else: ?>
  
    <div class="card-arsip">
      <div class="header-title d-flex justify-content-between align-items-center">
        <h4 class="mb-0"><i class="fa fa-archive me-2"></i>DAFTAR ARSIP PERKARA</h4>
        <span class="total-badge">Total : <?= number_format($total_records) ?></span>
      </div>
      
      <div class="search-container">
        <form method="GET" class="row g-2 align-items-center">
          <div class="col-md-8">
            <input type="text" class="form-control" name="q" value="<?= htmlspecialchars($q) ?>" 
                   placeholder="Ketik kata kunci">
          </div>
          <div class="col-md-2">
            <button type="submit" class="btn btn-search text-white w-100">
              <i class="fa fa-search me-1"></i>Search
            </button>
          </div>
          <div class="col-md-2">
            <button type="button" class="btn btn-add text-white w-100" onclick="alert('Fitur tambah arsip belum tersedia')">
              <i class="fa fa-plus me-1"></i>Tambah Arsip
            </button>
          </div>
        </form>
      </div>
      
      <?php if(!empty($arsip_data)): ?>
      <div class="table-container">
        <table class="table table-bordered mb-0">
          <thead>
            <tr>
              <th style="width:40px">No</th>
              <th style="width:80px">Nomor Arsip</th>
              <th style="width:80px">Nomor Ruang</th>
              <th style="width:120px">Nomor Rak/Lemari</th>
              <th style="width:120px">Nomor Tingkat/Laci</th>
              <th style="width:80px">Nomor Boks</th>
              <th>Nomor Perkara</th>
              <th style="width:100px">Tanggal Masuk</th>
              <th style="width:80px">Status</th>
              <th style="width:60px">Link</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach($arsip_data as $i => $row): ?>
              <tr>
                <td><?= $offset + $i + 1 ?></td>
                <td><?= htmlspecialchars($row['nomor_arsip'] ?? $row['id'] ?? '') ?></td>
                <td><?= htmlspecialchars($row['nomor_ruang'] ?? '') ?></td>
                <td><?= htmlspecialchars($row['nomor_rak'] ?? $row['nomor_lemari'] ?? '') ?></td>
                <td><?= htmlspecialchars($row['nomor_tingkat'] ?? $row['nomor_laci'] ?? '') ?></td>
                <td><?= htmlspecialchars($row['nomor_boks'] ?? '') ?></td>
                <td style="text-align:left"><?= htmlspecialchars($row['nomor_perkara'] ?? '') ?></td>
                <td>
                  <?php 
                  $tanggal = $row['tanggal_masuk'] ?? $row['tanggal_daftar'] ?? $row['created_at'] ?? '';
                  if($tanggal && $tanggal !== '0000-00-00') {
                    echo date('d M. Y', strtotime($tanggal));
                  }
                  ?>
                </td>
                <td><span class="status-ada">Ada</span></td>
                <td><a href="#" class="text-primary">[detail]</a></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
      
      <?php if($total_pages > 1): ?>
      <nav aria-label="Pagination" class="mt-3">
        <ul class="pagination">
          <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
            <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => max(1, $page - 1)])) ?>">Prev</a>
          </li>
          
          <?php for($i = 1; $i <= min($total_pages, 10); $i++): ?>
          <li class="page-item <?= $i == $page ? 'active' : '' ?>">
            <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $i])) ?>"><?= $i ?></a>
          </li>
          <?php endfor; ?>
          
          <?php if($total_pages > 10): ?>
          <li class="page-item"><span class="page-link">...</span></li>
          <li class="page-item">
            <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $total_pages])) ?>"><?= $total_pages ?></a>
          </li>
          <?php endif; ?>
          
          <li class="page-item <?= $page >= $total_pages ? 'disabled' : '' ?>">
            <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => min($total_pages, $page + 1)])) ?>">Next</a>
          </li>
        </ul>
      </nav>
      <?php endif; ?>
      
      <?php else: ?>
      <div class="text-center py-5">
        <i class="fa fa-archive fa-3x text-muted mb-3"></i>
        <h5>Tidak ada data arsip</h5>
        <p class="text-muted">
          <?php if($q): ?>
            Tidak ditemukan data untuk pencarian "<?= htmlspecialchars($q) ?>"
            <br><a href="arsip.php" class="btn btn-primary btn-sm mt-2">Tampilkan Semua</a>
          <?php else: ?>
            Belum ada data arsip dalam database
          <?php endif; ?>
        </p>
      </div>
      <?php endif; ?>
    </div>
  
  <?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body></html>
