<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\WalletTransaction;
use App\Services\ReceiptPdfService;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class DownloadWalletReceiptController extends Controller
{
    public function __invoke(Request $request, WalletTransaction $transaction): Response
    {
        if (! $request->user()?->isAdminOrSuperAdmin()) {
            abort(403);
        }

        if (! $transaction->canDownloadReceipt()) {
            abort(404);
        }

        $pdfBinary = app(ReceiptPdfService::class)->generateWalletTransactionReceiptPdf(
            fullName: (string) ($transaction->user?->name ?: 'Member'),
            type: (string) $transaction->type,
            currencyCode: (string) $transaction->currency_code,
            amount: (float) $transaction->amount,
            reference: $transaction->transaction_code ?: (string) $transaction->id,
            phoneOrBankAccountNumber: $transaction->phone_number ?: $transaction->user?->phone,
            occurredAt: $transaction->processed_at?->toDateTimeString() ?: $transaction->updated_at?->toDateTimeString(),
        );

        $filenameType = strtolower(str_replace(' ', '-', str_replace('_', ' ', (string) $transaction->type)));
        $filename = "receipt-{$filenameType}-{$transaction->id}.pdf";

        return response($pdfBinary, 200, [
            'Content-Type' => 'application/pdf',
            'Content-Disposition' => "attachment; filename=\"{$filename}\"",
        ]);
    }
}
