<?php

use App\Models\Security;
use App\Traits\Vrm\Livewire\WithNotifications;
use Livewire\Attributes\Computed;
use Livewire\Component;
use Livewire\WithPagination;

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

    public string $search = '';
    public int $perPage = 10;

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

    #[Computed]
    public function securities()
    {
        return Security::query()
            ->with('latestLog')
            ->with(['logs' => fn ($query) => $query->latest('logged_at')->limit(2)])
            ->withCount('logs')
            ->when($this->search !== '', function ($query): void {
                $query->where(function ($innerQuery): void {
                    $innerQuery->where('description', 'like', "%{$this->search}%")
                        ->orWhere('trading_name', 'like', "%{$this->search}%");
                });
            })
            ->orderByDesc('created_at')
            ->paginate($this->perPage);
    }

    public function activate(int $securityId): void
    {
        $security = Security::query()->find($securityId);

        if (! $security) {
            $this->notifyError(__('Security not found.'));

            return;
        }

        $security->update(['is_active' => true]);
        $this->notifySuccess(__('Security activated.'));
    }

    public function deactivate(int $securityId): void
    {
        $security = Security::query()->find($securityId);

        if (! $security) {
            $this->notifyError(__('Security not found.'));

            return;
        }

        $security->update(['is_active' => false]);
        $this->notifySuccess(__('Security deactivated.'));
    }

    public function delete(int $securityId): void
    {
        $security = Security::query()->find($securityId);

        if (! $security) {
            $this->notifyError(__('Security not found.'));

            return;
        }

        $security->delete();
        $this->notifySuccess(__('Security deleted.'));
    }


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