<?php

namespace App\Models\Sales;

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

class SalesProspectProduct extends Model
{
    use SoftDeletes;

    protected $table = 'sales_prospect_products';

    protected $fillable = [
        'prospect_id',
        'product_name',
        'contract_amount',
        'subscription_fee',
        'commission_rate',
        'commission_amount',
        'contract_date',
        'join_approved',
        'payment_approved',
        'payout_rate',
        'payout_amount',
        'sub_models',
    ];

    protected $casts = [
        'contract_amount' => 'decimal:2',
        'subscription_fee' => 'decimal:2',
        'commission_rate' => 'decimal:2',
        'commission_amount' => 'decimal:2',
        'payout_rate' => 'decimal:2',
        'payout_amount' => 'decimal:2',
        'contract_date' => 'date',
        'join_approved' => 'boolean',
        'payment_approved' => 'boolean',
        'sub_models' => 'array',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];

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

    /**
     * 수수료 자동 계산
     */
    public function calculateCommission(): void
    {
        $this->commission_amount = $this->contract_amount * ($this->commission_rate / 100);
    }

    /**
     * 지급금액 계산
     */
    public function calculatePayout(): void
    {
        $this->payout_amount = $this->contract_amount * ($this->payout_rate / 100);
    }

    /**
     * 승인 상태 라벨
     */
    public function getApprovalStatusAttribute(): string
    {
        if ($this->payment_approved) {
            return '결제승인';
        }
        if ($this->join_approved) {
            return '가입승인';
        }

        return '대기중';
    }

    /**
     * 승인 상태별 색상
     */
    public function getApprovalColorAttribute(): string
    {
        if ($this->payment_approved) {
            return 'bg-green-100 text-green-800';
        }
        if ($this->join_approved) {
            return 'bg-blue-100 text-blue-800';
        }

        return 'bg-gray-100 text-gray-800';
    }
}
