<?php

namespace App\Models\Tenants;

use App\Models\Orders\Client;
use App\Traits\Auditable;
use App\Traits\BelongsToTenant;
use App\Traits\ModelTrait;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * 비용 계정 모델
 *
 * CEO 대시보드용 비용 데이터 (복리후생비, 접대비 등)
 */
class ExpenseAccount extends Model
{
    use Auditable, BelongsToTenant, HasFactory, ModelTrait, SoftDeletes;

    protected $table = 'expense_accounts';

    protected $fillable = [
        'tenant_id',
        'account_type',
        'sub_type',
        'expense_date',
        'amount',
        'description',
        'receipt_no',
        'vendor_id',
        'vendor_name',
        'payment_method',
        'card_no',
        'loan_id',
        'created_by',
        'updated_by',
        'deleted_by',
    ];

    protected $casts = [
        'expense_date' => 'date',
        'amount' => 'decimal:2',
    ];

    // 계정 유형 상수
    public const TYPE_WELFARE = 'welfare';

    public const TYPE_ENTERTAINMENT = 'entertainment';

    public const TYPE_TRAVEL = 'travel';

    public const TYPE_OFFICE = 'office';

    // 세부 유형 상수 (접대비)
    public const SUB_TYPE_GIFT_CERTIFICATE = 'gift_certificate';

    // 세부 유형 상수 (복리후생)
    public const SUB_TYPE_MEAL = 'meal';

    public const SUB_TYPE_HEALTH = 'health';

    public const SUB_TYPE_EDUCATION = 'education';

    // 결제 수단 상수
    public const PAYMENT_CARD = 'card';

    public const PAYMENT_CASH = 'cash';

    public const PAYMENT_TRANSFER = 'transfer';

    /**
     * 거래처 관계
     */
    public function vendor(): BelongsTo
    {
        return $this->belongsTo(Client::class, 'vendor_id');
    }

    /**
     * 복리후생비 스코프
     */
    public function scopeWelfare($query)
    {
        return $query->where('account_type', self::TYPE_WELFARE);
    }

    /**
     * 접대비 스코프
     */
    public function scopeEntertainment($query)
    {
        return $query->where('account_type', self::TYPE_ENTERTAINMENT);
    }

    /**
     * 기간 필터 스코프
     */
    public function scopeInPeriod($query, string $startDate, string $endDate)
    {
        return $query->whereBetween('expense_date', [$startDate, $endDate]);
    }
}
