<?php
require_once __DIR__ . '/../config/database.php';

requireLogin();
requireAnyRole(['admin', 'super_admin']);

$db = Database::getInstance();

$status = isset($_GET['status']) ? trim($_GET['status']) : '';
$course = isset($_GET['course']) ? (int)$_GET['course'] : 0;
$student = isset($_GET['student']) ? (int)$_GET['student'] : 0;
$q = isset($_GET['q']) ? trim($_GET['q']) : '';

$where = [];
$params = [];

if ($status !== '') {
    $where[] = 'cert.is_revoked = ?';
    $params[] = ($status === 'active' ? 0 : 1);
}
if ($course > 0) {
    $where[] = 'cert.course_id = ?';
    $params[] = $course;
}
if ($student > 0) {
    $where[] = 'cert.student_id = ?';
    $params[] = $student;
}
if ($q !== '') {
    $where[] = '(cert.certificate_name LIKE ? OR u.username LIKE ? OR u.email LIKE ? OR CONCAT_WS(" ", u.first_name, u.last_name) LIKE ? OR c.title LIKE ?)';
    $params[] = "%$q%";
    $params[] = "%$q%";
    $params[] = "%$q%";
    $params[] = "%$q%";
    $params[] = "%$q%";
}

$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

$certificates = $db->getAll(
    "SELECT cert.*, c.title AS course_title, u.username, u.email, u.first_name, u.last_name
     FROM certificates cert
     JOIN courses c ON cert.course_id = c.id
     JOIN users u ON cert.student_id = u.id
     $whereSql
     ORDER BY cert.issue_date DESC
     LIMIT 200",
    $params
);

$courses = $db->getAll("SELECT id, title FROM courses ORDER BY title");
$students = $db->getAll(
    "SELECT u.id, u.username, u.first_name, u.last_name
     FROM users u
     JOIN user_roles ur ON u.id = ur.user_id
     WHERE ur.role = 'student' AND u.status = 'active'
     ORDER BY u.last_name, u.first_name"
);

$pageTitle = 'Certificates';
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0">Certificates</h1>
    <p class="text-muted mb-0">Manage issued certificates</p>
  </div>
  <div>
    <a href="certificates_edit.php" class="btn btn-primary">
      <i class="fas fa-plus me-2"></i>Issue Certificate
    </a>
  </div>
</div>

<div class="card mb-4">
  <div class="card-header">
    <form method="get" class="row g-3">
      <div class="col-sm-3">
        <label class="form-label">Status</label>
        <select name="status" class="form-select">
          <option value="">All</option>
          <option value="active" <?php echo $status==='active'?'selected':''; ?>>Active</option>
          <option value="revoked" <?php echo $status==='revoked'?'selected':''; ?>>Revoked</option>
        </select>
      </div>
      <div class="col-sm-3">
        <label class="form-label">Course</label>
        <select name="course" class="form-select">
          <option value="">All</option>
          <?php foreach ($courses as $c): ?>
            <option value="<?php echo (int)$c['id']; ?>" <?php echo $course===$c['id']?'selected':''; ?>><?php echo htmlspecialchars($c['title']); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-sm-3">
        <label class="form-label">Student</label>
        <select name="student" class="form-select">
          <option value="">All</option>
          <?php foreach ($students as $s): ?>
            <option value="<?php echo (int)$s['id']; ?>" <?php echo $student===$s['id']?'selected':''; ?>><?php echo htmlspecialchars($s['first_name'] . ' ' . $s['last_name'] . ' (' . $s['username'] . ')'); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-sm-3">
        <label class="form-label">Search</label>
        <input type="text" name="q" class="form-control" placeholder="name, email, course, certificate" value="<?php echo htmlspecialchars($q); ?>">
      </div>
      <div class="col-12">
        <button class="btn btn-primary" type="submit">Filter</button>
      </div>
    </form>
  </div>
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table table-striped table-hover mb-0">
        <thead>
          <tr>
            <th>ID</th>
            <th>Certificate</th>
            <th>Student</th>
            <th>Course</th>
            <th>Status</th>
            <th>Issued</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$certificates): ?>
            <tr><td colspan="7" class="text-center text-muted py-4">No certificates found.</td></tr>
          <?php else: foreach ($certificates as $c): ?>
            <tr>
              <td><?php echo (int)$c['id']; ?></td>
              <td><?php echo htmlspecialchars($c['certificate_name'] ?? ''); ?></td>
              <td>
                <div>
                  <strong><?php echo htmlspecialchars(($c['first_name'] ?? '') . ' ' . ($c['last_name'] ?? '')); ?></strong><br>
                  <small class="text-muted"><?php echo htmlspecialchars($c['username'] ?? ''); ?></small>
                </div>
              </td>
              <td><?php echo htmlspecialchars($c['course_title'] ?? ''); ?></td>
              <td>
                <span class="badge bg-<?php echo $c['is_revoked'] ? 'danger' : 'success'; ?>">
                  <?php echo $c['is_revoked'] ? 'Revoked' : 'Active'; ?>
                </span>
              </td>
              <td><?php echo htmlspecialchars($c['issue_date'] ?? ''); ?></td>
              <td class="text-nowrap">
                <a href="certificates_view.php?id=<?php echo (int)$c['id']; ?>" class="btn btn-sm btn-outline-secondary me-1">
                  <i class="fas fa-eye"></i>
                </a>
                <?php if (!$c['is_revoked']): ?>
                  <a href="certificates_revoke.php?id=<?php echo (int)$c['id']; ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Revoke this certificate?');">
                    <i class="fas fa-ban"></i>
                  </a>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

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