<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;

class BankAccount extends Model
{
    use HasFactory;

    protected $fillable = [
        'finance_user_id',
        'finance_group_id',
        'account_name',
        'account_holder',
        'account_holder_name',
        'bank_name',
        'iban',
        'description',
        'account_number',
        'branch_name',
        'branch_code',
        'daily_limit',
        'min_amount',
        'max_amount',
        'is_active',
        'is_blocked',
        'created_by',
    ];

    protected $casts = [
        'daily_limit' => 'decimal:2',
        'min_amount' => 'decimal:2',
        'max_amount' => 'decimal:2',
        'is_active' => 'boolean',
        'is_blocked' => 'boolean',
    ];

    /**
     * Get the finance user who owns this account
     */
    public function financeUser()
    {
        return $this->belongsTo(FinanceUser::class);
    }

    /**
     * Get the finance group this account belongs to
     */
    public function financeGroup()
    {
        return $this->belongsTo(FinanceGroup::class);
    }

    /**
     * Get the backoffice user who created this account
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Get transactions using this bank account
     */
    public function transactions()
    {
        return $this->hasMany(Transaction::class);
    }

    /**
     * Per-site status overrides for this bank account.
     */
    public function siteStatuses()
    {
        return $this->hasMany(BankAccountSiteStatus::class);
    }

    /**
     * Check if account can handle this amount
     */
    public function canHandleAmount($amount)
    {
        return !$this->is_blocked &&
               $this->is_active &&
               $amount >= $this->min_amount &&
               $amount <= $this->max_amount;
    }

    /**
     * Get pending transactions count for this account
     */
    public function getPendingTransactionsCount()
    {
        return $this->transactions()->where('status', 'pending')->count();
    }

    /**
     * Scope a query to only include active bank accounts
     */
    public function scopeActive($query)
    {
        $query->where('is_active', true);
        if (Schema::hasColumn($this->getTable(), 'is_blocked')) {
            $query->where('is_blocked', false);
        }

        return $query;
    }

    /**
     * Effective active state for a specific site.
     */
    public function isActiveForSite(?int $siteId): bool
    {
        if ((bool) $this->is_blocked) {
            return false;
        }

        if (!$siteId) {
            return (bool) $this->is_active;
        }

        $siteStatus = $this->relationLoaded('siteStatuses')
            ? $this->siteStatuses->firstWhere('site_id', $siteId)
            : $this->siteStatuses()->where('site_id', $siteId)->first();

        if (!$siteStatus) {
            return (bool) $this->is_active;
        }

        return (bool) $siteStatus->is_active;
    }

    /**
     * Accessor for account_name (maps to account_holder_name)
     */
    public function getAccountNameAttribute()
    {
        if (array_key_exists('account_name', $this->attributes) && $this->attributes['account_name'] !== null) {
            return $this->attributes['account_name'];
        }

        return $this->account_holder_name;
    }

    /**
     * Accessor for account_holder (fallback to account_holder_name)
     */
    public function getAccountHolderAttribute($value)
    {
        return $value ?? $this->account_holder_name;
    }

    /**
     * Accessor for branch_name (fallback to branch_code)
     */
    public function getBranchNameAttribute($value)
    {
        return $value ?? $this->branch_code;
    }

    /**
     * Accessor for branch (maps to branch_code)
     */
    public function getBranchAttribute()
    {
        return $this->branch_name ?? $this->branch_code;
    }
}
