<?php

namespace App\Http\Controllers\Admin\AcademicClasses;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\AcademicClasses\MaterialRequest;
use App\Http\Requests\PaginatedRequest;
use App\Models\Material;
use App\Services\Admin\AcademicClasses\MaterialService;
use App\Services\Admin\Manage\CourseClassService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class MaterialController extends Controller
{
    public function __construct(
        private readonly MaterialService $service,
        private readonly CourseClassService $courseClassService,
    ) {}

    public function index(PaginatedRequest $request): Response
    {
        return Inertia::render('admin/academic-classes/materials/index', [
            'materials' => $this->service->paginated(
                $request->user(),
                ...$request->validatedWithDefaults(),
                courseClassId: $request->validated('course_class_id'),
            ),
            'courseClasses' => $this->courseClassService->getAllForSelect($request->user()),
            'filters' => $request->only(['course_class_id']),
        ]);
    }

    public function store(MaterialRequest $request): RedirectResponse
    {
        $this->service->create($request->validated(), $request->file('file'));

        Inertia::flash('toast', ['type' => 'success', 'message' => 'Materi berhasil ditambahkan.']);

        return to_route('admin.academic-classes.materials.index');
    }

    public function update(MaterialRequest $request, Material $material): RedirectResponse
    {
        $this->service->update($material, $request->validated(), $request->file('file'));

        Inertia::flash('toast', ['type' => 'success', 'message' => 'Materi berhasil diperbarui.']);

        return to_route('admin.academic-classes.materials.index');
    }

    public function destroy(Material $material): RedirectResponse
    {
        $this->service->delete($material);

        return Inertia::flash('toast', ['type' => 'success', 'message' => 'Materi berhasil dihapus.'])->back();
    }
}
