<?php

namespace App\Livewire\Configurations\Products;

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

class Create extends Component
{
    use WithFileUploads;

    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;

    protected function rules()
    {
        return [
            'slug' => 'required|string|max:100|unique:products,slug',
            '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 store()
    {
        $this->authorize('admin.configurations.products.create');
        
        $validated = $this->validate();

        // Procesar imagen si se subió una
        if ($this->image) {
            $validated['image'] = $this->image->store('products', 'public');
        }

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

        // Crear el producto
        $product = Product::create($validated);

        // Sincronizar tipos de entornos
        if (!empty($types)) {
            $product->types()->sync($types);
        }

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

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

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