<?php

namespace App\Models\Sales;

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

class SalesProspectScenario extends Model
{
    protected $table = 'sales_prospect_scenarios';

    protected $fillable = [
        'prospect_id',
        'scenario_type',
        'step_id',
        'checkpoint_index',
        'is_checked',
    ];

    protected $casts = [
        'step_id' => 'integer',
        'checkpoint_index' => 'integer',
        'is_checked' => 'boolean',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /**
     * 가망고객
     */
    public function prospect(): BelongsTo
    {
        return $this->belongsTo(SalesProspect::class, 'prospect_id');
    }

    /**
     * 시나리오 유형 라벨
     */
    public function getScenarioTypeLabelAttribute(): string
    {
        return match ($this->scenario_type) {
            'sales' => '영업 시나리오',
            'manager' => '매니저 시나리오',
            default => $this->scenario_type,
        };
    }

    /**
     * 특정 가망고객의 시나리오 진행률 계산
     */
    public static function getProgressRate(int $prospectId, string $scenarioType): float
    {
        $total = self::where('prospect_id', $prospectId)
            ->where('scenario_type', $scenarioType)
            ->count();

        if ($total === 0) {
            return 0;
        }

        $checked = self::where('prospect_id', $prospectId)
            ->where('scenario_type', $scenarioType)
            ->where('is_checked', true)
            ->count();

        return round(($checked / $total) * 100, 1);
    }
}
