<?php

namespace Modules\User\Models;

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

class UserCard extends Model
{
    use SoftDeletes;
    protected $fillable = ['card_number', 'month','year','user_id'];

    public function getCardAttribute()
    {
        return preg_replace_callback('/\d(?=\d{4})/', function ($matches) {
            return '*';
        }, $this->card_number);
    }

    public function getCardLastAttribute()
    {
        return substr($this->card_number, -4);
    }

    public function getCardTypeAttribute()
    {
        $cardNumber = preg_replace('/\D/', '', $this->card_number); // Remove non-numeric characters

        $patterns = [
            'visa'       => '/^4[0-9]{12}(?:[0-9]{3})?$/',        // Visa: 13 or 16 digits, starts with 4
            'mastercard' => '/^5[1-5][0-9]{14}$/',               // MasterCard: 16 digits, starts with 51-55
            'amex'       => '/^3[47][0-9]{13}$/',                // American Express: 15 digits, starts with 34 or 37
            'discover'   => '/^6(?:011|5[0-9]{2})[0-9]{12}$/',   // Discover: 16 digits, starts with 6011 or 65
            'diners'     => '/^3(?:0[0-5]|[68][0-9])[0-9]{11}$/', // Diners Club: 14 digits, starts with 300-305, 36, 38
            'jcb'        => '/^(?:2131|1800|35\d{3})\d{11}$/',   // JCB: 15 or 16 digits, starts with 2131, 1800, or 35
        ];

        foreach ($patterns as $type => $pattern) {
            if (preg_match($pattern, $cardNumber)) {
                return ucfirst($type); // Return card type with the first letter capitalized
            }
        }

        return 'unknown';
    }
}
