<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use App\Models\Order;

class NewOrderNotification extends Notification
{
    use Queueable;

    public Order $order;

    public function __construct(Order $order)
    {
        // Pastikan relasi user & items.product sudah ter-load
        $this->order = $order->loadMissing(['user', 'items.product']);
    }

    public function via($notifiable): array
    {
        return ['database'];
    }

    public function toDatabase($notifiable): array
    {
        // Daftar produk: "Nama Produk x Qty"
        $productLines = $this->order->items->map(function ($item) {
            $name = optional($item->product)->product_name ?? 'Produk';
            return $name . ' x' . $item->quantity;
        })->implode(', ');

        return [
            'order_id'      => $this->order->order_id,
            'user_id'       => $this->order->user_id,
            'buyer_name'    => optional($this->order->user)->name ?? 'Pelanggan',
            'buyer_email'   => optional($this->order->user)->email ?? '',
            'products'      => $productLines,          // "Sofa Minimalis x2, Meja Kayu x1"
            'item_count'    => $this->order->items->count(),
            'status'        => $this->order->status,
            'total_price'   => $this->order->total_price,
            'message'       => 'Pesanan baru dari ' . (optional($this->order->user)->name ?? 'Pelanggan'),
            'icon'          => 'fas fa-shopping-bag',
            'color'         => 'text-green-600',
            'url'           => route('admin.order.show', $this->order->order_id),
            'time'          => now()->toDateTimeString(),
        ];
    }
}