from .models import SystemLog
import requests
from django.conf import settings




def log_system_event(user, action_type, description, request=None):
    ip = None

    if request:
        ip = request.META.get('REMOTE_ADDR')

    SystemLog.objects.create(
        user=user,
        action_type=action_type,
        description=description,
        ip_address=ip
    )
    
    
    

def normalize_phone(phone):
    """
    Convert Ghana numbers to international format (233xxxxxxxxx)
    """
    phone = phone.strip()

    if phone.startswith("0"):
        return "233" + phone[1:]

    if phone.startswith("+233"):
        return phone.replace("+", "")

    return phone


def send_sms(phone_numbers, message, sms_type=None):
    """
    phone_numbers: list of phone numbers
    sms_type: only use 'otp' for OTP messages
    """

    normalized_numbers = [normalize_phone(p) for p in phone_numbers]
    apiKey='DZPrpHnQfZMopCEadrdyezHfF'

    url = f"{settings.MNOTIFY_ENDPOINT}?key={apiKey}"

    data = {
        "recipient": normalized_numbers,
        "sender": settings.MNOTIFY_SENDER_ID,
        "message": message,
        "is_schedule": False,
        "schedule_date": ""
    }

   
    try:
        response = requests.post(url, json=data, timeout=30)
        result = response.json()
        
        print(result)
        
        return result

    except requests.exceptions.RequestException as e:
        print('sms notification is not sent')
        print(e)
        return {"status": "error", "message": str(e)}

# def send_sms(phone_numbers, message, sms_type=None):
#     endPoint = 'https://api.mnotify.com/api/sms/quick'
#     apiKey = settings.MNOTIFY_SENDER_ID
#     url = endPoint + '?key=' + apiKey
    
#     data = {
#       "recipient": ["0545079851", "0507560647"],
#       "sender": "mNotify",
#       "message": "API messaging is fun!",
#       "is_schedule": False,
#       "schedule_date": "",
#     # uncomment the below line to send OTP sms
#     # When sms_type: "otp" is included in your payload, a charge of 0.035 per campaign will be deducted from your main wallet.
#     # "sms_type": "otp" please do not include in payload when the purpose of the blast is not for otp
#     }
    
#     response = requests.post(url, json=data)
#     print(response.json())


# def send_sms(phone_numbers, message, sms_type=None):
#     """
#     phone_numbers: list of numbers
#     sms_type: use "otp" only for OTP messages
#     """

#     url = f"{settings.MNOTIFY_API_URL}?key={settings.MNOTIFY_API_KEY}"

#     payload = {
#         "recipient": phone_numbers,
#         "sender": settings.MNOTIFY_SENDER_ID,
#         "message": message,
#         "is_schedule": False,
#         "schedule_date": ""
#     }

    # # Only include sms_type if it is OTP
    # if sms_type == "otp":
    #     payload["sms_type"] = "otp"

    # try:
    #     response = requests.post(url, json=payload)
    #     result = response.json()

    #     # Log SMS
    #     SMSLog.objects.create(
    #         phone=",".join(phone_numbers),
    #         message=message,
    #         response=str(result),
    #         status=result.get("status", "unknown")
    #     )

    #     return result

    # except Exception as e:
    #     SMSLog.objects.create(
    #         phone=",".join(phone_numbers),
    #         message=message,
    #         response=str(e),
    #         status="error"
    #     )
    #     return {"status": "error", "message": str(e)}