from django.shortcuts import render,redirect
from django.conf import settings
import datetime
from django.contrib import messages
from visitors_app.models import website_setting
from visitors_app.context_processors import my_constants
from visitors_app.models import whatsapp_send_message_count
from django.template.loader import render_to_string
from django.db.models import Q
from django.core.mail import  EmailMultiAlternatives,get_connection
from django.utils.html import strip_tags
import socket
from visitors_app.check_subscription import check_subscription

@check_subscription
def admin_setting_update(request):
    constants = my_constants(request)
    username = request.session.get('admin')
    if not username:
        return redirect('admin')

    admin_data = constants.get('admin_data', {})
    user_id = admin_data.get('id')

    # Fetch the first or specific setting (assuming only one exists)

    setting = website_setting.objects.first()

    message_count = whatsapp_send_message_count.objects.get()

    remaining_messages = settings.WHATSAPP_SEND_MESSAGE_COUNT_LIMIT - message_count.count

    if request.method == "POST":
        website_name = request.POST.get('website_name')
        website_link = request.POST.get('website_link')
        copyright = request.POST.get('copyright')
        smtp_host = request.POST.get('smtp_host')
        smtp_user = request.POST.get('smtp_user')
        smtp_password = request.POST.get('smtp_password')
        smtp_ssl = request.POST.get('smtp_ssl')  == 'on'
        smtp_tls = request.POST.get('smtp_tls') == 'on'
        smtp_port = int(request.POST.get('smtp_port', 465))
        w_from_name = request.POST.get('w_from_name')
        w_from_email = request.POST.get('w_from_email')
        whatsapp_notificationes = request.POST.get('whatsapp_notification')
        safety_service_kiosk = request.POST.get('safety_service_kiosk')  # ✅ new field
        company_domain = request.POST.get('website_company_domaines')
        is_gate_pass_template_active = request.POST.get('is_gate_pass_template_active')
        is_safety_video_active = request.POST.get('is_safety_video_active')
        if whatsapp_notificationes == 'on':
            whatsapp_notificationes = 1
        else:
            whatsapp_notificationes = 0

        safety_service_kiosk = 1 if safety_service_kiosk == 'on' else 0
        is_gate_pass_template_active = 1 if is_gate_pass_template_active == 'on' else 0
        is_safety_video_active = 1 if is_safety_video_active == 'on' else 0
        if setting != None:
            # Validate image file
            if 'image' in request.FILES:
                file = request.FILES['image']
                file_extension = file.name.split('.')[-1].lower()
                if file_extension in ['png', 'jpg', 'jpeg']:
                    setting.image = file
                else:
                    messages.error(request, 'Error: Invalid image format. Only PNG, JPG, and JPEG are allowed.',
                                   extra_tags='danger')
                    return redirect('admin_setting_update')

            # Validate favicon file
            if 'favicon' in request.FILES:
                favicon_file = request.FILES['favicon']
                favicon_extension = favicon_file.name.split('.')[-1].lower()
                if favicon_extension != 'ico':
                    messages.error(request, 'Error: Invalid favicon format. Only ICO format is allowed.',
                                   extra_tags='danger')
                    return redirect('admin_setting_update')
                else:
                    setting.favicon = favicon_file  # Update favicon if valid
            now = datetime.datetime.now()
            updated_at = now.strftime("%y-%m-%d %H:%M:%S")
            # Update the fields with new data
            setting.website_name = website_name
            setting.website_link = website_link
            setting.copyright = copyright
            setting.smtp_host = smtp_host
            setting.smtp_user = smtp_user
            setting.smtp_password = smtp_password
            setting.from_name = w_from_name
            setting.from_email = w_from_email
            setting.updated_at = updated_at
            setting.whatsapp_notification = whatsapp_notificationes
            setting.safety_Service_Kiosk = safety_service_kiosk
            setting.is_gate_pass_template_active = is_gate_pass_template_active  # 👈 new
            setting.is_safety_video_active = is_safety_video_active
            setting.company_domain = company_domain
            setting.smtp_tls= smtp_tls
            setting.smtp_ssl = smtp_ssl
            setting.smtp_port= smtp_port
            setting.save()  # Save the updated setting
            setting.save()
            messages.success(request, "Successfully updated setting.")
            return redirect('admin_setting_update')
        else:
            if 'image' in request.FILES:
                file = request.FILES['image']
                file_extension = file.name.split('.')[-1].lower()
                if file_extension in ['png', 'jpg', 'jpeg']:
                    image = file
                else:
                    messages.error(request, 'Error: Invalid image format. Only PNG, JPG, and JPEG are allowed.',
                                   extra_tags='danger')
                    return redirect('admin_setting_update')

            # Validate favicon file
            if 'favicon' in request.FILES:
                favicon_file = request.FILES['favicon']
                favicon_extension = favicon_file.name.split('.')[-1].lower()
                if favicon_extension != 'ico':
                    messages.error(request, 'Error: Invalid favicon format. Only ICO format is allowed.',
                                   extra_tags='danger')
                    return redirect('admin_setting_update')
                else:
                    favicon = favicon_file
            now = datetime.datetime.now()
            created_at = now.strftime("%y-%m-%d %H:%M:%S")
            if whatsapp_notificationes == 'on':
                whatsapp_notificationes = 1
            else:
                whatsapp_notificationes = 0
            user_create = website_setting.objects.create(
                image=image,
                website_name=website_name,
                website_link=website_link,
                copyright=copyright,
                smtp_host=smtp_host,
                smtp_user=smtp_user,
                smtp_password=smtp_password,
                from_name=w_from_name,
                from_email=w_from_email,
                favicon=favicon,
                created_at=created_at,
                whatsapp_notification=whatsapp_notificationes,
                safety_service_kiosk=safety_service_kiosk,
                is_gate_pass_template_active=is_gate_pass_template_active,
                is_safety_video_active=is_safety_video_active,
                company_domain=company_domain

            )
            user_create.save()
            messages.success(request, "Successfully setting created:")
            return redirect('admin_setting_update')
    # Render the update form with the existing setting data
    return render(request, 'dashboard/admin_dashboard/admin_setting/admin_setting_update.html', {
        'setting': setting,
        'message_count': message_count.count,
        'remaining_messages': remaining_messages,
        'total_messages': settings.WHATSAPP_SEND_MESSAGE_COUNT_LIMIT,
        'function_name': 'Admin',
        'username': username
    })

def admin_setting_send_test_email(request):
    if request.method == "POST":
        test_email = request.POST.get('test_email')
        setting = website_setting.objects.first()

        if not test_email:
            messages.error(request, "Please enter a valid email address.")
            return redirect('admin_setting_update')

        if not setting:
            messages.error(request, "SMTP settings are not configured yet.")
            return redirect('admin_setting_update')

        try:
            # Set a 15-second global timeout for all socket (SMTP) operations
            socket.setdefaulttimeout(2)

            subject = f"Test Email from {setting.website_name or 'Your Website'}"
            html_content = render_to_string(
                'dashboard/admin_dashboard/admin_setting/test_email_template.html',
                {'website_name': setting.website_name}
            )
            text_content = strip_tags(html_content)
            connection = get_connection(
                host=setting.smtp_host,
                port=setting.smtp_port,
                username=setting.smtp_user,
                password=setting.smtp_password,
                use_tls=setting.smtp_tls,
                use_ssl=setting.smtp_ssl,
                timeout=5
            )
            email = EmailMultiAlternatives(
                subject,
                text_content,
                setting.from_email,
                [test_email],
                connection=connection
            )
            email.attach_alternative(html_content, "text/html")

            # Try sending the email
            email.send()

            messages.success(request, f"✅ Test email successfully sent to {test_email}",extra_tags='success')

        except socket.timeout:
            messages.error(request, "❌ Email sending timed out. It seems your SMTP details may be incorrect or the server is not responding. Please verify your SMTP configuration and try again.",extra_tags='danger')
        except Exception as e:
            messages.error(request, f"❌ Failed to send test email. Error: {str(e)}",extra_tags='danger')
        finally:
            # Always reset timeout back to default
            socket.setdefaulttimeout(None)

    return redirect('admin_setting_update')