<?php

namespace App\Livewire\Products;

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

class Edit extends Component
{
    public Product $product;
    public string $slug = '';
    public string $name = '';
    public ?string $summary = null;
    public ?string $description = null;
    public ?string $tech = null;
    public ?string $type = null;
    public ?string $metadata = null;
    public bool $actived = false;
    public bool $enabled = false;

    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->tech = $product->tech;
        $this->type = $product->type;
        $this->metadata = $product->metadata ? json_encode($product->metadata, JSON_PRETTY_PRINT) : null;
        $this->actived = $product->actived ?? false;
        $this->enabled = $product->enabled ?? false;
    }

    protected function rules()
    {
        return [
            'slug' => 'required|string|max:200|unique:products,slug,' . $this->product->id,
            'name' => 'required|string|max:200',
            'summary' => 'required|string',
            'description' => 'nullable|string',
            'tech' => 'required|string|max:50',
            'type' => 'required|string|max:50',
            'metadata' => 'nullable|string',
            'actived' => 'nullable|boolean',
            'enabled' => 'nullable|boolean',
        ];
    }

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

        // Procesar metadata JSON
        if (!empty($validated['metadata'])) {
            $decoded = json_decode($validated['metadata'], true);
            $validated['metadata'] = json_last_error() === JSON_ERROR_NONE ? $decoded : null;
        } else {
            $validated['metadata'] = null;
        }

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

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

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

    public function render()
    {
        return view('livewire.products.edit')->layout('layouts.app');
    }
}

