<?php

namespace App\Models\Sales;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class SalesManager extends Model
{
    use SoftDeletes;

    protected $table = 'sales_managers';

    protected $fillable = [
        'member_id',
        'password',
        'name',
        'phone',
        'email',
        'parent_id',
        'role',
        'remarks',
        'is_active',
    ];

    protected $hidden = [
        'password',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];

    /**
     * 상위 관리자
     */
    public function parent(): BelongsTo
    {
        return $this->belongsTo(SalesManager::class, 'parent_id');
    }

    /**
     * 하위 관리자 목록
     */
    public function children(): HasMany
    {
        return $this->hasMany(SalesManager::class, 'parent_id');
    }

    /**
     * 등록한 가망고객
     */
    public function registeredProspects(): HasMany
    {
        return $this->hasMany(SalesProspect::class, 'manager_id');
    }

    /**
     * 담당 가망고객
     */
    public function assignedProspects(): HasMany
    {
        return $this->hasMany(SalesProspect::class, 'sales_manager_id');
    }

    /**
     * 영업 실적
     */
    public function records(): HasMany
    {
        return $this->hasMany(SalesRecord::class, 'manager_id');
    }

    /**
     * 상담 기록
     */
    public function consultations(): HasMany
    {
        return $this->hasMany(SalesProspectConsultation::class, 'manager_id');
    }

    /**
     * 역할 라벨
     */
    public function getRoleLabelAttribute(): string
    {
        return match ($this->role) {
            'operator' => '운영자',
            'sales_admin' => '영업관리',
            'manager' => '매니저',
            default => $this->role,
        };
    }

    /**
     * 역할별 색상 클래스
     */
    public function getRoleColorAttribute(): string
    {
        return match ($this->role) {
            'operator' => 'bg-purple-100 text-purple-800',
            'sales_admin' => 'bg-blue-100 text-blue-800',
            'manager' => 'bg-green-100 text-green-800',
            default => 'bg-gray-100 text-gray-800',
        };
    }

    /**
     * 활성 관리자만 조회
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }
}
