<?php

namespace App\Models\Sales;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * 영업 파트너(영업 담당자) 모델
 *
 * @property int $id
 * @property int $user_id
 * @property string $partner_code
 * @property string $partner_type
 * @property float $commission_rate
 * @property float $manager_commission_rate
 * @property string|null $bank_name
 * @property string|null $account_number
 * @property string|null $account_holder
 * @property string $status
 * @property \Carbon\Carbon|null $approved_at
 * @property int|null $approved_by
 * @property int $total_contracts
 * @property float $total_commission
 * @property string|null $notes
 */
class SalesPartner extends Model
{
    use SoftDeletes;

    protected $table = 'sales_partners';

    protected $fillable = [
        'user_id',
        'partner_code',
        'partner_type',
        'commission_rate',
        'manager_commission_rate',
        'bank_name',
        'account_number',
        'account_holder',
        'status',
        'approved_at',
        'approved_by',
        'total_contracts',
        'total_commission',
        'notes',
        'company_name',
        'biz_no',
        'address',
        'referrer_partner_id',
    ];

    protected $casts = [
        'commission_rate' => 'decimal:2',
        'manager_commission_rate' => 'decimal:2',
        'total_contracts' => 'integer',
        'total_commission' => 'decimal:2',
        'approved_at' => 'datetime',
    ];

    /**
     * 연결된 사용자
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 승인자
     */
    public function approver(): BelongsTo
    {
        return $this->belongsTo(User::class, 'approved_by');
    }

    /**
     * 담당 테넌트 관리 목록
     */
    public function tenantManagements(): HasMany
    {
        return $this->hasMany(SalesTenantManagement::class, 'sales_partner_id');
    }

    /**
     * 수수료 정산 내역
     */
    public function commissions(): HasMany
    {
        return $this->hasMany(SalesCommission::class, 'partner_id');
    }

    /**
     * 이 단체를 유치한 영업파트너
     */
    public function referrer(): BelongsTo
    {
        return $this->belongsTo(SalesPartner::class, 'referrer_partner_id');
    }

    /**
     * 이 영업파트너가 유치한 단체 목록
     */
    public function referredGroups(): HasMany
    {
        return $this->hasMany(SalesPartner::class, 'referrer_partner_id');
    }

    /**
     * 단체 여부 확인 (partner_type 기반)
     */
    public function isGroup(): bool
    {
        return $this->partner_type === 'corporate';
    }

    /**
     * 파트너 코드 자동 생성
     */
    public static function generatePartnerCode(): string
    {
        $prefix = 'SP';
        $year = now()->format('y');
        $lastPartner = self::whereYear('created_at', now()->year)
            ->orderBy('id', 'desc')
            ->first();

        $sequence = $lastPartner ? (int) substr($lastPartner->partner_code, -4) + 1 : 1;

        return $prefix.$year.str_pad($sequence, 4, '0', STR_PAD_LEFT);
    }

    /**
     * 활성 파트너 스코프
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    /**
     * 승인 대기 스코프
     */
    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }
}
