from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt
from .models import Subscriber


@csrf_exempt
@require_POST
def subscribe(request):
    email = request.POST.get('email', '').strip().lower()
    name = request.POST.get('name', '').strip()
    source = request.POST.get('source', 'footer')
    if not email:
        return JsonResponse({'ok': False, 'error': 'Email required'}, status=400)
    sub, created = Subscriber.objects.get_or_create(
        email=email, defaults={'name': name, 'source': source}
    )
    if not created and not sub.is_active:
        sub.is_active = True
        sub.unsubscribed_at = None
        sub.save()
    return JsonResponse({
        'ok': True,
        'message': 'Thanks for subscribing!' if created else 'You are already subscribed.'
    })


def unsubscribe(request):
    email = request.GET.get('email', '').strip().lower()
    if email:
        Subscriber.objects.filter(email=email).update(is_active=False)
    return render(request, 'core/unsubscribe.html', {'email': email})
