<?php

namespace App\Http\Controllers\Tenant;

use App\Domain\Billing\PaymentService;
use App\Enums\PaymentMethod;
use App\Http\Controllers\Controller;
use App\Http\Requests\PaymentRequest;
use App\Models\Installment;
use App\Models\Invoice;

class PaymentController extends Controller
{
    /**
     * The one-click payment endpoint: receptionists hit this from the
     * invoice page or the Installments-due screen with amount + method.
     */
    public function store(PaymentRequest $request, Invoice $invoice, PaymentService $payments)
    {
        $this->authorize('recordPayment', $invoice);

        $installment = $request->filled('installment_id')
            ? Installment::where('invoice_id', $invoice->id)->findOrFail($request->integer('installment_id'))
            : null;

        $payment = $payments->record(
            invoice: $invoice,
            amount: $request->integer('amount'),
            method: $request->enum('method', PaymentMethod::class),
            installment: $installment,
            reference: $request->reference,
            note: $request->note,
            receivedBy: $request->user()->id,
        );

        return back()->with('status', __(':amount IQD received (:method).', [
            'amount' => number_format($payment->amount),
            'method' => $payment->method->label(),
        ]));
    }
}
