<?php

namespace App\Livewire\Admin\Forms;

use Livewire\Component;
use App\Models\Admin\Forms;
use Illuminate\Support\Str;

class Create extends Component
{
    public $name;
    public $slug;
    public $description;
    public $store_data = 1;
    public $send_email = 0;
    public $recipient_address;
    public $email_subject;

    public function updatedSendEmail($value)
    {
        if ($value == 0) {
            $this->reset(['recipient_address', 'email_subject']);
        }
    }

    public function updatedName($value)
    {
        $this->slug = Str::slug($value);
    }

    public function save()
    {
        $form = Forms::create([
            'name' => $this->name,
            'slug' => $this->slug,
            'description' => $this->description,
            'store_data' => $this->store_data,
            'send_email' => $this->send_email,
            'recipient_address' => $this->recipient_address,
            'email_subject' => $this->email_subject,
        ]);

        activity()->performedOn($form)->causedBy(auth()->id())->log('Form oluşturuldu');

        $this->dispatch('showAlert', [
            'title' => 'Başarılı!', 'text' => 'Form oluşturuldu.', 'icon' => 'success'
        ]);

        $this->reset();
    }

    public function saveAndRedirect()
    {
        $this->save();
        return redirect()->route('admin.forms.index');
    }

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