<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Auth;

class Transaction extends Model
{
    use HasFactory;

    protected $guarded = [];

    protected $casts = [
        'transaction_id' => 'integer', // Cast transaction_id to integer
    ];

    public function invoice(){
        return $this->belongsTo('App\Models\Invoice','transaction_id')->where('transaction_type',2);
    }

    public function account(){
        return $this->belongsTo('App\Models\Account','account_id');
    }

    public function credit_note(){
        return $this->belongsTo('App\Models\CreditNote','transaction_id')->where('transaction_type',4);
    }
    
    public function bill(){
        return $this->belongsTo('App\Models\Bill','transaction_id')->where('transaction_type',3);
    }

    public function debit_note(){
        return $this->belongsTo('App\Models\DebitNote','transaction_id')->where('transaction_type',5);
    }

    public function journal(){
        return $this->belongsTo('App\Models\Journal','transaction_id')->where('transaction_type',7);
    }

    public function expense(){
        return $this->belongsTo('App\Models\Expense','transaction_id')->where('transaction_type',16);
    }

    public function customer(){
        return $this->belongsTo('App\Models\User','customer_id');
    }

    public function vendor(){
        return $this->belongsTo('App\Models\User','vendor_id');
    }

    protected static function boot()
    {
        parent::boot();

        Transaction::creating(function($model) {
            $user = Auth::user();
            if($user!=null){
                $model->enteredbyid = $user->id;
                $model->organisation_id = $user->active_organisation;
            }
        });
    }
}
