<?php

namespace App\Models\Sales;

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

/**
 * 영업 상품 모델
 *
 * @property int $id
 * @property int $category_id
 * @property string $code
 * @property string $name
 * @property string|null $description
 * @property float $development_fee
 * @property float $registration_fee
 * @property float $subscription_fee
 * @property float $partner_commission_rate
 * @property float $manager_commission_rate
 * @property bool $allow_flexible_pricing
 * @property bool $is_required
 * @property int $display_order
 * @property bool $is_active
 */
class SalesProduct extends Model
{
    use SoftDeletes;

    protected $table = 'sales_products';

    protected $fillable = [
        'category_id',
        'code',
        'name',
        'description',
        'development_fee',
        'registration_fee',
        'subscription_fee',
        'partner_commission_rate',
        'manager_commission_rate',
        'allow_flexible_pricing',
        'is_required',
        'display_order',
        'is_active',
    ];

    protected $casts = [
        'category_id' => 'integer',
        'development_fee' => 'decimal:2',
        'registration_fee' => 'decimal:2',
        'subscription_fee' => 'decimal:2',
        'partner_commission_rate' => 'decimal:2',
        'manager_commission_rate' => 'decimal:2',
        'allow_flexible_pricing' => 'boolean',
        'is_required' => 'boolean',
        'display_order' => 'integer',
        'is_active' => 'boolean',
    ];

    /**
     * 카테고리 관계
     */
    public function category(): BelongsTo
    {
        return $this->belongsTo(SalesProductCategory::class, 'category_id');
    }

    /**
     * 활성 상품 스코프
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * 정렬 스코프
     */
    public function scopeOrdered($query)
    {
        return $query->orderBy('display_order')->orderBy('name');
    }

    /**
     * 총 수당율
     */
    public function getTotalCommissionRateAttribute(): float
    {
        return $this->partner_commission_rate + $this->manager_commission_rate;
    }

    /**
     * 수당 계산 (개발비 기준)
     */
    public function getCommissionAttribute(): float
    {
        return $this->development_fee * ($this->total_commission_rate / 100);
    }

    /**
     * 포맷된 개발비
     */
    public function getFormattedDevelopmentFeeAttribute(): string
    {
        return '₩'.number_format($this->development_fee);
    }

    /**
     * 포맷된 개발비
     */
    public function getFormattedRegistrationFeeAttribute(): string
    {
        return '₩'.number_format($this->registration_fee);
    }

    /**
     * 포맷된 구독료
     */
    public function getFormattedSubscriptionFeeAttribute(): string
    {
        return '₩'.number_format($this->subscription_fee);
    }
}
