<?php

namespace App\Services\Admin\AcademicClasses;

use App\Models\Material;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\UploadedFile;

class MaterialService
{
    public function paginated(int $perPage = 25, string $search = '', ?int $courseClassId = null): LengthAwarePaginator
    {
        return Material::query()
            ->select(['id', 'course_class_id', 'title', 'description', 'meeting_number'])
            ->with('courseClass.course:id,code,name')
            ->when($search, fn ($q) => $q->where('title', 'like', "%{$search}%"))
            ->when($courseClassId, fn ($q) => $q->where('course_class_id', $courseClassId))
            ->latest()
            ->paginate($perPage);
    }

    public function create(array $data, ?UploadedFile $file): Material
    {
        $material = Material::create([
            'course_class_id' => $data['course_class_id'],
            'title' => $data['title'],
            'description' => $data['description'] ?? null,
            'meeting_number' => $data['meeting_number'] ?? null,
        ]);

        if ($file) {
            $material->addMedia($file)->toMediaCollection('materials');
        }

        return $material;
    }

    public function update(Material $material, array $data, ?UploadedFile $file): Material
    {
        $material->course_class_id = $data['course_class_id'];
        $material->title = $data['title'];
        $material->description = $data['description'] ?? null;
        $material->meeting_number = $data['meeting_number'] ?? null;
        $material->update();

        if ($file) {
            $material->addMedia($file)->toMediaCollection('materials');
        }

        return $material;
    }

    public function delete(Material $material): bool
    {
        return $material->delete();
    }
}
