import requests
import json
from visitors_app.views import date_time
from visitors_app.models import whatsapp_send_message_count
from django.contrib import messages
from django.conf import settings

def send_whatsapp_notification(request, to_mobile, template_name,employee_name, visitor_name, company_name, company_location, company_domain, check_in_date, check_in_time, Purpose_of_Visit=None):
    try:

	# Check the current count of messages in the database
        message_count = whatsapp_send_message_count.objects.get()
        
        # Check if the limit of 1000 is reached
        if message_count.count >= settings.WHATSAPP_SEND_MESSAGE_COUNT_LIMIT:
            messages.error(request, "You have reached your message limit. Please contact support for assistance.", extra_tags="danger")
            return
        
        # Show warning when count is between 990 and 999
        if settings.WHATSAPP_LIMIT_EXCEEDED_WARNING <= message_count.count < settings.WHATSAPP_SEND_MESSAGE_COUNT_LIMIT:
            remaining_messages = settings.WHATSAPP_SEND_MESSAGE_COUNT_LIMIT - message_count.count
            messages.warning(request, f"Warning: Only {remaining_messages} message(s) left before the limit is reached.", extra_tags="warning")
        
        url = "https://us-central1-pristine-nomad-264707.cloudfunctions.net/SendTemplateWhatsappV2"

        # Common payload structure
        payload = {
            "FromMobileNo": "918200599525",
            "FBToken": "EAB8uAArmndABO4ewJWGktpcbuBfZAiFV6XUIOYdEr9FR8L05gprGxlb1Sx9DNFwY9q1A8f3NcZAcs4b7DhE9nZBT5ZACPLxNIL3J0vTNHpvuam7zfrsHcwYilrmVybIowxY7xWapORJIUoPMcqWykvnFjgsnBqvZBURIzKEkUMZAfdPlQJdQ0b6W63W2sBgJ6i",
            "toMobileNo": to_mobile,
            "TemplateName": template_name,
            "TemplateLanguage": "en",
            "EmployeeName": "Suhag Patel"
        }

        # Define template-specific variables
        if template_name == 'message_1_visitor_welcome_message_upon_checkin':
            payload["Variables"] = [
                {"Variable": company_name},
                {"Variable": visitor_name},
                {"Variable": check_in_date},
                {"Variable": check_in_time},                
                {"Variable": employee_name},
                {"Variable": company_location},
                {"Variable": company_name},
                {"Variable": company_domain},
            ]
        elif template_name == 'message_2_notification_to_employee_visitor_checkin':
            payload["Variables"] = [
                {"Variable": employee_name},
                {"Variable": visitor_name},
                {"Variable": company_location},
                {"Variable": check_in_date},
                {"Variable": check_in_time},
                {"Variable": Purpose_of_Visit},
                {"Variable": company_name},
                {"Variable": company_domain}
            ]
        elif template_name == 'message_3_visitor_farewell_message_upon_checkout':
            payload["Variables"] = [
                {"Variable": company_name},
                {"Variable": visitor_name},
                {"Variable": check_in_date},
                {"Variable": check_in_time},                
                {"Variable": company_location},
                {"Variable": company_name},
                {"Variable": company_domain}
            ]
        elif template_name =='message_4_notification_to_employee_visitor_checkout':
            payload["Variables"] = [
                {"Variable": employee_name},                
                {"Variable": visitor_name},
                {"Variable": company_location},
                {"Variable": check_in_date},
                {"Variable": check_in_time},   
                {"Variable": company_name},           
                {"Variable": company_domain},
            ]
        else:
            return {"error": "Invalid template name"}

        headers = {"Content-Type": "application/json"}


        response = requests.post(url, data=json.dumps(payload), headers=headers)


        if response.status_code == 200:
            response_data = response.json()
            if response_data.get('status') == 1:
                message_count.count += 1
                message_count.updated_at = date_time()
                message_count.save()
                messages.success(request, "Appointment message successfully sent.", extra_tags="success")
            else:
                messages.error(request, f"Appointment message failed. Response: {response_data}", extra_tags="danger")
        else:
            messages.error(request, "Appointment message not sent.", extra_tags="danger")
    except requests.exceptions.RequestException as e:

        messages.error(request, f"Error_101: {e}", extra_tags="danger")
