<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Services\InvoiceTokenService;
use Illuminate\Contracts\Encryption\DecryptException;
use PDF;

class InvoiceController extends Controller
{
    public function __construct(
        protected InvoiceTokenService $invoiceTokenService
    ) {
    }

    public function show(string $encryptedOrderId)
    {
        try {
            $orderId = $this->invoiceTokenService->decryptOrderId($encryptedOrderId);
        } catch (DecryptException) {
            abort(404);
        }

        $order = Order::with(['items.product', 'user', 'staff'])->findOrFail($orderId);

        $pdf = PDF::loadView('admin.orders.thermal_invoice', [
            'order' => $order,
        ]);

        return $pdf->stream('invoice-' . $order->id . '.pdf');
    }
}
