<?php

namespace App\Modules\Stock;

use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\ValidationModel;
use App\Modules\Stock\Stock;
use App\Traits\SetCreatorAndUpdatorTrait;

class StockTransaction extends ValidationModel
{
    use SoftDeletes;
    use SetCreatorAndUpdatorTrait;
    use \Venturecraft\Revisionable\RevisionableTrait;

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'stock_transactions';

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['deleted_at'];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    // protected $appends = array();

    /**
     * Array of validation rules.
     *
     * @var  array
     */
    protected static $rules = [
        'stock_id'                   => 'required',
        'related_id'                 => 'required_if:related_type,task|
										required_if:related_type,project |
										required_if:related_type,sale |
										required_if:related_type,invoice |
										required_if:related_type,purchase_order
										required_if:related_type,user
										required_if:related_type,stock_report',
        'quantity'                    => 'required',
        'related_type'                => 'required',
    ];

    /**
     *	The attributes that won't be assigned during
     *	a mass assignment.
     */
    protected $fillable = ['stock_id', 'related_type','related_id','quantity', 'reason', 'created_by', 'updated_by'];

    // ==================================================================
    //
    // Discontinued setter and getter
    //
    // ------------------------------------------------------------------


    public static function createOrUpdate($related_type, $related_id, $stock_id, $quantity)
    {
        $transaction = self::where('related_type', $related_type)->where('stock_id', $stock_id)->where('related_id', $related_id)->first();

        if ($transaction) {
            $transaction->quantity = $quantity;
            $transaction->save();
        } else {
            $transaction = self::create([
                'related_type'                => $related_type,
                'stock_id'                    => $stock_id,
                'related_id'                  => $related_id,
                'quantity'                    => $quantity,
            ]);
        }

        if (! $transaction->id) {
            throw new Exception($transaction->errors->all(), 1);
        }
    }

    /**
     * Returns the stock item for the part.
     *
     * @return App\Modules\Stock\StockItem
     */
    public function stock()
    {
        return $this->belongsTo(Stock::class, 'stock_id')->withTrashed();
    }
}
