<?php

namespace App\Models;

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

class Beneficiary extends Model
{
    use HasFactory;

    // Type constants
    public const LOCAL = 'local';
    public const INTERNATIONAL = 'international';

    protected $fillable = [
        'user_id',
        'nickname',
        'account_number',
        'type',
        'meta',
    ];

    protected $casts = [
        'meta' => 'array', // Store JSON as array
    ];

    // Frontend-only attributes
    protected $appends = ['initials', 'color'];

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

    /**
     * Scope for local beneficiaries
     */
    public function scopeLocal($query)
    {
        return $query->where('type', self::LOCAL);
    }

    /**
     * Scope for international beneficiaries
     */
    public function scopeInternational($query)
    {
        return $query->where('type', self::INTERNATIONAL);
    }

    /**
     * Helper to get meta fields safely
     */
    public function getMetaField(string $key, $default = null)
    {
        return $this->meta[$key] ?? $default;
    }

    /**
     * Frontend-only: Get initials from meta.recipient_name, nickname, or account number
     */
    public function getInitialsAttribute(): string
    {
        $name = $this->getMetaField('recipient_name')
            ?? $this->nickname
            ?? $this->account_number
            ?? 'NA';

        return collect(explode(' ', $name))
            ->map(fn($word) => strtoupper(substr($word, 0, 1)))
            ->implode('');
    }

    /**
     * Frontend-only: Generate a consistent color based on recipient_name, nickname, or account
     */
    public function getColorAttribute(): string
    {
        $colors = [
            'bg-red-500',
            'bg-blue-500',
            'bg-green-500',
            'bg-purple-500',
            'bg-yellow-500',
            'bg-pink-500',
        ];

        $key = $this->getMetaField('recipient_name')
            ?? $this->nickname
            ?? $this->account_number
            ?? 'NA';

        return $colors[crc32($key) % count($colors)];
    }
}
