<?php

namespace App\Http\Controllers;

use App\Enums\PaymentMethod;
use App\Models\Invoice;
use App\Models\Payment;
use App\Services\PaymentService;
use Illuminate\Http\Request;

class PaymentController extends Controller
{
    public function __construct(protected PaymentService $service)
    {
        $this->middleware('permission:payments.view')->only(['index', 'show']);
        $this->middleware('permission:payments.create')->only(['create', 'store']);
    }

    public function index(Request $request)
    {
        $payments = Payment::query()
            ->with(['customer', 'line', 'invoice', 'user'])
            ->search($request->get('q'))
            ->latest('date')
            ->paginate(per_page())
            ->withQueryString();

        return view('payments.index', compact('payments'));
    }

    public function show(Payment $payment)
    {
        $payment->load(['customer', 'line', 'invoice', 'allocations.billingPeriod', 'user']);

        return view('payments.show', compact('payment'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'invoice_id' => ['required', 'exists:invoices,id'],
            'amount' => ['required', 'numeric', 'min:0.01'],
            'payment_method' => ['required', 'in:cash,visa,bank,wallet,other'],
            'notes' => ['nullable', 'string'],
        ]);
        $invoice = Invoice::query()->findOrFail($data['invoice_id']);
        $payment = $this->service->register($invoice, (string) $data['amount'], PaymentMethod::from($data['payment_method']), $request->user(), $data['notes'] ?? null);

        return redirect()->route('payments.show', $payment)->with('success', __('messages.payment_collected'));
    }
}
