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

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

$errors = [];
$success = getFlashMessage('success');
$errorFlash = getFlashMessage('error');
if ($errorFlash) {
    $errors[] = $errorFlash;
}

// Handle actions (enroll)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'enroll') {
    if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'student') {
        setFlashMessage('error', 'Only students can enroll in courses.');
        header('Location: courses.php');
        exit;
    }

    $courseId = (int)($_POST['course_id'] ?? 0);
    try {
        $courseModel->enroll($courseId, $user['id']);
        setFlashMessage('success', 'Enrolled successfully.');
        header('Location: courses.php');
        exit;
    } catch (Exception $e) {
        $errors[] = $e->getMessage();
    }
}

// Filters
$filters = [];
if (!empty($_GET['category_id'])) {
    $filters['category_id'] = (int)$_GET['category_id'];
}
if (!empty($_GET['level'])) {
    $filters['level'] = trim($_GET['level']);
}
if (!empty($_GET['search'])) {
    $filters['search'] = trim($_GET['search']);
}
if (isset($_GET['free_only']) && $_GET['free_only']) {
    $filters['free_only'] = true;
}
if (!empty($_GET['sort'])) {
    $filters['sort'] = trim($_GET['sort']);
}

// Apply region filter for students (optional) - Course::getCourses supports region
if (isset($_SESSION['region'])) {
    $filters['region'] = $_SESSION['region'];
}

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

// Pagination
$perPage = 12;
$page = max(1, (int)($_GET['page'] ?? 1));
$total = $courseModel->countCourses($filters);
$totalPages = max(1, (int)ceil($total / $perPage));
$offset = ($page - 1) * $perPage;

$courses = $courseModel->getCourses($filters, $perPage, $offset);

// If instructor requested their own courses, override with instructor-specific list
if (!empty($_GET['mine']) && hasRole('instructor')) {
    $courses = $courseModel->getInstructorCourses($user['id']);
    $total = count($courses);
    $totalPages = max(1, (int)ceil($total / $perPage));
}

// If a single course is requested, show course detail and lessons
if (!empty($_GET['course_id'])) {
    $courseId = (int)$_GET['course_id'];
    $course = $courseModel->getById($courseId);
    if (!$course) {
        setFlashMessage('error', 'Course not found.');
        header('Location: ' . APP_URL . '/lms/courses.php');
        exit;
    }

    $lessons = $courseModel->getLessons($courseId);
    $pageTitle = 'Course - ' . htmlspecialchars($course['title']);
    include __DIR__ . '/includes/header.php';
    ?>

    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h4 mb-0"><?php echo htmlspecialchars($course['title']); ?></h1>
            <p class="text-muted mb-0"><?php echo htmlspecialchars($course['short_description'] ?? ''); ?></p>
        </div>
        <div>
            <?php if (hasRole('instructor') && $course['instructor_id'] === $user['id']): ?>
                <a href="<?php echo APP_URL; ?>/lms/lessons_edit.php?course_id=<?php echo (int)$courseId; ?>" class="btn btn-primary">New Lesson</a>
                <a href="<?php echo APP_URL; ?>/lms/courses_edit.php?id=<?php echo (int)$courseId; ?>" class="btn btn-outline-secondary ms-2">Edit Course</a>
            <?php endif; ?>
        </div>
    </div>

    <div class="row">
        <div class="col-md-8">
            <div class="card mb-4">
                <div class="card-body">
                    <?php echo nl2br(htmlspecialchars($course['description'])); ?>
                </div>
            </div>

            <div class="card">
                <div class="card-header d-flex align-items-center justify-content-between">
                    <h5 class="m-0">Lessons</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($lessons)): ?>
                        <p class="text-muted">No lessons yet.</p>
                    <?php else: ?>
                        <ul class="list-group">
                            <?php foreach ($lessons as $l): ?>
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    <div>
                                        <a href="<?php echo APP_URL; ?>/lms/lesson.php?id=<?php echo (int)$l['id']; ?>"><?php echo htmlspecialchars($l['title']); ?></a>
                                        <div class="text-muted small"><?php echo htmlspecialchars($l['content_type']); ?></div>
                                    </div>
                                    <div>
                                        <?php if (hasRole('instructor') && $course['instructor_id'] === $user['id']): ?>
                                            <a class="btn btn-sm btn-outline-secondary" href="<?php echo APP_URL; ?>/lms/lessons_edit.php?id=<?php echo (int)$l['id']; ?>">Edit</a>
                                        <?php endif; ?>
                                        <?php if ($l['content_type'] === 'quiz'): ?>
                                            <a class="btn btn-sm btn-primary ms-2" href="<?php echo APP_URL; ?>/lms/assessments.php?lesson_id=<?php echo (int)$l['id']; ?>">Open Quiz</a>
                                        <?php endif; ?>
                                    </div>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="col-md-4">
            <div class="card">
                <div class="card-body">
                    <h6>Instructor</h6>
                    <p class="mb-0"><?php echo htmlspecialchars($course['first_name'] . ' ' . $course['last_name']); ?></p>
                </div>
            </div>
        </div>
    </div>

    <?php include __DIR__ . '/includes/footer.php';
    exit;
}

$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"><?php echo isset($_GET['mine']) && $_GET['mine'] ? 'My Courses' : 'Courses'; ?></h1>
        <p class="text-muted mb-0"><?php echo isset($_GET['mine']) && $_GET['mine'] ? 'Manage your courses.' : 'Browse and enroll in available courses.'; ?></p>
    </div>
    <?php if (hasRole('instructor')): ?>
    <div>
        <a href="<?php echo APP_URL; ?>/lms/courses_edit.php" class="btn btn-primary">New Course</a>
    </div>
    <?php endif; ?>
</div>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger">
        <ul class="mb-0">
            <?php foreach ($errors as $err): ?>
                <li><?php echo htmlspecialchars($err); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<?php if (!empty($success)): ?>
    <div class="alert alert-success">
        <?php echo htmlspecialchars($success); ?>
    </div>
<?php endif; ?>

<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 courses..." value="<?php echo htmlspecialchars($_GET['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 (int)($_GET['category_id'] ?? 0) === (int)$cat['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($cat['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-2">
                <select name="level" class="form-select">
                    <option value="">Any level</option>
                    <?php foreach (['beginner','intermediate','advanced','all_levels'] as $opt): ?>
                        <option value="<?php echo $opt; ?>" <?php echo (($_GET['level'] ?? '') === $opt) ? 'selected' : ''; ?>><?php echo ucfirst($opt); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-2">
                <select name="sort" class="form-select">
                    <option value="">Sort</option>
                    <option value="popular" <?php echo (($_GET['sort'] ?? '') === 'popular') ? 'selected' : ''; ?>>Most popular</option>
                    <option value="rating" <?php echo (($_GET['sort'] ?? '') === 'rating') ? 'selected' : ''; ?>>Top rated</option>
                    <option value="newest" <?php echo (($_GET['sort'] ?? '') === 'newest') ? 'selected' : ''; ?>>Newest</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">
                <img src="<?php echo htmlspecialchars($c['thumbnail'] ?? (APP_URL . '/assets/materio/assets/img/illustrations/course.png')); ?>" 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">By <?php echo htmlspecialchars($c['first_name'] . ' ' . $c['last_name']); ?> • <?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-2 mb-2">
                        <span class="small text-warning"><i class="ri ri-star-fill"></i> <?php echo round((float)$c['rating'], 1); ?></span>
                    </div>

                    <div class="mt-auto d-flex justify-content-between align-items-center pt-3">
                        <div>
                            <?php if ($c['price'] > 0): ?>
                                <div class="fw-semibold"><?php echo htmlspecialchars(number_format($c['price'], 2)); ?> <?php echo htmlspecialchars($c['currency']); ?></div>
                            <?php else: ?>
                                <div class="fw-semibold">Free</div>
                            <?php endif; ?>
                            <small class="text-muted"><?php echo (int)$c['enrollment_count']; ?> enrolled</small>
                        </div>

                        <div>
                            <?php if (isset($_SESSION['role']) && $_SESSION['role'] === 'student' && $courseModel->isEnrolled($c['id'], $user['id'])): ?>
                                <a href="dashboard.php" class="btn btn-outline-secondary btn-sm"><i class="ri ri-arrow-right-line me-1"></i>Go to Course</a>
                            <?php elseif (isset($_SESSION['role']) && $_SESSION['role'] === 'student'): ?>
                                <form method="post" class="d-inline">
                                    <input type="hidden" name="action" value="enroll">
                                    <input type="hidden" name="course_id" value="<?php echo (int)$c['id']; ?>">
                                    <button class="btn btn-primary btn-sm"><i class="ri ri-book-open-line me-1"></i>Enroll</button>
                                </form>
                            <?php else: ?>
                                <a href="login.php" class="btn btn-primary btn-sm"><i class="ri ri-login-box-line me-1"></i>Login to Enroll</a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    <?php endforeach; endif; ?>
</div>

<?php if ($totalPages > 1): ?>
<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 <= $totalPages; $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 >= $totalPages ? 'disabled' : ''; ?>">
      <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => min($totalPages, $page + 1)])); ?>" aria-label="Next">
        <span aria-hidden="true">&raquo;</span>
      </a>
    </li>
  </ul>
</nav>
<?php endif; ?>

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