<?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;
$type = isset($_GET['type']) ? trim($_GET['type']) : '';
$q = isset($_GET['q']) ? trim($_GET['q']) : '';

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

if ($status !== '') {
    $where[] = 'a.status = ?';
    $params[] = $status;
}
if ($course > 0) {
    $where[] = 'a.course_id = ?';
    $params[] = $course;
}
if ($type !== '') {
    $where[] = 'a.assessment_type = ?';
    $params[] = $type;
}
if ($q !== '') {
    $where[] = '(a.title LIKE ? OR a.description LIKE ?)';
    $params[] = "%$q%";
    $params[] = "%$q%";
}

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

$assessments = $db->getAll(
    "SELECT a.*, c.title AS course_title, u.first_name, u.last_name,
            (SELECT COUNT(*) FROM assessment_submissions WHERE assessment_id = a.id) AS submission_count
     FROM assessments a
     LEFT JOIN courses c ON a.course_id = c.id
     LEFT JOIN users u ON a.created_by = u.id
     $whereSql
     ORDER BY a.created_at DESC
     LIMIT 200",
    $params
);

$courses = $db->getAll("SELECT id, title FROM courses ORDER BY title");

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

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0">Assessments</h1>
    <p class="text-muted mb-0">Manage assessments and quizzes</p>
  </div>
  <div>
    <a href="assessments_edit.php" class="btn btn-primary">
      <i class="fas fa-plus me-2"></i>Add Assessment
    </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>
          <?php foreach (['published','draft','archived'] as $opt): ?>
            <option value="<?php echo $opt; ?>" <?php echo $status===$opt?'selected':''; ?>><?php echo ucfirst($opt); ?></option>
          <?php endforeach; ?>
        </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">Type</label>
        <select name="type" class="form-select">
          <option value="">All</option>
          <?php foreach (['quiz','assignment','exam','survey'] as $opt): ?>
            <option value="<?php echo $opt; ?>" <?php echo $type===$opt?'selected':''; ?>><?php echo ucfirst($opt); ?></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="title or description" 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>Title</th>
            <th>Course</th>
            <th>Type</th>
            <th>Status</th>
            <th>Submissions</th>
            <th>Created</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$assessments): ?>
            <tr><td colspan="8" class="text-center text-muted py-4">No assessments found.</td></tr>
          <?php else: foreach ($assessments as $a): ?>
            <tr>
              <td><?php echo (int)$a['id']; ?></td>
              <td><?php echo htmlspecialchars($a['title'] ?? ''); ?></td>
              <td><?php echo htmlspecialchars($a['course_title'] ?? ''); ?></td>
              <td>
                <span class="badge bg-info"><?php echo htmlspecialchars(ucfirst($a['assessment_type'] ?? '')); ?></span>
              </td>
              <td>
                <?php
                  $statusValue = $a['status'] ?? '';
                  $badgeClass = $statusValue === 'published' ? 'success' : ($statusValue === 'draft' ? 'warning' : 'secondary');
                ?>
                <span class="badge bg-<?php echo $badgeClass; ?>">
                  <?php echo htmlspecialchars(ucfirst($statusValue)); ?>
                </span>
              </td>
              <td><?php echo number_format((int)($a['submission_count'] ?? 0)); ?></td>
              <td><?php echo htmlspecialchars($a['created_at'] ?? ''); ?></td>
              <td class="text-nowrap">
                <a href="assessments_edit.php?id=<?php echo (int)$a['id']; ?>" class="btn btn-sm btn-outline-primary me-1">
                  <i class="fas fa-edit"></i>
                </a>
                <a href="assessments_view.php?id=<?php echo (int)$a['id']; ?>" class="btn btn-sm btn-outline-secondary me-1">
                  <i class="fas fa-eye"></i>
                </a>
              </td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

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