import requests
from requests.auth import HTTPBasicAuth
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.core.exceptions import ObjectDoesNotExist
from django.conf import settings
def whatsapps_send_notifications(request,employee_mobile,employee_name,visitor_name,accept_url,reject_url,purpose_of_visit,company_name,company_location,check_in_date,check_in_time,company_website,visitor_mobile, invitation_link):
    try:
        
        message_count = whatsapp_send_message_count.objects.first()
        if not message_count:
            message_count = whatsapp_send_message_count.objects.create(
                count=0,
                created_at=date_time(),
                updated_at=date_time()
            )
        # 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
        try:
            # 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.")
        except ObjectDoesNotExist:
            # Handle the case where the message_count object does not exist
            messages.error(request, "Error: Message count record not found.", extra_tags="danger") 
            return
        url = "https://us-central1-pristine-nomad-264707.cloudfunctions.net/SendTemplateWhatsappV2"
        headers = {
                "Content-Type": "application/json"
            }
        # ---------------------------
        # 1. Send Notification to Employee
        # ---------------------------
        if employee_mobile != "":
            payload = {
                "FromMobileNo": "918200599525",
                "FBToken": "EAB8uAArmndABO4ewJWGktpcbuBfZAiFV6XUIOYdEr9FR8L05gprGxlb1Sx9DNFwY9q1A8f3NcZAcs4b7DhE9nZBT5ZACPLxNIL3J0vTNHpvuam7zfrsHcwYilrmVybIowxY7xWapORJIUoPMcqWykvnFjgsnBqvZBURIzKEkUMZAfdPlQJdQ0b6W63W2sBgJ6i",
                "toMobileNo": employee_mobile,
                "TemplateName": "visitor_request_accpet_rejact_url_emp",
             
                "TemplateLanguage": "en",
                           "Variables": [
                    {"Variable": employee_name},
                    {"Variable": visitor_name},
                    {"Variable": company_location},                
                    {"Variable": purpose_of_visit},
                    {"Variable": check_in_date},
                    {"Variable": check_in_time},
                    {"Variable": accept_url},
                    {"Variable": reject_url},
                    {"Variable": company_name},
                    {"Variable": company_website},
                    
                ]
            }
            
            
            
            response = requests.post(url, data=json.dumps(payload), headers=headers)
            
            if response.status_code == 200:
               
                response_data = response.json()  # Parse the JSON response
                
                # Check if `status` key exists and its value is 1
                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 to employee.", 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")

        # ---------------------------
        # 2. Send Invitation to Visitor
        # ---------------------------
        
        if visitor_mobile != "":
            message_count = whatsapp_send_message_count.objects.first()
            if not message_count:
                message_count = whatsapp_send_message_count.objects.create(
                    count=0,
                    created_at=date_time(),
                    updated_at=date_time()
                )
            # 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
            try:
                # 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.")
            except ObjectDoesNotExist:
                # Handle the case where the message_count object does not exist
                messages.error(request, "Error: Message count record not found.", extra_tags="danger") 
                return
            visitor_payload = {
                "FromMobileNo": "918200599525",
                "FBToken": "EAB8uAArmndABO4ewJWGktpcbuBfZAiFV6XUIOYdEr9FR8L05gprGxlb1Sx9DNFwY9q1A8f3NcZAcs4b7DhE9nZBT5ZACPLxNIL3J0vTNHpvuam7zfrsHcwYilrmVybIowxY7xWapORJIUoPMcqWykvnFjgsnBqvZBURIzKEkUMZAfdPlQJdQ0b6W63W2sBgJ6i",
                "toMobileNo": visitor_mobile,
                "TemplateName": "visitor_invitation",
                "TemplateLanguage": "en",
                "EmployeeName": employee_name,
                "Variables": [
                    {"Variable": visitor_name},
                    {"Variable": employee_name},
                    {"Variable": company_name},
                    {"Variable": invitation_link},
                    {"Variable": company_name},
                    {"Variable": company_website}
                ],
                "HeaderPath": None
            }
            visitor_response = requests.post(url, data=json.dumps(visitor_payload), headers=headers)
            visitor_data = visitor_response.json()

            if visitor_response.status_code == 200 and visitor_data.get('status') == 1:
                message_count.count += 1
                message_count.updated_at = date_time()
                message_count.save()
                messages.success(request, "Visitor invitation successfully sent.", extra_tags="success")
            else:
                messages.error(request, f"Failed to send visitor invitation: {visitor_data}", extra_tags="danger")
        
    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}")
        messages.error(request, f"Error_101: {e}", extra_tags="danger")