<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Request;

class InvoiceController extends Controller
{
    public function download(Order $order)
    {
        // Authorization: Ensure user can download their own invoice or user is admin
        if (!auth()->user()->is_admin && auth()->id() !== $order->user_id) {
            abort(403);
        }

        $order->load('items.product', 'user');

        // Load view with UTF-8 support
        $pdf = Pdf::loadView('invoices.pdf', compact('order'))
                  ->setPaper('a4', 'portrait')
                  ->setOptions(['defaultFont' => 'DejaVu Sans']);
                  
        return $pdf->download('invoice-MSN-' . str_pad($order->id, 5, '0', STR_PAD_LEFT) . '.pdf');
    }
}
