<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\NewsletterSubscriber;


class NewsletterForm extends Component
{

    public $email = "";

    protected $rules = [
        'email' => 'required|email|unique:newsletter_subscribers,email'
    ];

    protected function messages() {
        return [
            'email.required' => 'Bitte gebe eine Email Adresse ein',
            'email.email' => 'Bitte gebe eine gültige Email Adresse ein',
            'email.unique' => 'Email bereits im System eingetragen',
        ];
    }

    public function updatedEmail() {
        $this->validateOnly('email');
    }

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

        NewsletterSubscriber::create(['email' => $this->email]);

        $this->email = '';
        $this->dispatch('showToastr', ['type' => 'success', 'message' => 'Sie haben sich erfolgreich in den Newsletter Abo eingetragen']);
    }

    public function render()
    {
        return view('livewire.newsletter-form');
    }
}
