<?php

namespace App\Http\Controllers;

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

class OrderController extends Controller
{
    /**
     * Generate and download/stream the PDF invoice for a given order.
     */
    public function downloadInvoice(Order $order)
    {
        // Load items relation to prevent N+1 query issue in PDF rendering
        $order->load('items.product');

        // Load the Dompdf configuration with premium styling
        $pdf = Pdf::loadView('pdf.invoice', compact('order'))
            ->setPaper('a4', 'portrait')
            ->setWarnings(false);

        return $pdf->stream('invoice-' . $order->order_number . '.pdf');
    }

    /**
     * Generate and download/stream a combined PDF of multiple invoices.
     */
    public function downloadBulkInvoices(\Illuminate\Http\Request $request)
    {
        $ids = explode(',', $request->query('ids', ''));
        $orders = Order::whereIn('id', $ids)->with('items.product')->get();

        if ($orders->isEmpty()) {
            abort(404, 'No orders selected.');
        }

        $pdf = Pdf::loadView('pdf.bulk-invoice', compact('orders'))
            ->setPaper('a4', 'portrait')
            ->setWarnings(false);

        return $pdf->stream('bulk-invoices-' . date('YmdHis') . '.pdf');
    }
}
