<?php

namespace App\Models\StockManagement;

use App\Models\Scopes\AdjustmentGlobalScope;
use App\Models\StockManagement\Observers\AdjustmentObserver;
use App\Models\StockManagement\Traits\HasStocks;
use App\Models\UserManagement\Admin;
use App\Models\UserManagement\User;
use Axn\EloquentAuthorable\AuthorableTrait;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class Adjustment extends Model{
    use HasFactory,SoftDeletes,HasStocks,AuthorableTrait;

    protected $table = "stock_mgt__adjustments";
    protected $guarded = ['id','created_at'];
    const FK_ID = "adjustment_id";

    const MORPH_ID_COLUMN = "adjuster_id";
    const MORPH_TYPE_COLUMN = "adjuster_type";
    const MORPH_FUNCTION_NAME = "adjuster";


    protected static function booted(){
        parent::observe(new AdjustmentObserver);

        parent::addGlobalScope(new AdjustmentGlobalScope);
    }


    /** Le Payeur
     * @return MorphTo
     */
    public function adjuster(){
        return $this->morphTo(__FUNCTION__,
            self::MORPH_TYPE_COLUMN,self::MORPH_ID_COLUMN);
    }

    //----RELATIONS----//////////////////////////////
    public function reason(){
        return $this->belongsTo(AdjustmentReason::class,"reason_code");
    }

    public function operation(){
        return $this->belongsTo(AdjustmentOperation::class,"operation_code");
    }

    public function createdBy(){
        return $this->belongsTo(Admin::class,"created_by");
    }

    //----END RELATIONS----//////////////////////////////

    //----GETTERS----//////////////////////////////
    public function getModifiedQtyAttribute(){
        $operation = $this->operation;

        return ($operation->id == AdjustmentOperation::INPUT)
            ? $this->qty_before - $this->qty_adjusted
            :$this->qty_before + $this->qty_adjusted;
    }

    public function getGapAttribute(){
        return $this->real_qty - $this->theoretical_qty;
    }
    public function getRealQtyAttribute(){
        return $this->qty_adjusted;
    }
    public function getTheoricalQtyAttribute(){
        return $this->qty_before;
    }
    public function getOperationStockAttribute(){
        $id = ($this->gap > 0)
            ? AdjustmentOperation::OUTPUT
            : AdjustmentOperation::INPUT;
        return AdjustmentOperation::find($id);
    }

    public function getLotIdAttribute(){
        return $this->stock->lot_id;
    }

    //----END GETTERS----//////////////////////////////


    //

    /**
     * Exécute le retour en stock de cet ajustement
     */
    public function replaceStock(){
        if (!$this->replaced) {
            $this->update(['replaced' => true]);
        }

        return false;
    }
}
