<?php

namespace App\Http\Controllers\Admin\Finances;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Finances\TuitionPaymentRequest;
use App\Models\TuitionInvoice;
use App\Models\TuitionPayment;
use App\Services\Admin\Finances\TuitionPaymentService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class TuitionPaymentController extends Controller
{
    public function __construct(
        private readonly TuitionPaymentService $service,
    ) {}

    public function index(TuitionInvoice $tuitionInvoice): Response
    {
        $tuitionInvoice->load(['student.user.profile', 'student.department', 'academicTerm']);

        return Inertia::render('admin/finances/tuition-invoices/payments', [
            'invoice' => $tuitionInvoice,
            'payments' => $this->service->forInvoice($tuitionInvoice),
        ]);
    }

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

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

    public function update(TuitionPaymentRequest $request, TuitionInvoice $tuitionInvoice, TuitionPayment $payment): RedirectResponse
    {
        $this->service->update($payment, $request->validated(), $request->file('proof'));

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

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

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