<?php

namespace App\Livewire\Configurations\Environments;

use App\Models\Environments\Type;
use Illuminate\Support\Facades\Storage;
use Livewire\Component;
use Livewire\WithFileUploads;

class Edit extends Component
{
    use WithFileUploads;

    public Type $type;
    public string $name = '';
    public string $shortname = '';
    public ?string $description = null;
    public $image = null;

    public function mount(Type $type)
    {
        $this->type = $type;
        $this->name = $type->name ?? '';
        $this->shortname = $type->shortname ?? '';
        $this->description = $type->description;
    }

    protected function rules()
    {
        return [
            'name' => 'required|string|max:200',
            'shortname' => 'required|string|max:20|unique:types,shortname,' . $this->type->id,
            'description' => 'nullable|string',
            'image' => ['nullable', 'file', 'mimes:jpeg,jpg,png,webp,svg', 'max:5120'],
        ];
    }

    public function update()
    {
        $this->authorize('admin.configurations.environments-types.edit');
        
        $validated = $this->validate();

        // Si hay una nueva imagen, guardarla
        if ($this->image) {
            // Eliminar imagen anterior si existe y NO está en images_static
            if ($this->type->image && Storage::disk('public')->exists($this->type->image)) {
                // No borrar imágenes que estén en images_static
                if (!str_starts_with($this->type->image, 'images_static/')) {
                    Storage::disk('public')->delete($this->type->image);
                }
            }

            // Guardar nueva imagen
            $path = $this->image->store('images/environments', 'public');
            $validated['image'] = $path;
        }

        $this->type->update($validated);

        session()->flash('success', 'Tipo de entorno actualizado correctamente.');

        return $this->redirect(route('configurations.environments-types.index'), navigate: true);
    }

    public function render()
    {
        return view('livewire.configurations.environments.edit')
        ->layout('layouts.clean');
    }
}
