<?php

namespace App\Models\Barobill;

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

/**
 * 바로빌 월별 집계 모델
 */
class BarobillMonthlySummary extends Model
{
    protected $table = 'barobill_monthly_summaries';

    protected $fillable = [
        'member_id',
        'billing_month',
        'bank_account_fee',
        'card_fee',
        'hometax_fee',
        'subscription_total',
        'tax_invoice_count',
        'tax_invoice_amount',
        'usage_total',
        'grand_total',
    ];

    protected $casts = [
        'bank_account_fee' => 'integer',
        'card_fee' => 'integer',
        'hometax_fee' => 'integer',
        'subscription_total' => 'integer',
        'tax_invoice_count' => 'integer',
        'tax_invoice_amount' => 'integer',
        'usage_total' => 'integer',
        'grand_total' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /**
     * 바로빌 회원사 관계
     */
    public function member(): BelongsTo
    {
        return $this->belongsTo(BarobillMember::class, 'member_id');
    }

    /**
     * 특정 월 조회
     */
    public function scopeOfMonth($query, string $billingMonth)
    {
        return $query->where('billing_month', $billingMonth);
    }

    /**
     * 집계 데이터 갱신 또는 생성
     */
    public static function updateOrCreateSummary(int $memberId, string $billingMonth): self
    {
        // 해당 월의 과금 기록 조회
        $records = BarobillBillingRecord::where('member_id', $memberId)
            ->where('billing_month', $billingMonth)
            ->get();

        $data = [
            'bank_account_fee' => 0,
            'card_fee' => 0,
            'hometax_fee' => 0,
            'subscription_total' => 0,
            'tax_invoice_count' => 0,
            'tax_invoice_amount' => 0,
            'usage_total' => 0,
            'grand_total' => 0,
        ];

        foreach ($records as $record) {
            if ($record->billing_type === 'subscription') {
                switch ($record->service_type) {
                    case 'bank_account':
                        $data['bank_account_fee'] = $record->total_amount;
                        break;
                    case 'card':
                        $data['card_fee'] = $record->total_amount;
                        break;
                    case 'hometax':
                        $data['hometax_fee'] = $record->total_amount;
                        break;
                }
                $data['subscription_total'] += $record->total_amount;
            } else {
                // 건별 사용
                if ($record->service_type === 'tax_invoice') {
                    $data['tax_invoice_count'] = $record->quantity;
                    $data['tax_invoice_amount'] = $record->total_amount;
                }
                $data['usage_total'] += $record->total_amount;
            }
        }

        $data['grand_total'] = $data['subscription_total'] + $data['usage_total'];

        return self::updateOrCreate(
            ['member_id' => $memberId, 'billing_month' => $billingMonth],
            $data
        );
    }

    /**
     * 전체 회원사 월별 합계
     */
    public static function getMonthlyTotal(string $billingMonth): array
    {
        $result = self::where('billing_month', $billingMonth)
            ->selectRaw('
                COUNT(*) as member_count,
                SUM(bank_account_fee) as bank_account_fee,
                SUM(card_fee) as card_fee,
                SUM(hometax_fee) as hometax_fee,
                SUM(subscription_total) as subscription_total,
                SUM(tax_invoice_count) as tax_invoice_count,
                SUM(tax_invoice_amount) as tax_invoice_amount,
                SUM(usage_total) as usage_total,
                SUM(grand_total) as grand_total
            ')
            ->first();

        return [
            'member_count' => (int) ($result->member_count ?? 0),
            'bank_account_fee' => (int) ($result->bank_account_fee ?? 0),
            'card_fee' => (int) ($result->card_fee ?? 0),
            'hometax_fee' => (int) ($result->hometax_fee ?? 0),
            'subscription_total' => (int) ($result->subscription_total ?? 0),
            'tax_invoice_count' => (int) ($result->tax_invoice_count ?? 0),
            'tax_invoice_amount' => (int) ($result->tax_invoice_amount ?? 0),
            'usage_total' => (int) ($result->usage_total ?? 0),
            'grand_total' => (int) ($result->grand_total ?? 0),
        ];
    }
}
