<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Newsletter;
use Illuminate\Validation\Rule;
use App\Notifications\WelcomeSubscriber;

class NewsletterForm extends Component
{
    public $email;
    public $success = false;

    protected function rules()
    {
        return [
            'email' => [
                'required',
                'email',
                'max:255',
                Rule::unique('newsletters')->where(fn ($query) => $query->where('is_subscribed', 1)),
            ],
        ];
    }

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

    // Create temporary email variable
    $email = $this->email;

    
        
        $newsletter = Newsletter::updateOrCreate(
            ['email' => $this->email],
            [
                'is_subscribed' => 1,
                'subscribed_at' => now(),
            ]
        );

        // Send welcome notification
        $newsletter->notify(new WelcomeSubscriber());

        // Show success message and reset form
        $this->success = true;
        $this->resetValidation();
        $this->reset('email');
    }

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