<?php

namespace App\Livewire\Frontend;

use Livewire\Component;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Models\NewsletterSubscriber as NewsletterSubscriberModel;

class NewsletterSubscriber extends Component
{

    public string $email;

    public function subscribe()
    {
        $this->validate([
            'email' => 'required|email|unique:newsletter_subscribers,email',
        ], [
            'email.unique' => 'You are already subscribed.',
        ]);

        try {
            DB::beginTransaction();

            NewsletterSubscriberModel::create([
                'email' => $this->email,
                'subscribed_at' => now(),
            ]);

            DB::commit();

            $this->reset('email');

            session()->flash('livewire_success', 'You have successfully subscribed.');
            return;
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error($e->getMessage());
            session()->flash('livewire_error', config('app.messages.error'));
            return;
        }
    }

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