<?php

namespace App\Livewire\Admin\Comment;

use App\Models\Comment;
use Illuminate\Support\Facades\DB;
use Livewire\Component;

class Create extends Component
{
    public $product, $client, $description, $rating;

    public function render()
    {
        return view('livewire.admin.comment.create');
    }

    public function mount()
    {
        $this->rating = 1;
    }

    public function save()
    {
        $this->validate([
            'client'        => 'required|string|min:4|max:200',
            'description'   => 'required|string|min:4|max:50000',
            'rating'        => 'required|integer|min:1|max:5',
        ]);
        
        DB::beginTransaction();
        try {
            //
            $comment = Comment::create([
                'client'        => $this->client,
                'description'   => $this->description,
                'rating'        => $this->rating,
                'product_id'    => $this->product->id,
            ]);

            DB::commit();
            session()->flash('status', 'Los datos se guardaron correctamente.');
            return redirect()->route('comments.index',$this->product);
        } catch (\Throwable $th) {
            DB::rollBack();
            info($th->getMessage());
        }
    }
}
