<?php

namespace App\Livewire;

use App\Models\Subscriber;
use Livewire\Component;

class NewsletterForm extends Component
{
    public string $email = '';
    public bool $subscribed = false;
    public string $errorMsg = '';

    public function subscribe(): void
    {
        $this->validate(['email' => 'required|email|max:255']);

        $this->errorMsg = '';

        if (Subscriber::where('email', $this->email)->exists()) {
            $this->errorMsg = 'This email is already subscribed.';
            return;
        }

        Subscriber::create(['email' => $this->email, 'status' => 'active']);

        $this->email      = '';
        $this->subscribed = true;
    }

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