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

requireLogin();
requireAnyRole(['instructor']);

$user = getCurrentUser();
$db = Database::getInstance();
$courseModel = new Course();

// Filters
$search = trim($_GET['search'] ?? '');
$category_id = (int)($_GET['category_id'] ?? 0);
$status = trim($_GET['status'] ?? '');
$sort = trim($_GET['sort'] ?? 'newest');

$perPage = 10;
$page = max(1, (int)($_GET['page'] ?? 1));
$offset = ($page - 1) * $perPage;

$where = "c.instructor_id = ?";
$params = [$user['id']];

if ($category_id) {
    $where .= " AND c.category_id = ?";
    $params[] = $category_id;
}
if (!empty($status)) {
    $where .= " AND c.status = ?";
    $params[] = $status;
}
if (!empty($search)) {
    $where .= " AND (c.title LIKE ? OR c.short_description LIKE ? OR c.description LIKE ? )";
    $s = "%{$search}%";
    $params[] = $s; $params[] = $s; $params[] = $s;
}

$orderBy = "c.created_at DESC";
if ($sort === 'popular') $orderBy = "c.enrollment_count DESC";
if ($sort === 'rating') $orderBy = "c.rating DESC";

$totalRow = $db->get("SELECT COUNT(*) as cnt FROM courses c WHERE {$where}", $params);
$total = (int)($totalRow['cnt'] ?? 0);

$params[] = $perPage;
$params[] = $offset;

$sql = "SELECT c.*, cat.name as category_name, u.first_name, u.last_name FROM courses c LEFT JOIN categories cat ON c.category_id = cat.id LEFT JOIN users u ON c.instructor_id = u.id WHERE {$where} ORDER BY {$orderBy} LIMIT ? OFFSET ?";
$courses = $db->getAll($sql, $params);

$categories = $db->getAll("SELECT id, name FROM categories WHERE is_active = 1 ORDER BY name");

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

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="h4 mb-0">My Courses</h1>
        <p class="text-muted mb-0">Manage your courses and content.</p>
    </div>
    <div>
        <a href="<?php echo APP_URL; ?>/lms/courses_edit.php" class="btn btn-primary">New Course</a>
    </div>
</div>

<div class="card mb-4">
    <div class="card-body">
        <form method="get" class="row g-3">
            <div class="col-md-4">
                <input type="search" name="search" class="form-control" placeholder="Search my courses..." value="<?php echo htmlspecialchars($search); ?>">
            </div>
            <div class="col-md-3">
                <select name="category_id" class="form-select">
                    <option value="">All categories</option>
                    <?php foreach ($categories as $cat): ?>
                        <option value="<?php echo (int)$cat['id']; ?>" <?php echo $category_id === (int)$cat['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($cat['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <select name="status" class="form-select">
                    <option value="">Any status</option>
                    <?php foreach (['draft','published','archived','suspended'] as $opt): ?>
                        <option value="<?php echo $opt; ?>" <?php echo ($status === $opt ? 'selected' : ''); ?>><?php echo ucfirst($opt); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <select name="sort" class="form-select">
                    <option value="newest" <?php echo ($sort === 'newest' ? 'selected' : ''); ?>>Newest</option>
                    <option value="popular" <?php echo ($sort === 'popular' ? 'selected' : ''); ?>>Most popular</option>
                    <option value="rating" <?php echo ($sort === 'rating' ? 'selected' : ''); ?>>Top rated</option>
                </select>
            </div>
            <div class="col-md-1 text-end">
                <button class="btn btn-primary">Filter</button>
            </div>
        </form>
    </div>
</div>

<div class="row g-3">
    <?php if (!$courses): ?>
        <div class="col-12">
            <div class="card"><div class="card-body text-center text-muted">No courses found.</div></div>
        </div>
    <?php else: foreach ($courses as $c): ?>
        <div class="col-12 col-md-6 col-xl-4">
            <div class="card h-100">
                <?php
                    $thumb = $c['thumbnail'] ?? '';
                    $thumbLocal = $thumb ? __DIR__ . '/../' . ltrim($thumb, '/') : '';
                    if ($thumb && file_exists($thumbLocal)) {
                        $thumbSrc = (stripos($thumb, 'http') === 0) ? $thumb : APP_URL . '/' . ltrim($thumb, '/');
                    } else {
                        $thumbSrc = APP_URL . '/assets/materio/assets/img/illustrations/course.png';
                    }
                ?>
                <img src="<?php echo htmlspecialchars($thumbSrc); ?>" class="card-img-top" alt="<?php echo htmlspecialchars($c['title']); ?>">
                <div class="card-body d-flex flex-column">
                    <h5 class="card-title mb-1"><?php echo htmlspecialchars($c['title']); ?></h5>
                    <small class="text-muted"><?php echo htmlspecialchars($c['category_name']); ?></small>
                    <p class="mt-2 mb-0 text-truncate"><?php echo htmlspecialchars(substr($c['short_description'] ?? $c['description'], 0, 120)); ?></p>

                    <div class="mt-auto d-flex justify-content-between align-items-center pt-3">
                        <div>
                            <a href="<?php echo APP_URL; ?>/lms/courses_edit.php?id=<?php echo (int)$c['id']; ?>" class="btn btn-outline-secondary btn-sm">Edit</a>
                            <a href="<?php echo APP_URL; ?>/lms/lessons_edit.php?course_id=<?php echo (int)$c['id']; ?>" class="btn btn-sm btn-primary ms-2">Manage Lessons</a>
                        </div>
                        <div>
                            <a href="<?php echo APP_URL; ?>/lms/enrollments.php" class="btn btn-sm btn-outline-primary">Enrollments</a>
                            <a href="<?php echo APP_URL; ?>/lms/assessments.php?course_id=<?php echo (int)$c['id']; ?>" class="btn btn-sm btn-outline-secondary ms-2">Assessments</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    <?php endforeach; endif; ?>
</div>

<?php if ($total > $perPage): ?>
<nav aria-label="Page navigation">
  <ul class="pagination justify-content-center mt-4">
    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
      <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => max(1, $page - 1)])); ?>" aria-label="Previous">
        <span aria-hidden="true">&laquo;</span>
      </a>
    </li>
    <?php for ($p = 1; $p <= ceil($total / $perPage); $p++): ?>
      <li class="page-item <?php echo $p === $page ? 'active' : ''; ?>"><a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $p])); ?>"><?php echo $p; ?></a></li>
    <?php endfor; ?>
    <li class="page-item <?php echo $page >= ceil($total / $perPage) ? 'disabled' : ''; ?>">
      <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => min(ceil($total / $perPage), $page + 1)])); ?>" aria-label="Next">
        <span aria-hidden="true">&raquo;</span>
      </a>
    </li>
  </ul>
</nav>
<?php endif; ?>

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