<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class CreditCard extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'card_number',
        'card_pin',
        'balance',
        'last_four',
        'card_type',
        'status',
        'extra_data',
        'expiry_date',
        'requested_at',
    ];

    protected $casts = [
        'extra_data' => 'array',
        'balance' => 'decimal:2',
    ];

    /**
     * Relationship: CreditCard belongs to a User
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Boot method to auto-generate card number on creation
     */
    protected static function booted()
    {
        static::creating(function ($card) {
            // Only generate if card_number not provided
            if (!$card->card_number) {
                $generated = self::generateCardNumber($card->card_type ?? 'visa');
                $card->card_number = $generated;
                $card->last_four = substr($generated, -4);
            }

            // Default expiry date to 3 years from now if not provided
            if (!$card->expiry_date) {
                $card->expiry_date = now()->addYears(3)->format('Y-m-d');
            }

            // Set requested_at timestamp if not provided
            if (!$card->requested_at) {
                $card->requested_at = now();
            }
        });
    }

    /**
     * Generate a mock credit card number based on type
     * Note: This is **fake/for testing purposes only**, not for real payments.
     */
    public static function generateCardNumber(string $type): string
    {
        $prefix = match (strtolower($type)) {
            'visa' => '4',
            'mastercard' => '5',
            'amex' => '3',
            'discover' => '6',
            default => '4', // default to Visa
        };

        // Generate remaining digits to reach 16 digits (Amex = 15)
        $length = $prefix === '3' ? 15 : 16;
        $number = $prefix;

        while (strlen($number) < $length) {
            $number .= random_int(0, 9);
        }

        return $number;
    }
}
