<?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 SalesProspect extends Model
{
    use SoftDeletes;

    protected $table = 'sales_prospects';

    protected $fillable = [
        'manager_id',
        'sales_manager_id',
        'company_name',
        'representative',
        'business_no',
        'contact_phone',
        'email',
        'address',
        'business_card_image',
        'id_card_image',
        'bankbook_image',
        'status',
    ];

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

    /**
     * 등록한 영업 담당자
     */
    public function manager(): BelongsTo
    {
        return $this->belongsTo(SalesManager::class, 'manager_id');
    }

    /**
     * 담당 매니저
     */
    public function salesManager(): BelongsTo
    {
        return $this->belongsTo(SalesManager::class, 'sales_manager_id');
    }

    /**
     * 계약 상품 목록
     */
    public function products(): HasMany
    {
        return $this->hasMany(SalesProspectProduct::class, 'prospect_id');
    }

    /**
     * 시나리오 체크리스트
     */
    public function scenarios(): HasMany
    {
        return $this->hasMany(SalesProspectScenario::class, 'prospect_id');
    }

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

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

    /**
     * 상태 라벨
     */
    public function getStatusLabelAttribute(): string
    {
        return match ($this->status) {
            'lead' => '리드',
            'prospect' => '가망',
            'negotiation' => '협상중',
            'contracted' => '계약완료',
            'lost' => '실패',
            default => $this->status,
        };
    }

    /**
     * 상태별 색상 클래스
     */
    public function getStatusColorAttribute(): string
    {
        return match ($this->status) {
            'lead' => 'bg-gray-100 text-gray-800',
            'prospect' => 'bg-blue-100 text-blue-800',
            'negotiation' => 'bg-yellow-100 text-yellow-800',
            'contracted' => 'bg-green-100 text-green-800',
            'lost' => 'bg-red-100 text-red-800',
            default => 'bg-gray-100 text-gray-800',
        };
    }

    /**
     * 사업자번호 포맷팅 (XXX-XX-XXXXX)
     */
    public function getFormattedBusinessNoAttribute(): string
    {
        $bizNo = preg_replace('/[^0-9]/', '', $this->business_no);
        if (strlen($bizNo) === 10) {
            return substr($bizNo, 0, 3).'-'.substr($bizNo, 3, 2).'-'.substr($bizNo, 5);
        }

        return $this->business_no ?? '';
    }

    /**
     * 총 계약금액
     */
    public function getTotalContractAmountAttribute(): float
    {
        return $this->products()->sum('contract_amount');
    }

    /**
     * 총 수수료
     */
    public function getTotalCommissionAttribute(): float
    {
        return $this->products()->sum('commission_amount');
    }

    /**
     * 명함 이미지 존재 여부
     */
    public function hasBusinessCard(): bool
    {
        return ! empty($this->business_card_image);
    }

    /**
     * 명함 이미지 URL
     */
    public function getBusinessCardUrlAttribute(): ?string
    {
        if (! $this->hasBusinessCard()) {
            return null;
        }

        return asset('storage/'.$this->business_card_image);
    }

    /**
     * 신분증 이미지 존재 여부
     */
    public function hasIdCard(): bool
    {
        return ! empty($this->id_card_image);
    }

    /**
     * 신분증 이미지 URL
     */
    public function getIdCardUrlAttribute(): ?string
    {
        if (! $this->hasIdCard()) {
            return null;
        }

        return asset('storage/'.$this->id_card_image);
    }

    /**
     * 통장사본 이미지 존재 여부
     */
    public function hasBankbook(): bool
    {
        return ! empty($this->bankbook_image);
    }

    /**
     * 통장사본 이미지 URL
     */
    public function getBankbookUrlAttribute(): ?string
    {
        if (! $this->hasBankbook()) {
            return null;
        }

        return asset('storage/'.$this->bankbook_image);
    }
}
