<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\NewsletterSubscriber;
use App\Models\User;
use App\Services\EmailService;
use Illuminate\Http\Request;

class NewsletterController extends Controller
{
    public function index()
    {
        $subscribers = NewsletterSubscriber::latest()->paginate(50);
        return view('admin.newsletter.index', compact('subscribers'));
    }

    public function send(Request $request)
    {
        $request->validate([
            'subject' => 'required|string',
            'message' => 'required|string'
        ]);

        $subscribers = NewsletterSubscriber::where('status', 'active')->get();
        $emailService = new EmailService();

        foreach ($subscribers as $subscriber) {
            try {
                $emailService->sendEmail(
                    $subscriber->email,
                    $request->subject,
                    $request->message
                );
            } catch (\Exception $e) {
                continue;
            }
        }

        return back()->with('success', 'Newsletter envoyée à ' . $subscribers->count() . ' abonnés.');
    }

    public function destroy(NewsletterSubscriber $newsletter)
    {
        $newsletter->delete();
        return back()->with('success', 'Abonné supprimé.');
    }
}
