import logging
from django.views.generic import TemplateView
from django.views import View
from django.http import JsonResponse
from django.core.mail import send_mail
from django.conf import settings
from .forms import ContactForm

logger = logging.getLogger(__name__)


class HomeView(TemplateView):
    template_name = 'core/home.html'


class ContactAjaxView(View):
    """Reçoit le formulaire en AJAX, répond en JSON — pas de rechargement."""

    def post(self, request, *args, **kwargs):
        form = ContactForm(request.POST)
        if form.is_valid():
            contact = form.save()
            subject = f"Nouvelle demande de contact — {contact.first_name} {contact.last_name}"
            body = (
                f"Nom : {contact.last_name}\n"
                f"Prénom : {contact.first_name}\n"
                f"Email : {contact.email}\n"
                f"Téléphone : {contact.phone or '—'}\n\n"
                f"Demande :\n{contact.message}"
            )
            try:
                send_mail(
                    subject,
                    body,
                    settings.DEFAULT_FROM_EMAIL,
                    [settings.CONTACT_NOTIFY_EMAIL],
                    fail_silently=False,
                )
                logger.info("Mail contact #%s envoyé → %s", contact.pk, settings.CONTACT_NOTIFY_EMAIL)
            except Exception as e:
                logger.error("Échec mail contact #%s : %s — %s", contact.pk, type(e).__name__, e)
            return JsonResponse({'ok': True})
        else:
            errors = {f: e.get_json_data() for f, e in form.errors.items()}
            return JsonResponse({'ok': False, 'errors': errors}, status=400)


class AboutView(TemplateView):
    template_name = 'core/about.html'


class KiriqView(TemplateView):
    template_name = 'core/products/kiriq.html'


class MonitorView(TemplateView):
    template_name = 'core/products/monitor.html'


class JoolidView(TemplateView):
    template_name = 'core/products/joolid.html'


class MonAgroView(TemplateView):
    template_name = 'core/products/monagro.html'


class PrivacyView(TemplateView):
    template_name = 'core/privacy.html'


class RobotsTxtView(TemplateView):
    template_name = 'robots.txt'
    content_type  = 'text/plain'


class SitemapXmlView(TemplateView):
    template_name = 'sitemap.xml'
    content_type  = 'application/xml'
