<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Support\InvoiceGenerator;
use Barryvdh\DomPDF\Facade\Pdf;

class InvoiceController extends Controller
{
    /** Guard: only the order owner (when logged in) or a guest who knows the
     *  exact order number may access an invoice. */
    private function authorize(Order $order): void
    {
        if ($order->user_id && auth()->id() !== $order->user_id && ! (auth()->user()?->is_admin)) {
            abort(403);
        }
    }

    /** Stream the invoice inline in the browser (print / save-as-PDF friendly). */
    public function show(string $orderNumber)
    {
        $order = Order::where('order_number', $orderNumber)->with('items')->firstOrFail();
        $this->authorize($order);

        return Pdf::loadView('invoice', ['order' => $order])
            ->setPaper('a4')
            ->stream(InvoiceGenerator::filename($order));
    }

    /** Force-download the invoice PDF. */
    public function download(string $orderNumber)
    {
        $order = Order::where('order_number', $orderNumber)->with('items')->firstOrFail();
        $this->authorize($order);

        return Pdf::loadView('invoice', ['order' => $order])
            ->setPaper('a4')
            ->download(InvoiceGenerator::filename($order));
    }
}
