<?php

namespace App\Http\Controllers;

use App\Models\NewsletterSubscriber;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class NewsletterController extends Controller
{
    public function subscribe(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'name' => 'nullable|string|max:255',
        ]);

        $existing = NewsletterSubscriber::where('email', $request->email)->first();

        if ($existing) {
            if ($existing->status === 'unsubscribed') {
                $existing->update([
                    'status' => 'pending',
                    'unsubscribed_at' => null,
                ]);
                
                if ($request->wantsJson()) {
                    return response()->json(['message' => 'Réabonnement en cours. Vérifiez votre email.']);
                }
                return back()->with('success', 'Réabonnement en cours. Vérifiez votre email.');
            }
            
            if ($request->wantsJson()) {
                return response()->json(['message' => 'Cette adresse email est déjà inscrite.'], 422);
            }
            return back()->with('error', 'Cette adresse email est déjà inscrite.');
        }

        $subscriber = NewsletterSubscriber::create([
            'email' => $request->email,
            'name' => $request->name,
            'source' => $request->get('source', 'website'),
        ]);

        if ($request->wantsJson()) {
            return response()->json([
                'message' => 'Inscription réussie !',
                'subscriber' => $subscriber,
            ], 201);
        }
        
        return back()->with('success', 'Merci ! Vous êtes inscrit à notre newsletter.');
    }

    public function confirm(string $token): JsonResponse
    {
        $subscriber = NewsletterSubscriber::where('unsubscribe_token', $token)->firstOrFail();
        
        if ($subscriber->confirmed_at) {
            return response()->json(['message' => 'Votre inscription est déjà confirmée.']);
        }

        $subscriber->confirm();

        return response()->json(['message' => 'Votre inscription à la newsletter est confirmée.']);
    }

    public function unsubscribe(string $token): JsonResponse
    {
        $subscriber = NewsletterSubscriber::where('unsubscribe_token', $token)->firstOrFail();
        $subscriber->unsubscribe();

        return response()->json(['message' => 'Vous avez été désabonné de la newsletter.']);
    }

    public function subscribers(Request $request): JsonResponse
    {
        $status = $request->get('status');

        $query = NewsletterSubscriber::latest();

        if ($status) {
            $query->where('status', $status);
        }

        $subscribers = $query->paginate(20);

        return response()->json($subscribers);
    }

    public function stats(): JsonResponse
    {
        $stats = [
            'total' => NewsletterSubscriber::count(),
            'active' => NewsletterSubscriber::active()->count(),
            'confirmed' => NewsletterSubscriber::confirmed()->count(),
            'pending' => NewsletterSubscriber::where('status', 'pending')->count(),
            'unsubscribed' => NewsletterSubscriber::where('status', 'unsubscribed')->count(),
        ];

        $recentGrowth = NewsletterSubscriber::where('created_at', '>=', now()->subMonth())->count();
        $stats['monthly_growth'] = $recentGrowth;

        return response()->json($stats);
    }
}
