<?php

namespace App\Http\Controllers;

use App\Models\SubscriptionInvoice;
use App\Services\Formatter;
use App\Services\SettingsRepository;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Request;

/**
 * Invoice PDFs.
 *
 * A plain controller rather than a Livewire action: a file download is a
 * request/response, and forcing it through a component would mean a redirect
 * dance for no benefit.
 */
class InvoiceController extends Controller
{
    public function pdf(Request $request, SubscriptionInvoice $invoice)
    {
        $invoice->loadMissing(['subscription.plan', 'tenant.product']);

        $settings = app(SettingsRepository::class);

        $html = view('documents.invoice', [
            'invoice' => $invoice,
            'fmt' => app(Formatter::class),
            'support' => [
                'email' => $settings->string('support_email', (string) config('thinkrax.company.email')),
                'phone' => $settings->string('support_phone', (string) config('thinkrax.company.phone')),
            ],
        ])->render();

        $pdf = Pdf::loadHTML($html)->setPaper('a4');

        // `?inline` opens it in the browser, which is what a reviewer wants
        // mid-call; the default downloads, which is what accounts wants.
        return $request->has('inline')
            ? $pdf->stream($invoice->invoice_number.'.pdf')
            : $pdf->download($invoice->invoice_number.'.pdf');
    }
}
