<?php

namespace App\Livewire\Admin\Forms;

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

class Edit extends Component
{
    public $name;
    public $slug;
    public $description;
    public $store_data;
    public $send_email;
    public $recipient_address;
    public $email_subject;

    public Forms $form;

    public function mount(Forms $form)
    {
        $this->form = $form;

        $this->name = $form->name;
        $this->slug = $form->slug;
        $this->description = $form->description;
        $this->store_data = $form->store_data;
        $this->send_email = $form->send_email;
        $this->recipient_address = $form->recipient_address;
        $this->email_subject = $form->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()
    {
        $this->form->update([
            '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($this->form)->causedBy(auth()->id())->log('Form güncellendi');

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

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