<?php

namespace App\Livewire;

use App\Models\Subscriber;
use App\Notifications\EmailNotification;
use App\Notifications\SmsNotification;
use Livewire\Component;
use Livewire\Attributes\Validate;
use Illuminate\Support\Facades\Log;

class NewsletterSubscribe extends Component
{
    #[Validate('required|email|max:255|unique:subscribers,email')]
    public $email = '';

    public $successMessage = '';

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

        try {
            Log::info('Newsletter subscription started', [
                'email' => $this->email,
            ]);

            // Save subscriber to database
            Subscriber::create([
                'email' => $this->email,
                'is_active' => true,
            ]);

            Log::info('Subscriber saved to database');

            // Send welcome email to subscriber
            try {
                Log::info('Attempting to send welcome email to subscriber');
                EmailNotification::welcomeSubscriber($this->email);
                Log::info('Welcome email sent successfully');
            } catch (\Exception $e) {
                Log::error('Failed to send welcome email: ' . $e->getMessage());
            }

            // Send notification to admin via SMS
            try {
                Log::info('Attempting to send SMS notification to admin');
                SmsNotification::newSubscriber($this->email);
                Log::info('SMS notification sent successfully');
            } catch (\Exception $e) {
                Log::error('Failed to send SMS notification: ' . $e->getMessage());
            }

            // Send notification to admin via Email
            try {
                Log::info('Attempting to send Email notification to admin');
                EmailNotification::newSubscriber($this->email);
                Log::info('Email notification sent successfully');
            } catch (\Exception $e) {
                Log::error('Failed to send Email notification: ' . $e->getMessage());
            }

            $this->successMessage = 'Thank you for subscribing to our newsletter!';

            // Reset form
            $this->reset(['email']);

            // Dispatch browser event for success notification
            $this->dispatch('subscribed');

            Log::info('Newsletter subscription completed successfully');

        } catch (\Exception $e) {
            Log::error('Newsletter subscription error: ' . $e->getMessage(), [
                'exception' => get_class($e),
                'trace' => $e->getTraceAsString(),
            ]);
            $this->addError('email', 'Something went wrong. Please try again later.');
        }
    }

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