<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use App\Models\User;

class PartyType extends Model
{
    /** If your table is rm_party_types */
    protected $table = 'rm_party_types';

    /** If your PK isn’t “id”, uncomment & set it
     *  protected $primaryKey = 'id';
     *  public $incrementing = true;
     *  protected $keyType = 'int';
     */

    protected $fillable = ['name', 'status', 'created_by', 'updated_by'];

    protected $casts = [
        'status' => 'integer',
    ];

    /** These are convenient for blade: $partyType->created_by_name, updated_by_name */
    protected $appends = ['created_by_name', 'updated_by_name'];

    /* ---------------- Relations ---------------- */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

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

    /* ---------------- Accessors ---------------- */
    public function getCreatedByNameAttribute(): ?string
    {
        return optional($this->creator)->name;
    }

    public function getUpdatedByNameAttribute(): ?string
    {
        return optional($this->updater)->name;
    }

    /* ---------------- Scopes (optional) ---------------- */
    public function scopeActive($query)
    {
        return $query->where('status', 1);
    }

    /* ---------------- Auto-fill created_by / updated_by (optional) ---------------- */
    protected static function booted(): void
    {
        static::creating(function ($model) {
            $model->created_by ??= Auth::id();
            $model->updated_by ??= Auth::id();
        });

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

