<?php

namespace App\Http\Livewire;

use App\Models\Transaction;
use Livewire\Component;

class AccountUsageBar extends Component
{
    public $selectedAccount;
    public $balancePct = 1;
    public $hasTransactions = false;

    protected $listeners = [
        'fromAccountId',
    ];

    public function mount()
    {
        $this->selectedAccount = [
            'id' => null,
            'name' => '',
            'balance' => 0,
            'limitMin' => 0,
            'limitMax' => 0,
            'available' => 0,
            'limitReceivable' => 0,
        ];
    }

    public function fromAccountId($selectedAccount)
    {
        $this->selectedAccount = $selectedAccount;
        // Calculate balance percentage (set to 100% if limitMax is 0)
        $this->balancePct = $selectedAccount['limitMax'] == 0 ? 100 : ($selectedAccount['balance'] / $selectedAccount['limitMax']) * 100;
        $this->selectedAccount['available'] = $selectedAccount['limitMax'] - $selectedAccount['balance'];
        $this->hasTransactions = Transaction::where('from_account_id', $selectedAccount['id'])
            ->orWhere('to_account_id', $selectedAccount['id'])
            ->exists();
    }

    public function render()
    {
        return view('livewire.account-usage-bar');
    }
}
