<?php

namespace App\Models\Tenants;

use App\Traits\BelongsToTenant;
use App\Traits\ModelTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * 법인카드 모델
 *
 * @property int $id
 * @property int $tenant_id
 * @property string $card_name
 * @property string $card_company
 * @property string $card_number
 * @property string $card_type
 * @property int $payment_day
 * @property float $credit_limit
 * @property float $current_usage
 * @property string $card_holder_name
 * @property string $actual_user
 * @property string|null $expiry_date
 * @property string|null $cvc
 * @property string $status
 * @property string|null $memo
 */
class CorporateCard extends Model
{
    use BelongsToTenant, ModelTrait, SoftDeletes;

    protected $table = 'corporate_cards';

    protected $fillable = [
        'tenant_id',
        'card_name',
        'card_company',
        'card_number',
        'card_type',
        'payment_day',
        'credit_limit',
        'current_usage',
        'card_holder_name',
        'actual_user',
        'expiry_date',
        'cvc',
        'status',
        'memo',
    ];

    protected $hidden = [
        'cvc',
        'deleted_at',
    ];

    protected $casts = [
        'payment_day' => 'integer',
        'credit_limit' => 'decimal:2',
        'current_usage' => 'decimal:2',
    ];

    protected $attributes = [
        'status' => 'active',
        'payment_day' => 15,
        'credit_limit' => 0,
        'current_usage' => 0,
    ];

    // =========================================================================
    // Scopes
    // =========================================================================

    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    public function scopeByType($query, string $cardType)
    {
        return $query->where('card_type', $cardType);
    }

    // =========================================================================
    // 헬퍼 메서드
    // =========================================================================

    public function isActive(): bool
    {
        return $this->status === 'active';
    }

    public function toggleStatus(): void
    {
        $this->status = $this->status === 'active' ? 'inactive' : 'active';
    }

    /**
     * 마스킹된 카드번호
     */
    public function getMaskedCardNumber(): string
    {
        $number = preg_replace('/[^0-9]/', '', $this->card_number);
        if (strlen($number) <= 4) {
            return $this->card_number;
        }

        return '****-****-****-'.substr($number, -4);
    }
}
