<?php

namespace App\Models\Sales;

use App\Models\Tenants\Tenant;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * 계약별 선택 상품 모델
 *
 * @property int $id
 * @property int $tenant_id
 * @property int $management_id
 * @property int $category_id
 * @property int $product_id
 * @property float|null $registration_fee
 * @property float|null $subscription_fee
 * @property float $discount_rate
 * @property string|null $notes
 * @property int|null $created_by
 */
class SalesContractProduct extends Model
{
    protected $table = 'sales_contract_products';

    protected $fillable = [
        'tenant_id',
        'management_id',
        'category_id',
        'product_id',
        'registration_fee',
        'subscription_fee',
        'discount_rate',
        'notes',
        'created_by',
    ];

    protected $casts = [
        'tenant_id' => 'integer',
        'management_id' => 'integer',
        'category_id' => 'integer',
        'product_id' => 'integer',
        'registration_fee' => 'decimal:2',
        'subscription_fee' => 'decimal:2',
        'discount_rate' => 'decimal:2',
        'created_by' => 'integer',
    ];

    /**
     * 테넌트 관계
     */
    public function tenant(): BelongsTo
    {
        return $this->belongsTo(Tenant::class);
    }

    /**
     * 영업관리 관계
     */
    public function management(): BelongsTo
    {
        return $this->belongsTo(SalesTenantManagement::class, 'management_id');
    }

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

    /**
     * 상품 관계
     */
    public function product(): BelongsTo
    {
        return $this->belongsTo(SalesProduct::class, 'product_id');
    }

    /**
     * 등록자 관계
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * 테넌트별 총 개발비
     */
    public static function getTotalRegistrationFee(int $tenantId): float
    {
        return self::where('tenant_id', $tenantId)->sum('registration_fee') ?? 0;
    }

    /**
     * 테넌트별 총 구독료
     */
    public static function getTotalSubscriptionFee(int $tenantId): float
    {
        return self::where('tenant_id', $tenantId)->sum('subscription_fee') ?? 0;
    }
}
