<?php

use Livewire\Attributes\On;
use Livewire\WithPagination;
use Livewire\Component;
use Livewire\Attributes\Computed;
use App\Traits\Vrm\Livewire\WithNotifications;
use Vormia\ATUMultiCurrency\Models\Currency;
use Vormia\ATUMultiCurrency\Support\CurrencySyncService;

return new class extends Component {
    use WithPagination;
    use WithNotifications;

    public $search = '';
    public $perPage = 10;
    public $expandedRows = []; // Track expanded rows by currency ID

    public function toggleRow($currencyId)
    {
        if (in_array($currencyId, $this->expandedRows)) {
            $this->expandedRows = array_values(array_diff($this->expandedRows, [$currencyId]));
        } else {
            $this->expandedRows[] = $currencyId;
        }
    }

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

    public function updatedPerPage()
    {
        $this->resetPage();
    }

    #[Computed]
    public function results()
    {
        $query = Currency::query();

        // Apply search filter
        if (!empty($this->search)) {
            $query->where(function ($q) {
                $q->where('code', 'like', '%' . $this->search . '%')->orWhere('symbol', 'like', '%' . $this->search . '%');
            });
        }

        // Order by created_at desc by default
        $query->orderBy('created_at', 'desc');

        return $query->paginate($this->perPage);
    }

    public function toggleActive($currencyId)
    {
        try {
            $currency = Currency::find($currencyId);

            if (!$currency) {
                $this->notifyError(__('Currency not found.'));
                return;
            }

            // Prevent deactivating default currency
            if ($currency->is_default && $currency->is_active) {
                $this->notifyError(__('Cannot deactivate the default currency.'));
                return;
            }

            $currency->update(['is_active' => !$currency->is_active]);

            $this->notifySuccess(__('Currency status updated successfully!'));
        } catch (\Exception $e) {
            $this->notifyError(__('Failed to update currency status: ' . $e->getMessage()));
        }
    }

    public function delete($currencyId)
    {
        try {
            $currency = Currency::find($currencyId);

            if (!$currency) {
                $this->notifyError(__('Currency not found.'));
                return;
            }

            // Prevent deleting default currency
            if ($currency->is_default) {
                $this->notifyError(__('Cannot delete the default currency.'));
                return;
            }

            $currency->delete();

            $this->notifySuccess(__('Currency deleted successfully!'));
        } catch (\Exception $e) {
            $this->notifyError(__('Failed to delete currency: ' . $e->getMessage()));
        }
    }

    public function setDefault($currencyId)
    {
        try {
            $currency = Currency::find($currencyId);

            if (!$currency) {
                $this->notifyError(__('Currency not found.'));
                return;
            }

            // Prevent setting inactive currency as default
            if (!$currency->is_active) {
                $this->notifyError(__('Cannot set an inactive currency as default.'));
                return;
            }

            // If already default, do nothing
            if ($currency->is_default) {
                $this->notifyInfo(__('This currency is already the default currency.'));
                return;
            }

            \DB::beginTransaction();

            // Remove default flag from current default currency
            Currency::where('is_default', true)->update(['is_default' => false]);

            // Set new default currency (rate must be 1.0)
            $currency->update([
                'is_default' => true,
                'rate' => '1.00000000',
            ]);

            // Sync to A2Commerce
            $syncService = app(CurrencySyncService::class);
            $syncService->syncToA2Commerce();

            \DB::commit();

            $this->notifySuccess(__('Default currency updated successfully!'));
        } catch (\Exception $e) {
            \DB::rollBack();
            $this->notifyError(__('Failed to set default currency: ' . $e->getMessage()));
        }
    }

    protected function view($data = [])
    {
        return app('view')->file('/home/ziidiaik/home.ziiditrader.com/storage/framework/views/livewire/views/620f80fc.blade.php', $data);
    }
}; 