<?php

namespace App\Http\Controllers\Admin\Master;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Master\AcademicTermRequest;
use App\Http\Requests\Admin\UpdateStatusRequest;
use App\Http\Requests\PaginatedRequest;
use App\Models\AcademicTerm;
use App\Services\Admin\Master\AcademicTermService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class AcademicTermController extends Controller
{
    public function __construct(
        private readonly AcademicTermService $service,
    ) {}

    public function index(PaginatedRequest $request): Response
    {
        return Inertia::render('admin/master/academic-terms/index', [
            'academicTerms' => $this->service->paginated(
                ...$request->validatedWithDefaults(),
                semester: $request->validated('semester'),
                isActive: $request->filled('is_active') ? $request->boolean('is_active') : null,
            ),
            'filters' => $request->only(['semester', 'is_active']),
        ]);
    }

    public function store(AcademicTermRequest $request): RedirectResponse
    {
        $this->service->create($request->validated());

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

        return to_route('admin.master.academic-terms.index');
    }

    public function update(AcademicTermRequest $request, AcademicTerm $academicTerm): RedirectResponse
    {
        $this->service->update($academicTerm, $request->validated());

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

        return to_route('admin.master.academic-terms.index');
    }

    public function destroy(AcademicTerm $academicTerm): RedirectResponse
    {
        $this->service->delete($academicTerm);

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

    public function updateStatus(UpdateStatusRequest $request, AcademicTerm $academicTerm): RedirectResponse
    {
        $this->service->updateActiveStatus($academicTerm, $request->boolean('is_active'));

        return Inertia::flash('toast', ['type' => 'success', 'message' => 'Status periode akademik berhasil diperbarui.'])->back();
    }
}
