<?php

namespace App\Models\Sales;

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

class SalesRecord extends Model
{
    use SoftDeletes;

    protected $table = 'sales_records';

    protected $fillable = [
        'manager_id',
        'prospect_id',
        'record_date',
        'record_type',
        'amount',
        'commission',
        'description',
        'status',
    ];

    protected $casts = [
        'record_date' => 'date',
        'amount' => 'decimal:2',
        'commission' => 'decimal:2',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];

    /**
     * 담당자
     */
    public function manager(): BelongsTo
    {
        return $this->belongsTo(SalesManager::class, 'manager_id');
    }

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

    /**
     * 상태 라벨
     */
    public function getStatusLabelAttribute(): string
    {
        return match ($this->status) {
            'pending' => '대기',
            'approved' => '승인',
            'rejected' => '반려',
            'paid' => '지급완료',
            default => $this->status,
        };
    }

    /**
     * 상태별 색상 클래스
     */
    public function getStatusColorAttribute(): string
    {
        return match ($this->status) {
            'pending' => 'bg-yellow-100 text-yellow-800',
            'approved' => 'bg-blue-100 text-blue-800',
            'rejected' => 'bg-red-100 text-red-800',
            'paid' => 'bg-green-100 text-green-800',
            default => 'bg-gray-100 text-gray-800',
        };
    }

    /**
     * 특정 기간의 실적 합계
     */
    public static function getSummary(int $managerId, ?string $startDate = null, ?string $endDate = null): array
    {
        $query = self::where('manager_id', $managerId);

        if ($startDate) {
            $query->where('record_date', '>=', $startDate);
        }
        if ($endDate) {
            $query->where('record_date', '<=', $endDate);
        }

        return [
            'total_amount' => $query->sum('amount'),
            'total_commission' => $query->sum('commission'),
            'record_count' => $query->count(),
            'approved_amount' => (clone $query)->where('status', 'approved')->sum('amount'),
            'paid_amount' => (clone $query)->where('status', 'paid')->sum('amount'),
        ];
    }

    /**
     * 대기 상태만 조회
     */
    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

    /**
     * 승인 상태만 조회
     */
    public function scopeApproved($query)
    {
        return $query->where('status', 'approved');
    }
}
