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

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

$db = Database::getInstance();

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

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

if ($status !== '') {
    $where[] = 'c.status = ?';
    $params[] = $status;
}
if ($category > 0) {
    $where[] = 'c.category_id = ?';
    $params[] = $category;
}
if ($instructor > 0) {
    $where[] = 'c.instructor_id = ?';
    $params[] = $instructor;
}
if ($q !== '') {
    $where[] = '(c.title LIKE ? OR c.description LIKE ?)';
    $params[] = "%$q%";
    $params[] = "%$q%";
}

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

$courses = $db->getAll(
    "SELECT c.*, cat.name AS category_name, u.first_name, u.last_name,
            (SELECT COUNT(*) FROM course_enrollments WHERE course_id = c.id) AS enrollment_count
     FROM courses c
     LEFT JOIN categories cat ON c.category_id = cat.id
     LEFT JOIN users u ON c.instructor_id = u.id
     $whereSql
     ORDER BY c.created_at DESC
     LIMIT 200",
    $params
);

$categories = $db->getAll("SELECT id, name FROM categories ORDER BY name");
$instructors = $db->getAll(
    "SELECT DISTINCT u.id, u.first_name, u.last_name
     FROM users u
     JOIN user_roles ur ON u.id = ur.user_id
     WHERE ur.role = 'instructor' AND u.status = 'active'
     ORDER BY u.last_name, u.first_name"
);

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

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0">Courses</h1>
    <p class="text-muted mb-0">Manage courses and content</p>
  </div>
  <div>
    <a href="courses_edit.php" class="btn btn-primary">
      <i class="fas fa-plus me-2"></i>Add Course
    </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">Category</label>
        <select name="category" class="form-select">
          <option value="">All</option>
          <?php foreach ($categories as $cat): ?>
            <option value="<?php echo (int)$cat['id']; ?>" <?php echo $category===$cat['id']?'selected':''; ?>><?php echo htmlspecialchars($cat['name']); ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-sm-3">
        <label class="form-label">Instructor</label>
        <select name="instructor" class="form-select">
          <option value="">All</option>
          <?php foreach ($instructors as $ins): ?>
            <option value="<?php echo (int)$ins['id']; ?>" <?php echo $instructor===$ins['id']?'selected':''; ?>><?php echo htmlspecialchars($ins['first_name'] . ' ' . $ins['last_name']); ?></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>Instructor</th>
            <th>Category</th>
            <th>Status</th>
            <th>Enrollments</th>
            <th>Created</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$courses): ?>
            <tr><td colspan="8" class="text-center text-muted py-4">No courses found.</td></tr>
          <?php else: foreach ($courses as $c): ?>
            <tr>
              <td><?php echo (int)$c['id']; ?></td>
              <td><?php echo htmlspecialchars($c['title'] ?? ''); ?></td>
              <td><?php echo htmlspecialchars(($c['first_name'] ?? '') . ' ' . ($c['last_name'] ?? '')); ?></td>
              <td><?php echo htmlspecialchars($c['category_name'] ?? ''); ?></td>
              <td>
                <span class="badge bg-<?php echo $c['status']==='published'?'success':($c['status']==='draft'?'warning':'secondary'); ?>">
                  <?php echo htmlspecialchars(ucfirst($c['status'] ?? '')); ?>
                </span>
              </td>
              <td><?php echo number_format((int)($c['enrollment_count'] ?? 0)); ?></td>
              <td><?php echo htmlspecialchars($c['created_at'] ?? ''); ?></td>
              <td class="text-nowrap">
                <a href="courses_edit.php?id=<?php echo (int)$c['id']; ?>" class="btn btn-sm btn-outline-primary me-1">
                  <i class="fas fa-edit me-1"></i>Edit
                </a>
                <a href="courses_view.php?id=<?php echo (int)$c['id']; ?>" class="btn btn-sm btn-outline-secondary me-1">
                  <i class="fas fa-eye me-1"></i>View
                </a>
              </td>
            </tr>
          <?php endforeach; endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

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