<?php

namespace App\Livewire\Setups;

use App\Models\Products\Product;
use App\Models\Setups\Setup;
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component
{
    use WithPagination;

    public Product $product;
    public string $search = '';
    public ?string $statusFilter = null;

    protected $queryString = ['search', 'statusFilter'];

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

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

    public function toggleStatus($id)
    {
        $setup = Setup::findOrFail($id);

        $newStatus = $setup->status === 'active' ? 'deprecated' : 'active';
        $setup->update([
            'status' => $newStatus,
            'updated_by' => auth()->id(),
            'change_log' => "Estado cambiado a {$newStatus}",
        ]);

        // Crear entrada en historial
        $setup->createHistoryEntry("Estado cambiado a {$newStatus}");

        $statusLabel = $newStatus === 'active' ? 'activo' : 'deprecado';
        session()->flash('success', "Setup marcado como {$statusLabel} correctamente.");
    }

    public function duplicate($id)
    {
        try {
            $setup = Setup::findOrFail($id);
            $newSetup = $setup->duplicate();

            session()->flash('success', "Setup duplicado. Nueva versión: {$newSetup->version}");

            return $this->redirect(route('products.setups.edit', [$this->product, $newSetup]), navigate: true);
        } catch (\Exception $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function mount(Product $product)
    {
        $this->product = $product;
    }

    public function render()
    {
        $setups = Setup::query()
            ->with(['creator', 'product'])
            ->where('product_id', $this->product->id)
            ->when($this->search, function ($query) {
                $query->where('version', 'like', "%{$this->search}%");
            })
            ->when($this->statusFilter, function ($query) {
                if ($this->statusFilter === 'active') {
                    $query->active();
                } elseif ($this->statusFilter === 'deprecated') {
                    $query->deprecated();
                }
            })
            ->orderByDesc('version')
            ->paginate(20);

        return view('livewire.setups.index', [
            'setups' => $setups,
            'product' => $this->product,
        ])->layout('layouts.app');
    }
}


