<?php

namespace App\Livewire\Tutorials;

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

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

    public function mount(Product $product)
    {
        $this->product = $product;
        
        // Generar versión por defecto basada en la fecha actual
        $this->version = date('Ymd') . '00';
        
        // Verificar que no exista ya esta versión
        $exists = TutorialVersion::where('product_id', $this->product->id)
            ->where('version', $this->version)
            ->exists();

        if ($exists) {
            // Si existe, buscar la última versión y generar la siguiente
            $lastVersion = TutorialVersion::where('product_id', $this->product->id)
                ->orderByDesc('version')
                ->first();
            
            if ($lastVersion) {
                $this->version = $lastVersion->generateNextVersion();
            } else {
                // Incrementar manualmente
                $this->version = str_pad((string) ((int) $this->version + 1), 10, '0', STR_PAD_LEFT);
            }
        }
    }

    protected function rules()
    {
        return [
            'version' => [
                'required',
                'string',
                'regex:/^\d{10}$/',
                function ($attribute, $value, $fail) {
                    // Validar que no exista otra versión con el mismo producto y versión
                    $exists = TutorialVersion::where('product_id', $this->product->id)
                        ->where('version', $value)
                        ->exists();
                    if ($exists) {
                        $fail('Ya existe una versión con este número para este producto.');
                    }
                },
            ],
            'description' => [
                'nullable',
                'string',
                'max:1000',
            ],
        ];
    }

    protected function messages()
    {
        return [
            'version.required' => 'La versión es obligatoria.',
            'version.regex' => 'La versión debe tener el formato YYYYMMDDXX (10 dígitos).',
            'description.max' => 'La descripción no puede exceder 1000 caracteres.',
        ];
    }

    public function save()
    {
        $this->authorize('admin.tutorials.version.create');
        
        $validated = $this->validate();

        $tutorialVersion = TutorialVersion::create([
            'product_id' => $this->product->id,
            'version' => $validated['version'],
            'description' => $validated['description'],
            'created_by' => auth()->id(),
            'updated_by' => auth()->id(),
        ]);

        session()->flash('success', 'Versión de Tutoriales creada correctamente.');

        return $this->redirect(route('products.tutorials.version.show', [$this->product, $tutorialVersion]), navigate: true);
    }

    public function render()
    {
        return view('livewire.tutorials.version-create', [
            'product' => $this->product,
        ])->layout('layouts.clean');
    }
}


