<?php

namespace App\Models;

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

class Account extends Model
{
    use HasFactory;
    protected $guarded = [];

    public function activity(){
        return $this->hasMany('App\Models\Activity','module_id')->where('module',"Accounts");
    }

    public function sub_accounts(){
        return $this->hasMany('App\Models\Account','parent_id','id') ->where('is_disabled', 0)->where('sub_account',1);
    }

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

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

         // Always update acc_case_name when account_name changes
        static::saving(function ($account) {
            if ($account->isDirty('account_name')) {
                $account->acc_case_name = Str::snake($account->account_name);
            }
        });
    }
}
