<?php

namespace App\Livewire\ScssCdn;

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

class BundleEdit extends Component
{
    public Product $product;
    public ScssCdnBundle $bundle;
    public string $version = '';
    public ?string $description = null;

    public function mount(Product $product, ScssCdnBundle $bundle)
    {
        $this->product = $product;
        $this->bundle = $bundle->load('product');
        
        // Verificar que el bundle pertenezca al producto
        if ($this->bundle->product_id !== $this->product->id) {
            abort(404, 'El bundle no pertenece a este producto.');
        }

        $this->version = $bundle->version;
        $this->description = $bundle->description;
    }

    public function save()
    {
        $this->validate([
            'version' => ['required', 'string', 'size:10', 'regex:/^\d{10}$/'],
            'description' => ['nullable', 'string', 'max:1000'],
        ], [
            'version.required' => 'La versión es obligatoria.',
            'version.size' => 'La versión debe tener 10 dígitos (formato YYYYMMDDXX).',
            'version.regex' => 'La versión debe contener solo números.',
        ]);

        // Verificar que la versión no exista (si cambió)
        if ($this->version !== $this->bundle->version) {
            $exists = ScssCdnBundle::where('product_id', $this->product->id)
                ->where('version', $this->version)
                ->where('id', '!=', $this->bundle->id)
                ->exists();

            if ($exists) {
                $this->addError('version', 'Ya existe un bundle con esta versión para este producto.');
                return;
            }
        }

        try {
            $this->bundle->update([
                'version' => $this->version,
                'description' => $this->description,
                'updated_by' => auth()->id(),
            ]);

            session()->flash('success', 'Bundle actualizado correctamente.');
            return $this->redirect(route('products.scss-cdn.bundle.show', [$this->product, $this->bundle]), navigate: true);
        } catch (\Exception $e) {
            $this->addError('version', 'Error al actualizar el bundle: ' . $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.scss-cdn.bundle-edit', [
            'product' => $this->product,
        ])->layout('layouts.clean');
    }
}
