<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class SavedPaymentMethod extends Model
{
    protected $fillable = [
        'client_id',
        'gateway_slug',
        'token',
        'card_brand',
        'last_four',
        'expiry_month',
        'expiry_year',
        'label',
        'is_default',
        'status',
        'last_used_at',
    ];

    protected $casts = [
        'is_default' => 'boolean',
        'last_used_at' => 'datetime',
    ];

    protected $hidden = [
        'token',
    ];

    public function client()
    {
        return $this->belongsTo(Client::class);
    }

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

    public function scopeDefault($query)
    {
        return $query->where('is_default', true);
    }

    public function getDisplayNameAttribute(): string
    {
        $brand = $this->card_brand ? strtoupper($this->card_brand) : 'Card';
        $last4 = $this->last_four ? " •••• {$this->last_four}" : '';
        $label = $this->label ? " ({$this->label})" : '';

        return "{$brand}{$last4}{$label}";
    }
}
