<?php

namespace App\Models\StockManagement;

use App\Models\Scopes\ImportationGlobalScope;
use App\Models\StockManagement\Traits\HasProducts;
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\BelongsTo;

class Importation extends Model{
    use HasFactory,HasStocks,HasProducts,AuthorableTrait;

    protected $table = "stock_mgt__importations";
    protected $guarded = ['id'];
    public $timestamps = false;

    protected static function booted(){
        parent::addGlobalScope(new ImportationGlobalScope);
    }

    public function type(){
        return $this->belongsTo(ImportationType::class,ImportationType::FK_ID);
    }

    /**
     * @return BelongsTo
     */
    public function createdBy(){
        return $this->belongsTo(Admin::class,"created_by");
    }
    public function warehouse(){
        return $this->belongsTo(Warehouse::class,"warehouse_id");
    }


    public function getGapAttribute(){
        $gap = $this->real_qty; // par défaut gap = stock reel (qty importé)
        //si l'import est lié a un stock théorique
        if (!blank($this->stock)){ // App\Models\StockEntrepot
            $gap -=  $this->theoretical_qty; // déduit le stock theorique
        }
        return $gap;
    }

    public function getRealQtyAttribute(){
        return $this->qty ?? 0;
    }
    public function getTheoreticalQtyAttribute(){
        return $this->stock->qty ?? 0;
    }

    public function getOperationStockAttribute(){
        $id = ($this->gap > 0) ? AdjustmentOperation::OUTPUT:AdjustmentOperation::INPUT;
        return AdjustmentOperation::find($id);
    }

    public function getErrorsValidationAttribute(){
        $errors = json_decode($this->messages,true);
        return $errors['errors'] ?? null;
    }

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