<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\PaymentResource;
use App\Models\Payment;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class PaymentController extends Controller
{
    public function index(Request $request): AnonymousResourceCollection
    {
        $payments = Payment::query()
            ->with(['allocations.invoice', 'recordedBy'])
            ->when($request->input('status'), fn ($q, $status) => $q->where('status', $status))
            ->when($request->input('gateway'), fn ($q, $gateway) => $q->where('gateway', $gateway))
            ->when($request->input('gateway_status'), fn ($q, $gatewayStatus) => $q->where('gateway_status', $gatewayStatus))
            ->when($request->input('payment_method'), fn ($q, $method) => $q->where('payment_method', $method))
            ->latest('payment_date')
            ->paginate($request->integer('per_page', 25));

        return PaymentResource::collection($payments);
    }

    public function show(Request $request, Payment $payment): PaymentResource
    {
        $payment->load(['allocations.invoice', 'recordedBy']);

        return new PaymentResource($payment);
    }
}
