<?php

use App\Models\Order;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Layout;
use Livewire\Component;

return new class extends Component
{
    #[Layout('layouts.store')]

    public function downloadInvoice($orderId)
    {
        $order = Order::with(['user', 'items'])->where('order_number', $orderId)->firstOrFail();

        // Security: Ensure users can only download their own invoices
        if ($order->user_id !== Auth::id()) {
            abort(403);
        }

        $pdf = Pdf::loadView('pdf.invoice', ['order' => $order]);

        return response()->streamDownload(function () use ($pdf) {
            echo $pdf->stream();
        }, "invoice-{$order->order_number}.pdf");
    }

    public function with()
    {
        // return [
        //     'orders' =>Auth::user()->orders()->latest()->get()
        // ];
        return [
            'orders' => Order::where('user_id', auth()->id())
                ->with(['items.product', 'user', 'address'])
                ->latest()
                ->get()
        ];

    }

    protected function view($data = [])
    {
        return app('view')->file('C:\laragon\www\ecommerce\storage\framework/views/livewire/views/b683d2c4.blade.php', $data);
    }
};
