<?php

namespace App\Modules\Invoices;

use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\ValidationModel;
use App\Modules\Invoices\Invoice;
use App\Models\User;

class InvoiceTransaction extends ValidationModel
{
    use \Venturecraft\Revisionable\RevisionableTrait;
    use SoftDeletes;

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

    /**
     *	The attributes that won't be assigned during
     *	a mass assignment.
     */
    protected $fillable = ['invoice_id', 'xero_id', 'amount', 'type', 'method_of_payment', 'payment_date', 'notes'];

    /**
     * Array of validation rules.
     *
     * @var  array
     */
    protected static $rules = [
        'method_of_payment' => 'required',
    ];

    /**
     * The "booting" method of the model.
     *
     * @return void
     */
    public static function boot()
    {
        parent::boot();

        // When a transaction is created we want to
        // update the created_by field
        static::creating(function ($model) {
            $model->created_by = Auth::user()->id;
            $model->updated_by = Auth::user()->id;
        });

        // When a transaction gets updated we want to know who
        // updated it
        static::updating(function ($model) {
            $model->updated_by = Auth::user()->id;
        });
    }

    /**
     * Links to an invoice, by using the foreign key.
     *
     * @return void
     */
    public function invoice()
    {
        return $this->belongsTo(Invoice::class);
    }

    /**
     *	Defines a relationship on the users table.
     *	Retrieves the person who created the transaction.
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }
}
