<?php
// public/students.php - Daftar Siswa dengan Pencarian, Filter & Pagination
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
$db = get_db();

// Get parameters
$search = $_GET['search'] ?? '';
$grade_filter = $_GET['grade'] ?? '';
$sort = $_GET['sort'] ?? 'name_asc';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;

// Build query for counting
$count_sql = 'SELECT COUNT(*) FROM students WHERE 1=1';
$sql = 'SELECT * FROM students WHERE 1=1';
$params = [];

// Search filter
if (!empty($search)) {
  $search_condition = ' AND (nis LIKE :search OR name LIKE :search)';
  $count_sql .= $search_condition;
  $sql .= $search_condition;
  $params[':search'] = '%' . $search . '%';
}

// Grade filter
if (!empty($grade_filter)) {
  $count_sql .= ' AND grade = :grade';
  $sql .= ' AND grade = :grade';
  $params[':grade'] = $grade_filter;
}

// Get total count
$count_stmt = $db->prepare($count_sql);
$count_stmt->execute($params);
$total_items = $count_stmt->fetchColumn();
$total_pages = ceil($total_items / $per_page);

// Sorting
switch ($sort) {
  case 'name_desc':
    $sql .= ' ORDER BY name DESC';
    break;
  case 'nis_asc':
    $sql .= ' ORDER BY nis ASC';
    break;
  case 'nis_desc':
    $sql .= ' ORDER BY nis DESC';
    break;
  case 'grade_asc':
    $sql .= ' ORDER BY grade ASC, name ASC';
    break;
  default: // name_asc
    $sql .= ' ORDER BY name ASC';
}

// Pagination
$sql .= ' LIMIT :limit OFFSET :offset';

// Execute query
$stmt = $db->prepare($sql);
foreach ($params as $key => $value) {
  $stmt->bindValue($key, $value);
}
$stmt->bindValue(':limit', $per_page, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$students = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get all grades for filter
$grades = $db->query('SELECT DISTINCT grade FROM students WHERE grade IS NOT NULL AND grade != "" ORDER BY grade')->fetchAll(PDO::FETCH_COLUMN);

// Build query string for pagination
function build_query_string($exclude = []) {
  $params = $_GET;
  foreach ($exclude as $key) {
    unset($params[$key]);
  }
  return http_build_query($params);
}

require __DIR__ . '/_header.php';
?>

<div class="container py-5">
  <!-- Header -->
  <div class="row mb-4">
    <div class="col-12">
      <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
          <h1 class="display-6 fw-bold mb-2">Daftar Siswa</h1>
          <p class="text-muted mb-0">
            <a href="<?php echo base_url(); ?>/public/index.php" class="text-decoration-none">
              <i class="fa fa-arrow-left me-1"></i>Kembali ke Beranda
            </a>
          </p>
        </div>
        <div>
          <span class="badge bg-primary-subtle text-primary fs-5">
            <i class="fa fa-users me-1"></i><?php echo $total_items; ?> Siswa
          </span>
        </div>
      </div>
    </div>
  </div>

  <!-- Search & Filter Bar -->
  <div class="row mb-4">
    <div class="col-12">
      <div class="card border-0 shadow-sm">
        <div class="card-body">
          <form method="GET" action="students.php" class="row g-3">
            <!-- Search -->
            <div class="col-md-5">
              <div class="input-group">
                <span class="input-group-text bg-white">
                  <i class="fa fa-search text-muted"></i>
                </span>
                <input type="text" 
                       name="search" 
                       class="form-control border-start-0" 
                       placeholder="Cari berdasarkan NIS atau Nama..." 
                       value="<?php echo e($search); ?>">
              </div>
            </div>
            
            <!-- Grade Filter -->
            <div class="col-md-3">
              <select name="grade" class="form-select">
                <option value="">Semua Kelas</option>
                <?php foreach ($grades as $grade): ?>
                  <option value="<?php echo e($grade); ?>" <?php echo $grade_filter === $grade ? 'selected' : ''; ?>>
                    <?php echo e($grade); ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            
            <!-- Sort -->
            <div class="col-md-3">
              <select name="sort" class="form-select">
                <option value="name_asc" <?php echo $sort === 'name_asc' ? 'selected' : ''; ?>>Nama A-Z</option>
                <option value="name_desc" <?php echo $sort === 'name_desc' ? 'selected' : ''; ?>>Nama Z-A</option>
                <option value="nis_asc" <?php echo $sort === 'nis_asc' ? 'selected' : ''; ?>>NIS Terkecil</option>
                <option value="nis_desc" <?php echo $sort === 'nis_desc' ? 'selected' : ''; ?>>NIS Terbesar</option>
                <option value="grade_asc" <?php echo $sort === 'grade_asc' ? 'selected' : ''; ?>>Kelas</option>
              </select>
            </div>
            
            <!-- Buttons -->
            <div class="col-md-1">
              <button type="submit" class="btn btn-primary w-100" title="Cari">
                <i class="fa fa-search">Cari</i>
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>

  <!-- Results Info -->
  <div class="row mb-3">
    <div class="col-12">
      <div class="d-flex justify-content-between align-items-center">
        <p class="text-muted mb-0">
          Menampilkan <?php echo count($students); ?> dari <?php echo $total_items; ?> siswa
          <?php if (!empty($search)): ?>
            untuk "<strong><?php echo e($search); ?></strong>"
          <?php endif; ?>
          <?php if (!empty($grade_filter)): ?>
            di kelas <strong><?php echo e($grade_filter); ?></strong>
          <?php endif; ?>
        </p>
        <?php if (!empty($search) || !empty($grade_filter)): ?>
          <a href="students.php" class="btn btn-sm btn-outline-secondary">
            <i class="fa fa-times me-1"></i>Reset Filter
          </a>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <!-- Students Table -->
  <div class="row">
    <div class="col-12">
      <div class="card border-0 shadow-sm">
        <div class="card-body p-0">
          <div class="table-responsive">
            <table class="table table-hover mb-0">
              <thead class="table-light">
                <tr>
                  <th class="px-4 py-3" style="width: 80px;">No</th>
                  <th class="py-3" style="width: 150px;">NIS</th>
                  <th class="py-3">Nama Siswa</th>
                  <th class="py-3" style="width: 150px;">Kelas</th>
                </tr>
              </thead>
              <tbody>
                <?php if (empty($students)): ?>
                  <tr>
                    <td colspan="4" class="text-center py-5">
                      <i class="fa fa-users fa-3x text-muted mb-3 d-block"></i>
                      <p class="text-muted mb-2">Tidak ada siswa yang ditemukan</p>
                      <?php if (!empty($search) || !empty($grade_filter)): ?>
                        <a href="students.php" class="btn btn-sm btn-primary">Reset Filter</a>
                      <?php endif; ?>
                    </td>
                  </tr>
                <?php else: ?>
                  <?php 
                  $no = $offset + 1;
                  foreach ($students as $s): 
                  ?>
                    <tr>
                      <td class="px-4 py-3 text-muted"><?php echo $no++; ?></td>
                      <td class="py-3">
                        <span class="badge bg-primary-subtle text-primary">
                          <?php echo e($s['nis']); ?>
                        </span>
                      </td>
                      <td class="py-3">
                        <div class="d-flex align-items-center">
                          <?php if (!empty($s['photo'])): ?>
                            <img src="<?php echo base_url(); ?>/data/uploads/<?php echo e($s['photo']); ?>" 
                                 alt="<?php echo e($s['name']); ?>" 
                                 class="rounded-circle me-3" 
                                 style="width: 48px; height: 48px; object-fit: cover; border: 2px solid #e9ecef;">
                          <?php else: ?>
                            <div class="rounded-circle me-3 bg-primary-subtle d-flex align-items-center justify-content-center" 
                                 style="width: 48px; height: 48px;">
                              <i class="fa fa-user text-primary"></i>
                            </div>
                          <?php endif; ?>
                          <div>
                            <div class="fw-semibold"><?php echo e($s['name']); ?></div>
                          </div>
                        </div>
                      </td>
                      <td class="py-3">
                        <span class="badge bg-success-subtle text-success">
                          <?php echo e($s['grade']); ?>
                        </span>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Pagination -->
  <?php if ($total_pages > 1): ?>
    <div class="row mt-4">
      <div class="col-12">
        <nav aria-label="Page navigation">
          <ul class="pagination justify-content-center">
            <!-- Previous -->
            <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
              <a class="page-link" href="?<?php echo build_query_string(['page']); ?>&page=<?php echo $page - 1; ?>">
                <i class="fa fa-chevron-left"></i>
              </a>
            </li>
            
            <?php
            $start = max(1, $page - 2);
            $end = min($total_pages, $page + 2);
            
            if ($start > 1): ?>
              <li class="page-item">
                <a class="page-link" href="?<?php echo build_query_string(['page']); ?>&page=1">1</a>
              </li>
              <?php if ($start > 2): ?>
                <li class="page-item disabled"><span class="page-link">...</span></li>
              <?php endif; ?>
            <?php endif; ?>
            
            <?php for ($i = $start; $i <= $end; $i++): ?>
              <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                <a class="page-link" href="?<?php echo build_query_string(['page']); ?>&page=<?php echo $i; ?>">
                  <?php echo $i; ?>
                </a>
              </li>
            <?php endfor; ?>
            
            <?php if ($end < $total_pages): ?>
              <?php if ($end < $total_pages - 1): ?>
                <li class="page-item disabled"><span class="page-link">...</span></li>
              <?php endif; ?>
              <li class="page-item">
                <a class="page-link" href="?<?php echo build_query_string(['page']); ?>&page=<?php echo $total_pages; ?>">
                  <?php echo $total_pages; ?>
                </a>
              </li>
            <?php endif; ?>
            
            <!-- Next -->
            <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
              <a class="page-link" href="?<?php echo build_query_string(['page']); ?>&page=<?php echo $page + 1; ?>">
                <i class="fa fa-chevron-right"></i>
              </a>
            </li>
          </ul>
        </nav>
        
        <p class="text-center text-muted small">
          Halaman <?php echo $page; ?> dari <?php echo $total_pages; ?>
        </p>
      </div>
    </div>
  <?php endif; ?>
</div>

<style>
/* Table styling */
.table thead th {
  font-weight: 600;
  text-transform: uppercase;
  font-size: 0.875rem;
  letter-spacing: 0.5px;
  color: #64748b;
  border-bottom: 2px solid #e2e8f0;
}

.table tbody tr {
  transition: all 0.2s ease;
}

.table tbody tr:hover {
  background-color: #f8f9fa;
  transform: translateX(2px);
}

/* Pagination styling */
.pagination .page-link {
  border-radius: 0.375rem;
  margin: 0 0.25rem;
  border: 1px solid #dee2e6;
  color: #4f46e5;
}

.pagination .page-item.active .page-link {
  background-color: #4f46e5;
  border-color: #4f46e5;
}

.pagination .page-link:hover {
  background-color: #f8f9fa;
  color: #4f46e5;
}

/* Badge styling */
.badge {
  padding: 0.5rem 0.75rem;
  font-weight: 500;
}

/* Card hover effect */
.card {
  transition: all 0.3s ease;
}

.card:hover {
  box-shadow: 0 8px 24px rgba(0,0,0,0.12) !important;
}

/* Input focus */
.form-control:focus,
.form-select:focus {
  border-color: #4f46e5;
  box-shadow: 0 0 0 0.2rem rgba(79, 70, 229, 0.15);
}
</style>

<?php require __DIR__ . '/_footer.php'; ?>
