<?php

namespace App\Observers;

use App\Models\OrderManagement\OrderProduct;
use App\Models\StockManagement\AdjustmentOperation;
use App\Models\StockManagement\AdjustmentReason;

class OrderProductObserver{

    /**
     * @param OrderProduct $orderProduct
     */
    public function created(OrderProduct $orderProduct){
        $product = $orderProduct->product;
        $stocks = $product->stocks;
        $warehouse = $orderProduct->order->warehouse ?? null;

//        dd(!$orderProduct->rejected,filled($stocks),filled($warehouse) );
        // si pas "rejétée"
        if (!$orderProduct->rejected and (filled($stocks) and filled($warehouse))){
            /*debite le stock de ce produit dans le point de vente*/
            $product->reduceStock($warehouse,$orderProduct->quantity,$orderProduct);
        }
    }

    /**
     * @param OrderProduct $orderProduct
     */
    public function updated(OrderProduct $orderProduct){
        $changes = $orderProduct->getChanges();


        //si le statut de la commande a été modifié
        if (isset($changes['rejected'])){

            // si "rejétée"
            if ($orderProduct->rejected){

               $adjustements =  $orderProduct->stocksAdjustments()->where('replaced',false)->get();

               $adjustements->map->replaceStock();
            }
        }
    }
}
