<?php

namespace App\Models\Agency;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\Permission\Traits\HasRoles;

class AgencyStaff extends Model
{
    use HasFactory, SoftDeletes, HasRoles;

    protected $table = 'agency_staff';

    protected $fillable = [
        'agency_id',
        'user_id',
        'first_name',
        'last_name',
        'email',
        'phone',
        'position',
        'hired_at',
        'left_at',
        'is_active',
        'is_agency_owner',
        'can_login',
        'resume',
        'experience',
        'created_by',
        'updated_by',
    ];

    protected $casts = [
        'hired_at' => 'date',
        'left_at' => 'date',
        'is_active' => 'boolean',
        'is_agency_owner' => 'boolean',
        'can_login' => 'boolean',
        'resume' => 'array',
        'experience' => 'array',
    ];

    /**
     * Get the agency this staff member belongs to.
     */
    public function agency(): BelongsTo
    {
        return $this->belongsTo(Agency::class);
    }

    /**
     * Get the user account for this staff member (if any).
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get the full name of the staff member.
     */
    public function getFullNameAttribute(): string
    {
        return "{$this->first_name} {$this->last_name}";
    }

    /**
     * Boot the model.
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($staff) {
            if (auth()->check()) {
                $staff->created_by = auth()->id();
            }
        });

        static::updating(function ($staff) {
            if (auth()->check()) {
                $staff->updated_by = auth()->id();
            }
        });
    }
}
