<?php

namespace App\Modules\Procurement\Observers;

use App\Modules\Procurement\Models\PurchaseOrder;
use App\Modules\Procurement\Notifications\NewPurchaseOrder;
use App\Modules\Core\Models\User;
use Illuminate\Support\Facades\Notification;

class PurchaseOrderObserver
{
    /**
     * Handle the PurchaseOrder "created" event.
     */
    public function created(PurchaseOrder $purchaseOrder): void
    {
        // 找出有檢視採購單權限的使用者
        $users = User::permission('purchase_orders.view')->get();
        
        // 排除建立者自己（避免自己收到自己的通知）
        // $users = $users->reject(function ($user) use ($purchaseOrder) {
        //     return $user->id === $purchaseOrder->user_id;
        // });

        $creatorName = $purchaseOrder->user ? $purchaseOrder->user->name : '系統';

        if ($users->isNotEmpty()) {
            Notification::send($users, new NewPurchaseOrder($purchaseOrder, $creatorName));
        }
    }
}
