<?php

namespace App\Models;

use App\Traits\UuidTrait;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Area extends Model
{
    use HasFactory,SoftDeletes,UuidTrait;

    protected $table = 'areas';
    public $timestamps = true; 
    protected $fillable = [
        'uuid',
        'address',
        'is_active',
        'created_by',
        'updated_by',
        'deleted_at',
    ];

    protected $appends = [
        'customer_count',
    ];

    protected static function boot()
    {
        parent::boot();
        static::creating(function(Area $model) {
            $model->created_by = auth()->user() ? auth()->user()->id : config('constant.roles.super_admin');
        });

        /*
        static::deleting(function(Area $model) {
            $model->deleted_by = auth()->user()->id;
            $model->save();
        });
        */

        static::updating(function(Area $model) {
            $model->updated_by = auth()->user()->id;
        });
    }   

    public function createdBy(){
        return $this->belongsTo(User::class, 'created_by');
    }    


    public function customers(){
        return $this->hasMany(Customer::class, 'area_id');
    }

    public function getCustomerCountAttribute()
    {
        return $this->customers()->count();
    }
}
