<?php

namespace App\Http\Controllers\Admin\Finances;

use App\Enums\StudentStatus;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Finances\TuitionInvoiceRequest;
use App\Http\Requests\PaginatedRequest;
use App\Models\TuitionInvoice;
use App\Services\Admin\Finances\TuitionInvoiceService;
use App\Services\Admin\Master\AcademicTermService;
use App\Services\Admin\Users\StudentService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class TuitionInvoiceController extends Controller
{
    public function __construct(
        private readonly TuitionInvoiceService $service,
        private readonly StudentService $studentService,
        private readonly AcademicTermService $academicTermService,
    ) {}

    public function index(PaginatedRequest $request): Response
    {
        $students = $this->studentService->getAllForSelect(status: StudentStatus::Active->value);

        $invoicedTermIdsByStudent = $this->service->getInvoicedTermIdsByStudent($students->pluck('id')->all());

        $students->each(function ($student) use ($invoicedTermIdsByStudent) {
            $student->invoiced_term_ids = $invoicedTermIdsByStudent->get($student->id, []);
        });

        $academicTerms = $this->academicTermService->getAllForSelect();

        $requestedTermId = $request->validated('academic_term_id');
        $summaryTermId = $requestedTermId ?? $this->academicTermService->getActive()?->id;

        return Inertia::render('admin/finances/tuition-invoices/index', [
            'invoices' => $this->service->paginated(
                ...$request->validatedWithDefaults(),
                academicTermId: $requestedTermId,
                status: $request->validated('status'),
                paymentMethod: $request->validated('payment_method'),
            ),
            'summary' => $this->service->summary(
                search: $request->validated('search') ?? '',
                academicTermId: $summaryTermId,
            ),
            'summaryAcademicTerm' => $academicTerms->firstWhere('id', $summaryTermId),
            'students' => $students,
            'academicTerms' => $academicTerms,
            'filters' => $request->only(['academic_term_id', 'status', 'payment_method']),
        ]);
    }

    public function store(TuitionInvoiceRequest $request): RedirectResponse
    {
        $this->service->createMany($request->validated('student_ids'), $request->validated());

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

        return to_route('admin.finances.tuition-invoices.index');
    }

    public function update(TuitionInvoiceRequest $request, TuitionInvoice $tuitionInvoice): RedirectResponse
    {
        $this->service->update($tuitionInvoice, $request->validated());

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

        return to_route('admin.finances.tuition-invoices.index');
    }

    public function destroy(TuitionInvoice $tuitionInvoice): RedirectResponse
    {
        $this->service->delete($tuitionInvoice);

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