<?php
namespace App\Services;

class CourseService {
    public function __construct(private \PDO $pdo) {}

    public function publishedCourses(): array {
        return $this->pdo->query("SELECT c.*, cc.name AS category_name, cl.name AS level_name FROM courses c LEFT JOIN course_categories cc ON c.category_id = cc.id LEFT JOIN course_levels cl ON c.level_id = cl.id WHERE c.is_published = 1 ORDER BY c.is_featured DESC, c.created_at DESC")->fetchAll();
    }

    public function enrollPackageCourses(int $studentId, int $packageId): int {
        $stmt = $this->pdo->prepare("SELECT course_id FROM package_courses WHERE package_id = ? ORDER BY sort_order");
        $stmt->execute([$packageId]);
        $count = 0;
        foreach ($stmt->fetchAll(\PDO::FETCH_COLUMN) as $courseId) {
            $this->pdo->prepare("INSERT IGNORE INTO enrollments (student_id, course_id, package_id, status, enrolled_at) VALUES (?, ?, ?, 'active', NOW())")
                ->execute([$studentId, $courseId, $packageId]);
            $count++;
        }
        return $count;
    }
}
