<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Currency;

class AdminCurrencies extends Component
{
    public $currencies;
    public $search = '';
    public $editingCurrency;
    public $editLeverage;
    public $editStatus;

    public function mount()
    {
        $this->loadCurrencies();
    }

    public function updatedSearch()
    {
        $this->loadCurrencies();
    }

    public function loadCurrencies()
    {
        $this->currencies = Currency::where('name', 'like', '%' . $this->search . '%')->get();
    }

    public function toggleEnabled($currencyId)
    {
        $currency = Currency::find($currencyId);
        if ($currency) {
            $currency->enabled = !$currency->enabled;
            $currency->save();
            $this->loadCurrencies();
        }
    }

    public function updateLeverage($currencyId, $leverage)
    {
        $currency = Currency::find($currencyId);
        if ($currency) {
            $currency->leverage = $leverage;
            $currency->save();
            $this->loadCurrencies();
        }
    }

    public function editCurrency($currencyId)
    {
        $this->editingCurrency = Currency::find($currencyId);
        if ($this->editingCurrency) {
            $this->editLeverage = $this->editingCurrency->leverage;
            $this->editStatus = $this->editingCurrency->enabled;
        }
    }

    public function updateCurrency()
    {
        if ($this->editingCurrency) {
            $this->editingCurrency->leverage = $this->editLeverage;
            $this->editingCurrency->enabled = $this->editStatus;
            $this->editingCurrency->save();
            $this->loadCurrencies();
            $this->editingCurrency = null;
            $this->dispatch('close-modal');
        }
    }

    public function render()
    {
        return view('livewire.admin-currencies');
    }
}
