<?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 nama_pihak LIKE ? OR jenis_perkara LIKE ? OR keterangan LIKE ?)";
            $count_sql .= " AND (nomor_perkara LIKE ? OR nama_pihak LIKE ? OR jenis_perkara LIKE ? OR keterangan 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>Arsip SIPP - Sistem 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}
.card{box-shadow:0 2px 10px rgba(0,0,0,0.1)}
.table th{background:#f8f9fa}
</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> 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" 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-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>
      <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">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h2><i class="fa fa-archive text-primary"></i> Data Arsip SIPP</h2>
    <?php if(!$connection_error): ?>
      <span class="badge bg-success">
        <i class="fa fa-check-circle"></i> Terhubung ke SIPP
      </span>
    <?php endif; ?>
  </div>

  <?php if($connection_error): ?>
    <div class="alert alert-danger">
      <i class="fa fa-exclamation-triangle"></i> <strong>Error:</strong> <?= htmlspecialchars($connection_error) ?>
    </div>
  <?php endif; ?>

  <!-- Search Form -->
  <?php if(!$connection_error): ?>
  <div class="card mb-3">
    <div class="card-body">
      <form method="GET" class="row g-3">
        <div class="col-md-10">
          <input type="text" class="form-control" name="q" value="<?= htmlspecialchars($q) ?>" 
                 placeholder="Cari nomor perkara, nama pihak, jenis perkara, atau keterangan...">
        </div>
        <div class="col-md-2">
          <button type="submit" class="btn btn-primary w-100"><i class="fa fa-search"></i> Cari</button>
        </div>
        <?php if($q): ?>
        <div class="col-12">
          <a href="arsip.php" class="btn btn-outline-secondary btn-sm">
            <i class="fa fa-times"></i> Hapus Pencarian
          </a>
        </div>
        <?php endif; ?>
      </form>
    </div>
  </div>
  <?php endif; ?>

  <!-- Results Info -->
  <?php if(!$connection_error): ?>
    <div class="d-flex justify-content-between align-items-center mb-3">
      <span class="text-muted">
        <?php if($total_records > 0): ?>
          Menampilkan <?= number_format(count($arsip_data)) ?> dari <?= number_format($total_records) ?> data arsip
          <?php if($q): ?>| Pencarian: "<strong><?= htmlspecialchars($q) ?></strong>"<?php endif; ?>
        <?php else: ?>
          Tidak ada data arsip
        <?php endif; ?>
      </span>
      <?php if($total_pages > 1): ?>
      <nav aria-label="Pagination">
        <ul class="pagination pagination-sm">
          <?php if($page > 1): ?>
            <li class="page-item">
              <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page-1])) ?>">
                <i class="fa fa-chevron-left"></i>
              </a>
            </li>
          <?php endif; ?>
          
          <?php
          $start_page = max(1, $page - 2);
          $end_page = min($total_pages, $page + 2);
          
          for($i = $start_page; $i <= $end_page; $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($page < $total_pages): ?>
            <li class="page-item">
              <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['page' => $page+1])) ?>">
                <i class="fa fa-chevron-right"></i>
              </a>
            </li>
          <?php endif; ?>
        </ul>
      </nav>
      <?php endif; ?>
    </div>
  <?php endif; ?>

  <!-- Data Table -->
  <?php if(!$connection_error && !empty($arsip_data)): ?>
    <div class="card">
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-striped table-hover mb-0">
            <thead class="table-dark">
              <tr>
                <th width="50">No</th>
                <?php 
                // Tampilkan header berdasarkan kolom yang ada
                $sample_row = $arsip_data[0];
                foreach(array_keys($sample_row) as $column):
                  if($column !== 'id'): // Skip ID column
                ?>
                <th><?= ucwords(str_replace('_', ' ', htmlspecialchars($column))) ?></th>
                <?php 
                  endif;
                endforeach; 
                ?>
              </tr>
            </thead>
            <tbody>
              <?php foreach($arsip_data as $i => $row): ?>
                <tr>
                  <td><?= $offset + $i + 1 ?></td>
                  <?php foreach($row as $column => $value): ?>
                    <?php if($column !== 'id'): // Skip ID column ?>
                    <td>
                      <?php if(strlen($value) > 100): ?>
                        <span title="<?= htmlspecialchars($value) ?>">
                          <?= htmlspecialchars(substr($value, 0, 100)) ?>...
                        </span>
                      <?php else: ?>
                        <?= htmlspecialchars($value ?? '') ?>
                      <?php endif; ?>
                    </td>
                    <?php endif; ?>
                  <?php endforeach; ?>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  <?php elseif(!$connection_error && empty($arsip_data) && $q): ?>
    <div class="text-center py-5">
      <i class="fa fa-search fa-3x text-muted mb-3"></i>
      <h5>Tidak ada data yang ditemukan</h5>
      <p class="text-muted">Coba gunakan kata kunci yang berbeda</p>
      <a href="arsip.php" class="btn btn-primary">Tampilkan Semua Data</a>
    </div>
  <?php elseif(!$connection_error && empty($arsip_data)): ?>
    <div class="text-center py-5">
      <i class="fa fa-archive fa-3x text-muted mb-3"></i>
      <h5>Belum ada data arsip</h5>
      <p class="text-muted">Data arsip akan muncul di sini</p>
    </div>
  <?php endif; ?>
</div>

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