<?php

namespace App\Livewire\Configurations\Products;

use App\Models\Products\Product;
use Livewire\Component;
use Livewire\WithFileUploads;

class Edit extends Component
{
    use WithFileUploads;

    public Product $product;
    public string $slug = '';
    public string $name = '';
    public ?string $summary = null;
    public ?string $description = null;
    public ?string $type = null;
    public array $types = [];
    public bool $actived = false;
    public bool $enabled = false;
    public $image = null;

    public function mount(Product $product)
    {
        $this->product = $product;
        $this->slug = $product->slug ?? '';
        $this->name = $product->name ?? '';
        $this->summary = $product->summary;
        $this->description = $product->description;
        $this->type = $product->type;
        $this->types = $product->types->pluck('id')->toArray();
        $this->actived = $product->actived ?? false;
        $this->enabled = $product->enabled ?? false;
    }

    protected function rules()
    {
        return [
            'slug' => 'required|string|max:100|unique:products,slug,' . $this->product->id,
            'name' => 'required|string|max:200',
            'summary' => 'nullable|string|max:500',
            'description' => 'nullable|string',
            'type' => 'nullable|string|max:50',
            'types' => 'array',
            'actived' => 'boolean',
            'enabled' => 'boolean',
            'image' => ['nullable', 'file', 'mimes:jpeg,jpg,png,webp,svg', 'max:5120'], // 5MB
        ];
    }

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

        // Procesar imagen si se subió una nueva
        if ($this->image) {
            // Eliminar imagen anterior si existe y NO está en images_static
            if ($this->product->image) {
                // No borrar imágenes que estén en images_static
                if (!str_starts_with($this->product->image, 'images_static/')) {
                    \Illuminate\Support\Facades\Storage::disk('public')->delete($this->product->image);
                }
            }

            // Guardar nueva imagen
            $validated['image'] = $this->image->store('products', 'public');
        } else {
            // Mantener la imagen existente
            unset($validated['image']);
        }

        // Separar types del array de validación
        $types = $validated['types'] ?? [];
        unset($validated['types']);

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

        // Sincronizar tipos de entornos
        $this->product->types()->sync($types);

        session()->flash('success', 'Producto actualizado correctamente.');
    }

    public function render()
    {
        return view('livewire.configurations.products.edit', [
            'availableTypes' => \App\Models\Environments\Type::orderBy('name')->get(),
        ])->layout('layouts.clean');
    }
}
