<?php

namespace App\Http\Controllers;

use App\Models\Payment;
use App\Services\PaymentDocumentPresenter;
use App\Services\PaymentPdfGenerator;
use Illuminate\Http\Request;

class PublicPaymentController extends Controller
{
    public function __construct(
        private readonly PaymentDocumentPresenter $presenter,
        private readonly PaymentPdfGenerator $pdfGenerator,
    ) {}

    public function show(string $token, Request $request)
    {
        $payment = $this->resolveByToken($token);
        $data = $this->presenter->displayData($payment);
        $copyKey = $request->query('copy', 'original');
        $data['documentCopyLabel'] = $data['documentCopies'][$copyKey] ?? 'Original Copy';
        $data['forPublic'] = true;
        $data['shareToken'] = $token;

        return view('public.payments.show', $data);
    }

    public function pdf(string $token, Request $request)
    {
        $payment = $this->resolveByToken($token);
        $data = $this->presenter->displayData($payment);
        $copyLabel = $data['documentCopies'][$request->query('copy', 'original')] ?? 'Original Copy';

        if ($request->boolean('inline')) {
            return $this->pdfGenerator->stream($payment, $data, $copyLabel);
        }

        return $this->pdfGenerator->download($payment, $data, $copyLabel);
    }

    public function print(string $token, Request $request)
    {
        return view('admin.payments.print-pdf', [
            'payment' => $this->resolveByToken($token),
            'copyKey' => $request->query('copy', 'original'),
            'autoprint' => $request->boolean('autoprint', true),
            'backUrl' => route('public.payments.show', $token),
            'pdfUrl' => route('public.payments.pdf', ['token' => $token, 'copy' => $request->query('copy', 'original'), 'inline' => 1]),
        ]);
    }

    private function resolveByToken(string $token): Payment
    {
        $payment = Payment::with(['allocations', 'customer', 'vendor'])
            ->where('share_token', $token)
            ->first();

        if (! $payment) {
            abort(404, 'This payment link is invalid or has expired.');
        }

        return $payment;
    }
}
