<?php


namespace App\Models\StockManagement\Observers;


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

class AdjustmentObserver {

    /** Se produit quand la commande est en cours de creation
     * @param Adjustment $adjustment
     * @return Adjustment
     */
    public function created(Adjustment $adjustment){
        $attributes = $adjustment->getAttributes();

        $stock = $adjustment->stock ?? null;

        if ($stock){
             $originals_stock_data = $stock->getOriginal();
             $changes_stock_data = $stock->getChanges();
             $updates = [];
            if (!isset($attributes['qty_before']) and filled($originals_stock_data)){
                $updates['qty_before'] = $originals_stock_data['qty'];
            }
            if (!isset($attributes['qty_after']) and filled($changes_stock_data)){
                $updates['qty_after'] = $changes_stock_data['qty'];
            }
            if (filled($updates)) {
                $adjustment->update($updates);
            }
        }

        return $adjustment;
    }


    /** Se produit quand la commande est en cours de creation
     * @param Adjustment $adjustment
     * @return Adjustment
     */
    public function updated(Adjustment $adjustment){
        $attributes = $adjustment->getAttributes();
        $changes = $adjustment->getChanges();
        $stock = $adjustment->stock ?? null;

        if ($stock and isset($changes['replaced'])){
           if ($changes['replaced']){
               $comment = AdjustmentReason::ROLLBACK_STOCK;
               $adjuster= $adjustment->adjuster;

               if ($adjuster instanceof OrderProduct){
                   $comment = __("Stock returned on order id ':ref_id'" , ['ref_id' => $adjuster->order->ref_id]);
               }

               $stock->adjust([
                   "operation_code"  => AdjustmentOperation::INPUT,
                   "qty_adjusted" => $attributes["qty_adjusted"],
                   "adjuster" => $adjuster,
                   'comment' => $comment,
                   'parent_id' => $adjustment->getKey(),
                   "reason_code"  => AdjustmentReason::ROLLBACK_STOCK,
               ]);
           }
        }

        return $adjustment;
    }

}
