<?php

namespace App\Livewire\Plugins;

use App\Models\Environments\Plugin;
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component
{
    use WithPagination;

    public ?string $componentFilter = null;

    public ?string $typeFilter = null;

    public bool $onlyWithOutdatedEnvironments = false;

    public ?string $selectedComponent = null;

    public bool $showEnvironmentsModal = false;

    public bool $showOnlyOutdatedInModal = false;

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

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

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

    public function getPluginsAggregatedProperty()
    {
        $query = Plugin::query()
            ->selectRaw('component, type, MIN(name) as name, COUNT(DISTINCT environment_id) as environments_count, COUNT(DISTINCT CASE WHEN has_updates = 1 THEN environment_id END) as environments_outdated_count')
            ->groupBy('component', 'type');

        if ($this->componentFilter !== null && $this->componentFilter !== '') {
            $term = '%' . trim($this->componentFilter) . '%';
            $query->where('component', 'like', $term);
        }

        if ($this->typeFilter !== null && $this->typeFilter !== '') {
            $query->where('type', $this->typeFilter);
        }

        if ($this->onlyWithOutdatedEnvironments) {
            $query->havingRaw('COUNT(DISTINCT CASE WHEN has_updates = 1 THEN environment_id END) > 0');
        }

        return $query->orderBy('component')->paginate(25);
    }

    public function openEnvironmentsModal(string $component, bool $onlyOutdated = false): void
    {
        $this->selectedComponent = $component;
        $this->showOnlyOutdatedInModal = $onlyOutdated;
        $this->showEnvironmentsModal = true;
    }

    public function closeEnvironmentsModal(): void
    {
        $this->showEnvironmentsModal = false;
        $this->selectedComponent = null;
        $this->showOnlyOutdatedInModal = false;
    }

    public function getSelectedComponentEnvironmentsProperty()
    {
        if (!$this->selectedComponent) {
            return collect();
        }

        $query = Plugin::with('environment')
            ->where('component', $this->selectedComponent);

        if ($this->showOnlyOutdatedInModal) {
            $query->where('has_updates', true);
        }

        return $query->orderBy('environment_id')->get();
    }

    public function render()
    {
        return view('livewire.plugins.index', [
            'plugins' => $this->pluginsAggregated,
        ])->layout('layouts.app');
    }
}

