<?php

namespace App\Services\Admin\Manage;

use App\Models\CourseClass;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;

class CourseClassService
{
    public function getAllForSelect(): Collection
    {
        return CourseClass::select(['id', 'course_id', 'academic_term_id'])
            ->with('course:id,code,name,semester_number,department_id')
            ->get();
    }

    public function paginated(int $perPage = 25, string $search = '', ?int $academicTermId = null, ?string $method = null): LengthAwarePaginator
    {
        return CourseClass::query()
            ->select(['id', 'course_id', 'lecturer_id', 'academic_term_id', 'method'])
            ->withCount('enrollments')
            ->with(['course:id,code,name,department_id', 'lecturer.user.profile', 'academicTerm:id,name,semester,start_date,end_date'])
            ->when($search, fn ($q) => $q->whereHas('course', fn ($q) => $q->where('name', 'like', "%{$search}%")->orWhere('code', 'like', "%{$search}%")))
            ->when($academicTermId, fn ($q) => $q->where('academic_term_id', $academicTermId))
            ->when($method, fn ($q) => $q->where('method', $method))
            ->latest()
            ->paginate($perPage);
    }

    public function create(array $data): CourseClass
    {
        return CourseClass::create($data);
    }

    public function update(CourseClass $courseClass, array $data): CourseClass
    {
        $courseClass->course_id = $data['course_id'];
        $courseClass->lecturer_id = $data['lecturer_id'];
        $courseClass->academic_term_id = $data['academic_term_id'];
        $courseClass->method = $data['method'] ?? null;
        $courseClass->update();

        return $courseClass;
    }

    public function delete(CourseClass $courseClass): bool
    {
        return $courseClass->delete();
    }
}
