<?php

namespace Modules\Main\Http\Livewire;

use Livewire\Component;
use Livewire\Attributes\On;
use Modules\Contracts\Models\ContractStatus;
use Modules\Main\Models\Deal\DealStatus;

class ClientSearchInputLivewire extends Component
{
    public $filter = [];
    public $complexes;
    public function mount()
    {
        $this->complexes = GetAvailableComplexes();
        $this->setStatus(DealStatus::UNIQUE);
        $this->updated();
    }

    public function setStatus($status)
    {
        if (array_key_exists('status', $this->filter) && $this->filter['status'] === $status) {
            unset($this->filter['status']);
            return;
        }
        $this->filter['status'] = $status;
    }

    public function toggleComplex($complexId)
    {
        if (!array_key_exists('complexes', $this->filter)) {
            $this->filter['complexes'] = [];
        }
        $disabled = false;
        foreach ($this->filter['complexes'] as $selectedKey=>$selectedComplex) {
            if ($selectedComplex['id'] == $complexId) {
                unset($this->filter['complexes'][$selectedKey]);
                $disabled = true;
            }
        }
        if (!$disabled) {
            foreach ($this->complexes as $complex) {
                if($complex['id'] == $complexId) {
                    $this->filter['complexes'][] = ['id' => $complexId, 'name' => $complex['name']];
                }
            }
        }
        $this->filter['complexes'] = array_values($this->filter['complexes']);
        if (!count($this->filter['complexes'])) {
            unset($this->filter['complexes']);
        }

        $this->updated();
    }

    public function removeSearchString() {
        unset($this->filter['search']);
        $this->updated();
    }
    public function updated()
    {
        $this->dispatch('clientsTableFilterUpdated', filter: $this->filter);
    }

    public function render()
    {
        return view('main::clients.livewire.search.input', [
            'statuses' => DealStatus::class
        ]);
    }


}