<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';

requireRole('branch_admin');
$pageTitle = 'Riwayat Transaksi';

$db = db();

// ============================================================================
// 1. DETEKSI CABANG USER
// ============================================================================
$currentUserId = currentUserId();
$userBranchId = null;
$userBranchName = 'Unknown';

try {
    $stmt = $db->prepare("SELECT u.branch_id, b.name as branch_name 
                          FROM users u LEFT JOIN branches b ON u.branch_id = b.id 
                          WHERE u.id = ?");
    $stmt->execute([$currentUserId]);
    $row = $stmt->fetch();
    $userBranchId = $row ? (int)$row['branch_id'] : null;
    $userBranchName = $row['branch_name'] ?? 'Unknown';
} catch (\Throwable $e) {}

if (!$userBranchId) {
    redirect('/branch/dashboard.php', '❌ Akun Anda tidak terdaftar di cabang manapun.', 'error');
}

// ============================================================================
// 2. FILTER & PARAMETER
// ============================================================================
$filterStatus = $_GET['status'] ?? '';
$filterDateFrom = $_GET['date_from'] ?? '';
$filterDateTo = $_GET['date_to'] ?? '';
$search = trim($_GET['search'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 25;
$offset = ($page - 1) * $perPage;

// ============================================================================
// 3. LOAD DATA TRANSAKSI (HANYA CABANG USER)
// ============================================================================
$where = ["bt.branch_id = ?"];
$params = [$userBranchId];

if ($filterStatus) {
    $where[] = "bt.status = ?";
    $params[] = $filterStatus;
}

if ($filterDateFrom) {
    $where[] = "DATE(bt.created_at) >= ?";
    $params[] = $filterDateFrom;
}

if ($filterDateTo) {
    $where[] = "DATE(bt.created_at) <= ?";
    $params[] = $filterDateTo;
}

if (!empty($search)) {
    $where[] = "(bt.customer_name LIKE ? OR bt.bill_number LIKE ? OR bt.transaction_id LIKE ?)";
    $searchParam = "%$search%";
    $params[] = $searchParam;
    $params[] = $searchParam;
    $params[] = $searchParam;
}

$whereClause = implode(' AND ', $where);

// Hitung total untuk pagination
try {
    $countStmt = $db->prepare("SELECT COUNT(*) as total FROM branch_transactions bt WHERE $whereClause");
    $countStmt->execute($params);
    $totalRows = (int)$countStmt->fetch()['total'];
    $totalPages = ceil($totalRows / $perPage);
} catch (\Throwable $e) {
    $totalRows = 0;
    $totalPages = 1;
}

// Ambil data transaksi
$sql = "
    SELECT bt.*, b.name as branch_name
    FROM branch_transactions bt
    LEFT JOIN branches b ON bt.branch_id = b.id
    WHERE $whereClause
    ORDER BY bt.created_at DESC
    LIMIT $perPage OFFSET $offset
";

$transactions = [];
try {
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $transactions = $stmt->fetchAll();
} catch (\Throwable $e) {
    $transactions = [];
}

// ============================================================================
// 4. STATISTIK (TANPA FILTER PAGINATION, tapi tetap dengan filter lainnya)
// ============================================================================
$stats = [
    'total_count' => 0,
    'total_amount' => 0,
    'pending_count' => 0,
    'pending_amount' => 0,
    'released_count' => 0,
    'released_amount' => 0,
    'cancelled_count' => 0,
    'cancelled_amount' => 0,
    'today_count' => 0,
    'today_amount' => 0,
    'this_month_count' => 0,
    'this_month_amount' => 0,
];

try {
    $statsSql = "
        SELECT 
            COUNT(*) as total_count,
            COALESCE(SUM(amount), 0) as total_amount,
            SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_count,
            COALESCE(SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END), 0) as pending_amount,
            SUM(CASE WHEN status = 'released' THEN 1 ELSE 0 END) as released_count,
            COALESCE(SUM(CASE WHEN status = 'released' THEN amount ELSE 0 END), 0) as released_amount,
            SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled_count,
            COALESCE(SUM(CASE WHEN status = 'cancelled' THEN amount ELSE 0 END), 0) as cancelled_amount,
            SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as today_count,
            COALESCE(SUM(CASE WHEN DATE(created_at) = CURDATE() THEN amount ELSE 0 END), 0) as today_amount,
            SUM(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN 1 ELSE 0 END) as this_month_count,
            COALESCE(SUM(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN amount ELSE 0 END), 0) as this_month_amount
        FROM branch_transactions
        WHERE branch_id = ?
    ";
    
    // Apply filter tanggal & search untuk statistik (kecuali status & pagination)
    $statsWhere = ["branch_id = ?"];
    $statsParams = [$userBranchId];
    
    if ($filterDateFrom) {
        $statsWhere[] = "DATE(created_at) >= ?";
        $statsParams[] = $filterDateFrom;
    }
    if ($filterDateTo) {
        $statsWhere[] = "DATE(created_at) <= ?";
        $statsParams[] = $filterDateTo;
    }
    if (!empty($search)) {
        $statsWhere[] = "(customer_name LIKE ? OR bill_number LIKE ? OR transaction_id LIKE ?)";
        $statsParams[] = $searchParam;
        $statsParams[] = $searchParam;
        $statsParams[] = $searchParam;
    }
    
    $statsSql = "
        SELECT 
            COUNT(*) as total_count,
            COALESCE(SUM(amount), 0) as total_amount,
            SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_count,
            COALESCE(SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END), 0) as pending_amount,
            SUM(CASE WHEN status = 'released' THEN 1 ELSE 0 END) as released_count,
            COALESCE(SUM(CASE WHEN status = 'released' THEN amount ELSE 0 END), 0) as released_amount,
            SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled_count,
            COALESCE(SUM(CASE WHEN status = 'cancelled' THEN amount ELSE 0 END), 0) as cancelled_amount,
            SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as today_count,
            COALESCE(SUM(CASE WHEN DATE(created_at) = CURDATE() THEN amount ELSE 0 END), 0) as today_amount,
            SUM(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN 1 ELSE 0 END) as this_month_count,
            COALESCE(SUM(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN amount ELSE 0 END), 0) as this_month_amount
        FROM branch_transactions
        WHERE " . implode(' AND ', $statsWhere);
    
    $stmt = $db->prepare($statsSql);
    $stmt->execute($statsParams);
    $stats = $stmt->fetch() ?: $stats;
} catch (\Throwable $e) {
    // Ignore, pakai default stats
}

// Saldo cabang
$balance = ['pending_balance' => 0, 'available_balance' => 0, 'total_income' => 0];
try {
    $stmt = $db->prepare("SELECT * FROM branch_balances WHERE branch_id = ?");
    $stmt->execute([$userBranchId]);
    $balance = $stmt->fetch() ?: $balance;
} catch (\Throwable $e) {}

require __DIR__ . '/../includes/header.php';
require __DIR__ . '/../includes/sidebar.php';
?>

<div class="main-content">
  <!-- Top Bar -->
  <div class="top-bar">
    <div class="top-bar-left">
      <button class="menu-toggle" onclick="toggleSidebar()"><i class="bi bi-list"></i></button>
      <div>
        <h3>
          <i class="bi bi-receipt me-2"></i>Riwayat Transaksi
          <span class="badge bg-info ms-2"><i class="bi bi-building"></i> <?= htmlspecialchars($userBranchName) ?></span>
        </h3>
        <small class="text-muted">
          Menampilkan <strong><?= number_format($totalRows) ?></strong> transaksi | 
          Total: <strong>Rp <?= number_format($stats['total_amount']) ?></strong>
        </small>
      </div>
    </div>
    <div class="top-bar-right">
      <a href="/branch/finance.php" class="btn btn-success">
        <i class="bi bi-bank"></i> <span class="d-none d-md-inline">Keuangan & Penarikan</span>
      </a>
    </div>
  </div>

  <?= flashMessage() ?>

  <!-- Info -->
  <div class="alert alert-info alert-dismissible fade show">
    <i class="bi bi-info-circle"></i> 
    Halaman ini menampilkan <strong>riwayat pembayaran pelanggan</strong> di cabang Anda. 
    Setiap transaksi akan masuk ke saldo <strong>Pending</strong> selama <strong>H+5</strong>, 
    lalu otomatis menjadi <strong>Tersedia</strong> untuk diajukan penarikan.
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
  </div>

  <!-- Statistics Cards -->
  <div class="row g-3 mb-4">
    <div class="col-md-3 col-sm-6">
      <div class="card border-primary h-100">
        <div class="card-body">
          <div class="d-flex justify-content-between align-items-start">
            <div>
              <h6 class="text-muted mb-1 small">Hari Ini</h6>
              <h4 class="text-primary mb-0"><?= $stats['today_count'] ?></h4>
              <small class="text-muted">Rp <?= number_format($stats['today_amount']) ?></small>
            </div>
            <i class="bi bi-calendar-day text-primary fs-2 opacity-50"></i>
          </div>
        </div>
      </div>
    </div>
    <div class="col-md-3 col-sm-6">
      <div class="card border-info h-100">
        <div class="card-body">
          <div class="d-flex justify-content-between align-items-start">
            <div>
              <h6 class="text-muted mb-1 small">Bulan Ini</h6>
              <h4 class="text-info mb-0"><?= $stats['this_month_count'] ?></h4>
              <small class="text-muted">Rp <?= number_format($stats['this_month_amount']) ?></small>
            </div>
            <i class="bi bi-calendar-month text-info fs-2 opacity-50"></i>
          </div>
        </div>
      </div>
    </div>
    <div class="col-md-3 col-sm-6">
      <div class="card border-warning h-100">
        <div class="card-body">
          <div class="d-flex justify-content-between align-items-start">
            <div>
              <h6 class="text-muted mb-1 small">Pending (H+5)</h6>
              <h4 class="text-warning mb-0"><?= $stats['pending_count'] ?></h4>
              <small class="text-muted">Rp <?= number_format($stats['pending_amount']) ?></small>
            </div>
            <i class="bi bi-hourglass-split text-warning fs-2 opacity-50"></i>
          </div>
        </div>
      </div>
    </div>
    <div class="col-md-3 col-sm-6">
      <div class="card border-success h-100">
        <div class="card-body">
          <div class="d-flex justify-content-between align-items-start">
            <div>
              <h6 class="text-muted mb-1 small">Sudah Released</h6>
              <h4 class="text-success mb-0"><?= $stats['released_count'] ?></h4>
              <small class="text-muted">Rp <?= number_format($stats['released_amount']) ?></small>
            </div>
            <i class="bi bi-check-circle text-success fs-2 opacity-50"></i>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Saldo Cabang Summary -->
  <div class="card mb-3 border-success">
    <div class="card-body">
      <div class="row text-center">
        <div class="col-md-4">
          <small class="text-muted d-block">Saldo Pending</small>
          <h5 class="text-warning mb-0">Rp <?= number_format($balance['pending_balance']) ?></h5>
        </div>
        <div class="col-md-4 border-start border-end">
          <small class="text-muted d-block">Saldo Tersedia</small>
          <h5 class="text-success mb-0">Rp <?= number_format($balance['available_balance']) ?></h5>
        </div>
        <div class="col-md-4">
          <small class="text-muted d-block">Total Income</small>
          <h5 class="text-info mb-0">Rp <?= number_format($balance['total_income']) ?></h5>
        </div>
      </div>
    </div>
  </div>

  <!-- Filter Card -->
  <div class="card mb-3">
    <div class="card-body">
      <form method="GET" class="row g-2 align-items-end">
        <div class="col-md-3">
          <label class="form-label small mb-1">Cari</label>
          <input type="text" name="search" class="form-control form-control-sm" 
                 value="<?= htmlspecialchars($search) ?>" 
                 placeholder="Nama pelanggan, no tagihan, trx ID...">
        </div>
        <div class="col-md-2">
          <label class="form-label small mb-1">Status</label>
          <select name="status" class="form-select form-select-sm">
            <option value="">Semua Status</option>
            <option value="pending" <?= $filterStatus === 'pending' ? 'selected' : '' ?>>⏳ Pending</option>
            <option value="released" <?= $filterStatus === 'released' ? 'selected' : '' ?>>✅ Released</option>
            <option value="cancelled" <?= $filterStatus === 'cancelled' ? 'selected' : '' ?>>❌ Cancelled</option>
          </select>
        </div>
        <div class="col-md-2">
          <label class="form-label small mb-1">Dari Tanggal</label>
          <input type="date" name="date_from" class="form-control form-control-sm" 
                 value="<?= htmlspecialchars($filterDateFrom) ?>">
        </div>
        <div class="col-md-2">
          <label class="form-label small mb-1">Sampai Tanggal</label>
          <input type="date" name="date_to" class="form-control form-control-sm" 
                 value="<?= htmlspecialchars($filterDateTo) ?>">
        </div>
        <div class="col-md-3 d-flex gap-1">
          <button type="submit" class="btn btn-primary btn-sm flex-fill">
            <i class="bi bi-funnel"></i> Filter
          </button>
          <a href="/branch/transactions.php" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-x-lg"></i>
          </a>
        </div>
      </form>
    </div>
  </div>

  <!-- Transactions Table -->
  <div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
      <div>
        <i class="bi bi-list-ul me-2"></i>Daftar Transaksi
        <span class="badge bg-secondary ms-2"><?= $totalRows ?></span>
      </div>
      <div class="small text-muted">
        Halaman <?= $page ?> dari <?= $totalPages ?>
      </div>
    </div>
    <div class="card-body p-0">
      <?php if (empty($transactions)): ?>
        <div class="text-center py-5">
          <i class="bi bi-inbox" style="font-size: 4rem; color: var(--text-muted);"></i>
          <h5 class="mt-3 text-muted">Tidak ada transaksi</h5>
          <p class="text-muted">
            <?php if ($filterStatus || $filterDateFrom || $filterDateTo || $search): ?>
              Tidak ada transaksi yang sesuai dengan filter. 
              <a href="/branch/transactions.php">Reset filter</a>
            <?php else: ?>
              Belum ada transaksi pembayaran di cabang ini.
            <?php endif; ?>
          </p>
        </div>
      <?php else: ?>
      <div class="table-responsive">
        <table class="table table-hover mb-0">
          <thead class="table-light">
            <tr>
              <th style="width: 50px;">#</th>
              <th>Tanggal</th>
              <th>Pelanggan</th>
              <th>No. Tagihan</th>
              <th class="text-end">Jumlah</th>
              <th>Metode</th>
              <th>Status</th>
              <th>Release</th>
              <th class="text-center">Aksi</th>
            </tr>
          </thead>
          <tbody>
            <?php 
            $no = $offset + 1;
            foreach ($transactions as $t): 
            ?>
              <tr>
                <td class="text-muted"><?= $no++ ?></td>
                <td>
                  <small>
                    <strong><?= date('d/m/Y', strtotime($t['created_at'])) ?></strong><br>
                    <span class="text-muted"><?= date('H:i', strtotime($t['created_at'])) ?> WIB</span>
                  </small>
                </td>
                <td>
                  <div class="d-flex align-items-center gap-2">
                    <div style="width:32px;height:32px;border-radius:50%;background:var(--primary-light);color:var(--primary);display:flex;align-items:center;justify-content:center;font-weight:600;font-size:13px;">
                      <?= strtoupper(substr($t['customer_name'], 0, 1)) ?>
                    </div>
                    <div>
                      <div class="fw-semibold small"><?= htmlspecialchars($t['customer_name']) ?></div>
                      <?php if (!empty($t['transaction_id'])): ?>
                        <small class="text-muted" title="<?= htmlspecialchars($t['transaction_id']) ?>">
                          TRX: <?= htmlspecialchars(substr($t['transaction_id'], 0, 15)) ?>...
                        </small>
                      <?php endif; ?>
                    </div>
                  </div>
                </td>
                <td>
                  <code class="small"><?= htmlspecialchars($t['bill_number']) ?></code>
                </td>
                <td class="text-end">
                  <strong class="text-primary">Rp <?= number_format($t['amount']) ?></strong>
                </td>
                <td>
                  <small>
                    <?php if (!empty($t['payment_method'])): ?>
                      <span class="badge bg-light text-dark border">
                        <?= htmlspecialchars($t['payment_method']) ?>
                      </span>
                    <?php endif; ?>
                    <?php if (!empty($t['payment_channel'])): ?>
                      <br><span class="text-muted small"><?= htmlspecialchars($t['payment_channel']) ?></span>
                    <?php endif; ?>
                    <?php if (empty($t['payment_method']) && empty($t['payment_channel'])): ?>
                      <span class="text-muted">-</span>
                    <?php endif; ?>
                  </small>
                </td>
                <td>
                  <?php
                    $statusBadge = [
                        'pending' => ['bg-warning text-dark', '⏳ Pending', 'Menunggu H+5'],
                        'released' => ['bg-success', '✅ Released', 'Sudah masuk saldo'],
                        'cancelled' => ['bg-danger', '❌ Cancelled', 'Dibatalkan'],
                    ];
                    $s = $statusBadge[$t['status']] ?? ['bg-secondary', $t['status'], ''];
                  ?>
                  <span class="badge <?= $s[0] ?>" title="<?= $s[2] ?>"><?= $s[1] ?></span>
                </td>
                <td>
                  <small>
                    <?php if ($t['status'] === 'released'): ?>
                      <span class="text-success">
                        ✅ <?= date('d/m/Y', strtotime($t['released_at'])) ?>
                      </span>
                    <?php elseif ($t['status'] === 'pending'): ?>
                      <span class="text-warning">
                        ⏳ <?= date('d/m/Y', strtotime($t['pending_until'])) ?>
                        <br>
                        <?php
                          $daysLeft = ceil((strtotime($t['pending_until']) - time()) / 86400);
                          if ($daysLeft > 0):
                        ?>
                          <span class="text-muted">(<?= $daysLeft ?> hari lagi)</span>
                        <?php else: ?>
                          <span class="text-success">(segera)</span>
                        <?php endif; ?>
                      </span>
                    <?php else: ?>
                      <span class="text-muted">-</span>
                    <?php endif; ?>
                  </small>
                </td>
                <td class="text-center">
                  <button class="btn btn-sm btn-outline-primary" 
                          data-bs-toggle="modal" 
                          data-bs-target="#detailModal<?= $t['id'] ?>"
                          title="Detail">
                    <i class="bi bi-eye"></i>
                  </button>
                </td>
              </tr>

              <!-- Detail Modal -->
              <div class="modal fade" id="detailModal<?= $t['id'] ?>" tabindex="-1">
                <div class="modal-dialog modal-lg">
                  <div class="modal-content">
                    <div class="modal-header bg-primary text-white">
                      <h5 class="modal-title">
                        <i class="bi bi-receipt me-2"></i>Detail Transaksi
                      </h5>
                      <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                      <div class="row">
                        <div class="col-md-6">
                          <h6 class="text-muted">Informasi Pembayaran</h6>
                          <table class="table table-sm">
                            <tr>
                              <td class="text-muted">No. Tagihan</td>
                              <td><strong><?= htmlspecialchars($t['bill_number']) ?></strong></td>
                            </tr>
                            <tr>
                              <td class="text-muted">Pelanggan</td>
                              <td><strong><?= htmlspecialchars($t['customer_name']) ?></strong></td>
                            </tr>
                            <tr>
                              <td class="text-muted">Jumlah</td>
                              <td><strong class="text-primary">Rp <?= number_format($t['amount']) ?></strong></td>
                            </tr>
                            <tr>
                              <td class="text-muted">Metode</td>
                              <td><?= htmlspecialchars($t['payment_method'] ?? '-') ?></td>
                            </tr>
                            <tr>
                              <td class="text-muted">Channel</td>
                              <td><?= htmlspecialchars($t['payment_channel'] ?? '-') ?></td>
                            </tr>
                            <tr>
                              <td class="text-muted">Transaction ID</td>
                              <td><code><?= htmlspecialchars($t['transaction_id'] ?? '-') ?></code></td>
                            </tr>
                          </table>
                        </div>
                        <div class="col-md-6">
                          <h6 class="text-muted">Status & Waktu</h6>
                          <table class="table table-sm">
                            <tr>
                              <td class="text-muted">Tanggal Transaksi</td>
                              <td><?= date('d/m/Y H:i:s', strtotime($t['created_at'])) ?> WIB</td>
                            </tr>
                            <tr>
                              <td class="text-muted">Status</td>
                              <td><span class="badge <?= $s[0] ?>"><?= $s[1] ?></span></td>
                            </tr>
                            <tr>
                              <td class="text-muted">Masa Tunggu</td>
                              <td>s/d <?= date('d/m/Y H:i', strtotime($t['pending_until'])) ?> WIB</td>
                            </tr>
                            <tr>
                              <td class="text-muted">Released At</td>
                              <td>
                                <?= $t['released_at'] ? date('d/m/Y H:i:s', strtotime($t['released_at'])) . ' WIB' : '-' ?>
                              </td>
                            </tr>
                          </table>
                          
                          <?php if ($t['status'] === 'pending'): ?>
                            <div class="alert alert-warning mt-3 mb-0">
                              <i class="bi bi-hourglass-split"></i> 
                              Saldo ini akan otomatis masuk ke <strong>Saldo Tersedia</strong> pada:
                              <br>
                              <strong><?= date('d F Y, H:i', strtotime($t['pending_until'])) ?> WIB</strong>
                            </div>
                          <?php elseif ($t['status'] === 'released'): ?>
                            <div class="alert alert-success mt-3 mb-0">
                              <i class="bi bi-check-circle-fill"></i> 
                              Saldo sudah masuk ke <strong>Saldo Tersedia</strong> dan dapat diajukan penarikan.
                            </div>
                          <?php endif; ?>
                        </div>
                      </div>
                    </div>
                    <div class="modal-footer">
                      <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                      <a href="/branch/finance.php" class="btn btn-success">
                        <i class="bi bi-bank"></i> Ke Halaman Keuangan
                      </a>
                    </div>
                  </div>
                </div>
              </div>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>

      <!-- Pagination -->
      <?php if ($totalPages > 1): ?>
      <div class="card-footer">
        <nav>
          <ul class="pagination pagination-sm mb-0 justify-content-center">
            <?php
            // Build query string tanpa page
            $queryParams = $_GET;
            unset($queryParams['page']);
            $baseQuery = http_build_query($queryParams);
            $baseQuery = $baseQuery ? $baseQuery . '&' : '';
            ?>
            
            <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
              <a class="page-link" href="?<?= $baseQuery ?>page=1">« Pertama</a>
            </li>
            <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
              <a class="page-link" href="?<?= $baseQuery ?>page=<?= $page - 1 ?>">‹ Sebelumnya</a>
            </li>
            
            <?php
            $startPage = max(1, $page - 2);
            $endPage = min($totalPages, $page + 2);
            
            for ($i = $startPage; $i <= $endPage; $i++):
            ?>
              <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                <a class="page-link" href="?<?= $baseQuery ?>page=<?= $i ?>"><?= $i ?></a>
              </li>
            <?php endfor; ?>
            
            <li class="page-item <?= $page >= $totalPages ? 'disabled' : '' ?>">
              <a class="page-link" href="?<?= $baseQuery ?>page=<?= $page + 1 ?>">Berikutnya ›</a>
            </li>
            <li class="page-item <?= $page >= $totalPages ? 'disabled' : '' ?>">
              <a class="page-link" href="?<?= $baseQuery ?>page=<?= $totalPages ?>">Terakhir »</a>
            </li>
          </ul>
        </nav>
      </div>
      <?php endif; ?>

      <?php endif; ?>
    </div>
  </div>
</div>

<script>
function toggleSidebar() {
    document.getElementById('sidebar').classList.toggle('active');
    document.getElementById('sidebarOverlay').classList.toggle('active');
}
</script>

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