<?php

namespace App\Livewire\Forms\Admin\Opciones;

use App\Models\Opcion;
use Livewire\Attributes\Validate;
use Livewire\Form;

class NuevaOpcionForm extends Form
{
    public $nombre;
    public $tipo=1;
    public $caracteristicas = [
        [
            'valor' => '',
            'descripcion' => ''
        ]
    ];

    public $openModal = false;

    public function rules(){
        $rules= [
            'nombre' => 'required',
            'tipo' => 'required|in:1,2',
            'caracteristicas' => 'required|array|min:1',
        ];

        foreach($this->caracteristicas as $index => $caracteristica){
            if($this->tipo==1){
                $rules['caracteristicas.'.$index.'.valor']='required';
            }else{
                $rules['caracteristicas.'.$index.'.valor']='required|regex:/^#[a-f0-9]{6}$/i';
            }
            $rules['caracteristicas.'.$index.'.descripcion']='required|max:255';
        }

        return $rules;
    }

    public function validationAttributes(){

        $attributes = [];

        foreach($this->caracteristicas as $index => $caracteristica){
            $attributes['caracteristicas.'.$index.'.valor']='valor '. ($index+1);
            $attributes['caracteristicas.'.$index.'.descripcion']='descripcion '.($index+1);
        }
        return $attributes;
    }

    public function addCaracteristica(){
        $this->caracteristicas[] = [
            'valor' => '',
            'descripcion' => ''
        ];
    }

    public function removeCaracteristica($index)
    {
        unset($this->caracteristicas[$index]);
        $this->caracteristicas = array_values($this->caracteristicas);
    }

    public function save(){
        $this->validate();

        $opcion= Opcion::create([
            'nombre' => $this->nombre,
            'tipo' => $this->tipo
        ]);

        foreach($this->caracteristicas as $caracteristica){
            $opcion->caracteristicas()->create([
                'valor' => $caracteristica['valor'],
                'descripcion' => $caracteristica['descripcion']
            ]);
        }

        $this->reset();
    }

}
