<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;

class Bank extends Model
{
    protected $fillable = [
        'bank_name',
        'bank_type',
        'logo',
        'account_number',
        'account_type',
        'account_holder',
        'rnc',
        'phone_number',
        'currency',
        'instructions',
        'is_active',
        'sort_order',
    ];

    protected $casts = [
        'is_active' => 'boolean',
    ];

    protected $appends = ['logo_url'];

    /**
     * Get the logo URL.
     */
    public function getLogoUrlAttribute(): ?string
    {
        if (!$this->logo) {
            return null;
        }

        return Storage::url($this->logo);
    }

    /**
     * Scope for active banks.
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope for ordered banks.
     */
    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order')->orderBy('bank_name');
    }

    /**
     * Get account type label.
     */
    public function getAccountTypeLabelAttribute(): string
    {
        return match($this->account_type) {
            'savings' => 'Cuenta de Ahorro',
            'checking' => 'Cuenta Corriente',
            default => $this->account_type,
        };
    }

    /**
     * Get formatted account for display.
     */
    public function getFormattedAccountAttribute(): string
    {
        return "{$this->bank_name} - {$this->account_type_label}\n" .
               "Cuenta: {$this->account_number}\n" .
               "Titular: {$this->account_holder}";
    }
}
