<?php
namespace App\Livewire;

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

class Currencies extends Component
{
    public $currencies;
    public $isEditing = false;
    public $editId = null;

    public $form = [
        'code' => '',
        'name' => '',
        'symbol' => '',
        'major_unit' => '',
        'minor_unit' => '',
        'is_active' => true,
    ];

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

    public function loadCurrencies()
    {
        $this->currencies = Currency::all();
    }

    public function create()
    {
        $this->resetForm();
        $this->isEditing = true;
    }

    public function edit($id)
    {
        $this->resetForm();
        $this->editId = $id;
        $currency = Currency::findOrFail($id);
        
        $this->form = [
            'code' => $currency->code,
            'name' => $currency->name,
            'symbol' => $currency->symbol,
            'major_unit' => $currency->major_unit,
            'minor_unit' => $currency->minor_unit,
            'is_active' => (bool) $currency->is_active,
        ];
        
        $this->isEditing = true;
    }

    public function save()
    {
        $this->validate([
            'form.code' => 'required|string|max:10',
            'form.name' => 'required|string|max:255',
        ]);

        if ($this->editId) {
            $currency = Currency::findOrFail($this->editId);
            $currency->update($this->form);
        } else {
            Currency::create($this->form);
        }

        $this->isEditing = false;
        $this->loadCurrencies();
        
        // Dispatch an event to refresh other components (like Settings) that might depend on this
        $this->dispatch('currencies-updated');
        
        session()->flash('currency_message', 'تم حفظ العملة بنجاح.');
    }

    public function delete($id)
    {
        Currency::findOrFail($id)->delete();
        $this->loadCurrencies();
        $this->dispatch('currencies-updated');
        session()->flash('currency_message', 'تم حذف العملة بنجاح.');
    }

    public function cancel()
    {
        $this->isEditing = false;
        $this->resetForm();
    }

    private function resetForm()
    {
        $this->editId = null;
        $this->form = [
            'code' => '',
            'name' => '',
            'symbol' => '',
            'major_unit' => '',
            'minor_unit' => '',
            'is_active' => true,
        ];
    }

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