<?php

use Livewire\WithPagination;
use Livewire\Component;
use Livewire\Attributes\Computed;
use App\Traits\Vrm\Livewire\WithNotifications;
use Vormia\ATUMultiCurrency\Models\CurrencyConversionLog;

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

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

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

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

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

    #[Computed]
    public function results()
    {
        $query = CurrencyConversionLog::with(['currency', 'user']);

        // Apply search filter
        if (!empty($this->search)) {
            $searchTerm = $this->search;
            $query->where(function ($q) use ($searchTerm) {
                $q->where('entity_type', 'like', '%' . $searchTerm . '%')
                    ->orWhere('base_currency_code', 'like', '%' . $searchTerm . '%')
                    ->orWhere('target_currency_code', 'like', '%' . $searchTerm . '%')
                    ->orWhereHas('currency', function ($currencyQuery) use ($searchTerm) {
                        $currencyQuery->where('code', 'like', '%' . $searchTerm . '%');
                    })
                    ->orWhereHas('user', function ($userQuery) use ($searchTerm) {
                        $userQuery->where('name', 'like', '%' . $searchTerm . '%')->orWhere('email', 'like', '%' . $searchTerm . '%');
                    });
            });
        }

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

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

    protected function view($data = [])
    {
        return app('view')->file('/home/ziidfelj/home.ziidi.trade/storage/framework/views/livewire/views/f4d8df4a.blade.php', $data);
    }
}; 