<?php

namespace App\Http\Controllers;

use App\Actions\Payments\SubmitPaymentProofAction;
use App\Http\Requests\Payments\StorePaymentProofRequest;
use App\Models\EventPaymentProof;
use App\Models\EventRegistration;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
use InvalidArgumentException;
use Symfony\Component\HttpFoundation\StreamedResponse;

class PaymentProofController extends Controller
{
    public function create(EventRegistration $registration): View
    {
        $this->authorize('view', $registration);

        $registration->load(['event.paymentMethods.manualPaymentMethod']);

        return view('pages.registrations.payment-proof', [
            'registration' => $registration,
            'paymentMethods' => $registration->event->paymentMethods()
                ->where('is_active', true)
                ->with('manualPaymentMethod')
                ->get()
                ->pluck('manualPaymentMethod')
                ->filter(fn ($method) => $method?->is_active),
        ]);
    }

    public function store(
        StorePaymentProofRequest $request,
        EventRegistration $registration,
        SubmitPaymentProofAction $action,
    ): RedirectResponse {
        try {
            $action->execute(
                $registration,
                auth()->user(),
                $request->validated(),
                $request->file('proof'),
            );
        } catch (InvalidArgumentException $e) {
            return back()->withInput()->withErrors(['proof' => $e->getMessage()]);
        }

        return redirect()
            ->route('registrations.show', $registration)
            ->with('status', __('events.flash.payment_proof_uploaded'));
    }

    public function show(EventPaymentProof $proof): StreamedResponse
    {
        $this->authorize('view', $proof);

        return Storage::disk('payment_proofs')->download(
            $proof->file_path,
            $proof->original_name,
            ['Content-Type' => $proof->mime_type],
        );
    }
}
