import requests
from .models import Giftinglitedata, Config, mailer
import random
from datetime import datetime
import uuid
import json




# MTN CORPORATE GIFTING_______


def manual_giftinglite(network, plan, phone):
    def request_id():
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        num = random.randint(10000000, 99999999)
        random_num = str(num)
        request_idd = the_date + random_num
        return request_idd

    request_id = request_id()

    try:

        table = Config.objects.get(pk=1)
        email = table.admin_mail

        mailer(email, f'{network} MANUAL',
               f'Dear Admin, sell {plan.volume} {network} on {phone}.')
        result = [f"Successful {plan.volume} {network} on {phone}. The activation of {plan.volume} {network} was successful.", "Successful", request_id]
        return result
    except:
        result = [f" Oops Transaction Unsuccessful", "Unsuccessful", request_id]
        return result


def plan_code(network, plan, phone):
    
    sell = globals()[plan.vending_medium](network, plan, phone)
    
    return sell




def autopilot_giftinglite(network, plan, phone):
    def request_id_gen():
        # Request ID generator
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        tok = uuid.uuid4()
        token = tok.hex
        req = the_date + token
        request_id = req[0:25]
        return request_id

    request_id = request_id_gen()

    table = Config.objects.get(pk=1)
    autopilot_key = table.autopilot_key

    url = "https://autopilotng.com/api/live/v1/data"
    payload = {
        "networkId": "1",
        "dataType": "CORPORATE GIFTING LITE",
        "planId": plan.autopilot_id,
        "phone": phone,
        "reference": request_id
    }

    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Authorization": f"Bearer {autopilot_key}",

    }
    try:
        responses = requests.post(url, headers=headers, json=payload)
        response = responses.json()
        if 'code' in response:
            stat = response['code']
            if stat == 200:
                status = 'successful'
                api = response['data']['message']
            elif stat == 201:
                status = 'processing'
                api = response['data']['message']
            else:
                status = 'failed'
                api = response['data']['message']
        else:
            status = 'processing'
            api = 'processing'
    except:
        status = 'failed'
        api = "Transaction Failed"

    if status == "successful":
        result = [f"Successful {network}  {api}", "Successful", request_id]
        return result
    elif status == "processing":
        result = [f"Pending, {network}  {api}", "Pending", request_id]
        return result
    elif status == "failed":
        result = [f" Oops Unsuccessful {network},  {api}", "Unsuccessful", request_id]
        return result
    else:
        result = ["Transaction unsuccessful", "Unsuccessful", request_id]
        return result





def ms_giftinglite(network, plan, phone):
    def request_id_gen():
        # Request ID generator
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        tok = uuid.uuid4()
        token = tok.hex
        req = the_date + token
        request_id = req[0:25]
        return request_id

    request_id = request_id_gen()

    table = Config.objects.get(pk=1)
    ms_url = table.ms_url
    ms_api_key = table.ms_api_key

    url = f"{ms_url}/api/data/"
    payload = {
        "network": "1",
        "plan": plan.ms_id,
        "mobile_number": phone,
        "Ported_number":True
    }

    headers = {
        'Content-Type':'application/json',
        'Authorization': f'Token {ms_api_key}'
    }
  
    try:
        responses = requests.post(url, headers=headers, json=payload)
        response = responses.json()
        
        if responses.status_code == 200 or responses.status_code == 201:
            if "Status" in response and response["Status"]  == "successful" :
                status = 'successful'
                if "api_response" in response:
                    api = response["api_response"]
                else:
                    api = "Transaction successful"
            elif "Status" in response and response["Status"]  == "processing":
                status = 'processing'
                api = 'Transaction processing'
            else:
                status = 'failed'
                api = "Transaction Failed"
        else:
            status = 'failed'
            api = "Transaction Failed"
    except:
        status = 'failed'
        api = "Transaction Failed"
        
        
    if status == "successful":
        result = [f"Successful {network}  {api}", "Successful", request_id]
        return result
    elif status == "processing":
        result = [f"Pending, {network}  {api}", "Pending", request_id]
        return result
    elif status == "failed":
        result = [f" Oops Unsuccessful {network},  {api}", "Unsuccessful", request_id]
        return result
    else:
        result = ["Transaction unsuccessful", "Unsuccessful", request_id]
        return result
                
        
# def apisub_giftinglite(network, plan, phone):
#     def request_id():
#         date_time = datetime.now()
#         the_date = date_time.strftime("%Y%m%d%H%M")
#         num = random.randint(10000000, 99999999)
#         random_num = str(num)
#         request_idd = the_date + random_num
#         return request_idd

#     request_id = request_id()

#     url = "https://apisubportal.com/api/buydata.php"
#     parameters = {
#         "api_key": apisubportal_key,
#         "network": 'MTN_CGD',
#         "return_url": "yarabpro.com",
#         "plans": plan.apisubportal_plan_id,
#         "phonenumber": phone,
#     }

#     try:
#         responses = requests.get(url, params=parameters)
#         response = json.loads(responses.text)
#     except:
#         result = [(
#             f"Pending, dear customer, your transaction is pending, you can confirm if "
#             f"the service has being delivered or contact admin"), "Pending", request_id]
#         return result

#     res = response["status"]

#     if res == "success":
#         description = response["msg"]
#         result = [f"Successful {network}  {description}", "Successful", request_id]
#         return result

#     elif res == "unsuccessful":
#         description = response["msg"]
#         result = [f" Oops  {network} {description}", "Unsuccessful", request_id]
#         return result

#     else:
#         result = [(
#             f"Pending, dear customer, your transaction is pending, you can confirm if "
#             f"the service has being delivered or contact admin"), "Pending", request_id]
#         return result


def cloudsim_giftinglite(network, plan, phone):
    def request_id_gen():
        # Request ID generator
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        tok = uuid.uuid4()
        token = tok.hex
        req = the_date + token
        request_id = req[0:25]
        return request_id

    request_id = request_id_gen()

    table = Config.objects.get(pk=1)
    cloudsimhost_key = table.cloudsimhost_key
    
    url = "https://www.cloudsimhost.com/api/buy-data/"
    payload = {
        "plan": plan.cloudsim_plan_id,
        "phone": phone,
        "customer_ref": request_id,
        "webhook_url": "https://korabills.com/cloudsim_webhook/"
    }


    headers = {
        'Content-Type': 'application/json',
            'Authorization': f'Token {cloudsimhost_key}',}
  
    try:
        response = requests.post(url, headers=headers, json=payload)
        
        
        if response.status_code == 200 or response.status_code == 201:
            result = json.loads(response.text)
            if "data" in result and "success" in result["data"] and result["data"]["success"] == True:

                if "status" in result["data"] and result["data"]["status"] == "success":
                    status = 'successful'
                    api = result["data"]["msg"]
                    
                elif "status" in result["data"] and result["data"]["status"] == "pending":
                    status = 'processing'
                    api = result["data"]["msg"]
                    
                else:
                    status = 'failed'
                    api = "Transaction Failed"
                
            
            else:
                status = 'failed'
                api = "Transaction Failed"
        else:
            status = 'failed'
            api = "Transaction Failed"
    except:
        status = 'failed'
        api = "Transaction Failed"
        
        
    if status == "successful":
        result = [f"Successful {network}  {api}", "Successful", request_id]
        return result
    elif status == "processing":
        result = [f"Pending, {network}  {api}", "Pending", request_id]
        return result
    elif status == "failed":
        result = [f" Oops Unsuccessful {network},  {api}", "Unsuccessful", request_id]
        return result
    else:
        result = ["Transaction unsuccessful", "Unsuccessful", request_id]
        return result



def simserverslot_giftinglite(network, plan, phone):
    def request_id_gen():
        # Request ID generator
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        tok = uuid.uuid4()
        token = tok.hex
        req = the_date + token
        request_id = req[0:25]
        return request_id

    request_id = request_id_gen()

    table = Config.objects.get(pk=1)
    sim_url = table.simserver_web_url
    sim_key = table.simserver_web_key

    url = f"{sim_url}/api/v2/datashare/"
    payload = {
        "api_key": sim_key,
        "product_code": plan.simserver_web_id,
        "phone": phone,
        "callback":"cheapdatasales.com/callback.php"
    }
    
   
    try:
        responses = requests.post(url, json=payload)
        response = responses.json()
        
        if responses.status_code == 200 or responses.status_code == 201:
            if "text_status" in response and response["text_status"]  == "COMPLETED" :
                status = 'successful'
                if "data" in response and "true_response" in response["data"]:
                    api = response["data"]["true_response"]
                else:
                    api = "Transaction successful"
            elif "text_status" in response and response["text_status"]  == "FAILED":
                status = 'failed'
                api = "Transaction Failed"
            else:
                status = 'processing'
                api = 'Transaction processing'
                
        else:
            status = 'failed'
            api = "Transaction Failed"
    except:
        status = 'failed'
        api = "Transaction Failed"
        
        
    if status == "successful":
        result = [f"Successful {network}  {api}", "Successful", request_id]
        return result
    elif status == "processing":
        result = [f"Pending, {network}  {api}", "Pending", request_id]
        return result
    elif status == "failed":
        result = [f" Oops Unsuccessful {network},  {api}", "Unsuccessful", request_id]
        return result
    else:
        result = ["Transaction unsuccessful", "Unsuccessful", request_id]
        return result



def atuns_giftinglite(network, plan, phone):
    def request_id_gen():
        # Request ID generator
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        tok = uuid.uuid4()
        token = tok.hex
        req = the_date + token
        request_id = req[0:25]
        return request_id

    request_id = request_id_gen()

    table = Config.objects.get(pk=1)
    Atuns_web_api_key = table.Atuns_web_api_key
    Atuns_web_url = table.Atuns_web_url

    url = f"{Atuns_web_url}/api/data/"
    payload = {
        "network": "1",
        "plan": plan.Atuns_web_id,
        "mobile_number": phone,
        "Ported_number":True
    }

    headers = {
        'Content-Type':'application/json',
        'Authorization': f'Token {Atuns_web_api_key}'
    }
  
    try:
        responses = requests.post(url, headers=headers, json=payload)
        response = responses.json()
        
        if responses.status_code == 200 or responses.status_code == 201:
            if "Status" in response and response["Status"]  == "successful" :
                status = 'successful'
                if "api_response" in response:
                    api = response["api_response"]
                else:
                    api = "Transaction successful"
            elif "Status" in response and response["Status"]  == "processing":
                status = 'processing'
                api = 'Transaction processing'
            else:
                status = 'failed'
                api = "Transaction Failed"
        else:
            status = 'failed'
            api = "Transaction Failed"
    except:
        status = 'failed'
        api = "Transaction Failed"
        
        
    if status == "successful":
        result = [f"Successful {network}  {api}", "Successful", request_id]
        return result
    elif status == "processing":
        result = [f"Pending, {network}  {api}", "Pending", request_id]
        return result
    elif status == "failed":
        result = [f" Oops Unsuccessful {network},  {api}", "Unsuccessful", request_id]
        return result
    else:
        result = ["Transaction unsuccessful", "Unsuccessful", request_id]
        return result



def simserverslot2_giftinglite(network, plan, phone):
    def request_id_gen():
        # Request ID generator
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        tok = uuid.uuid4()
        token = tok.hex
        req = the_date + token
        request_id = req[0:25]
        return request_id

    request_id = request_id_gen()

    table = Config.objects.get(pk=1)

    url = f"{table.simserver_web_url_2}/api/v2/datashare/"
    payload = {
        "api_key": table.simserver_web_key_2,
        "product_code": plan.simserver_web_id_2,
        "phone": phone,
        "callback":"justpayng.com/callback.php"
    }
    
   
    try:
        responses = requests.post(url, json=payload)
        response = responses.json()
        
        if responses.status_code == 200 or responses.status_code == 201:
            if "text_status" in response and response["text_status"]  == "COMPLETED" :
                status = 'successful'
                if "data" in response and "true_response" in response["data"]:
                    api = response["data"]["true_response"]
                else:
                    api = "Transaction successful"
            elif "text_status" in response and response["text_status"]  == "FAILED":
                status = 'failed'
                api = "Transaction Failed"
            else:
                status = 'processing'
                api = 'Transaction processing'
                
        else:
            status = 'failed'
            api = "Transaction Failed"
    except:
        status = 'failed'
        api = "Transaction Failed"
        
        
    if status == "successful":
        result = [f"Successful {network}  {api}", "Successful", request_id]
        return result
    elif status == "processing":
        result = [f"Pending, {network}  {api}", "Pending", request_id]
        return result
    elif status == "failed":
        result = [f" Oops Unsuccessful {network},  {api}", "Unsuccessful", request_id]
        return result
    else:
        result = ["Transaction unsuccessful", "Unsuccessful", request_id]
        return result


def simserverslot3_giftinglite(network, plan, phone):
    def request_id_gen():
        # Request ID generator
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        tok = uuid.uuid4()
        token = tok.hex
        req = the_date + token
        request_id = req[0:25]
        return request_id

    request_id = request_id_gen()

    table = Config.objects.get(pk=1)

    url = f"{table.simserver_web_url_3}/api/v2/datashare/"
    payload = {
        "api_key": table.simserver_web_key_3,
        "product_code": plan.simserver_web_id_3,
        "phone": phone,
        "callback":"cheapdatasales.com/callback.php"
    }
    
    try:
        responses = requests.post(url, json=payload)
        response = responses.json()
        
        if responses.status_code == 200 or responses.status_code == 201:
            if "text_status" in response and response["text_status"]  == "COMPLETED" :
                status = 'successful'
                if "data" in response and "true_response" in response["data"]:
                    api = response["data"]["true_response"]
                else:
                    api = "Transaction successful"
            elif "text_status" in response and response["text_status"]  == "FAILED":
                status = 'failed'
                api = "Transaction Failed"
            else:
                status = 'processing'
                api = 'Transaction processing'
                
        else:
            status = 'failed'
            api = "Transaction Failed"
    except:
        status = 'failed'
        api = "Transaction Failed"
        
        
    if status == "successful":
        result = [f"Successful {network}  {api}", "Successful", request_id]
        return result
    elif status == "processing":
        result = [f"Pending, {network}  {api}", "Pending", request_id]
        return result
    elif status == "failed":
        result = [f" Oops Unsuccessful {network},  {api}", "Unsuccessful", request_id]
        return result
    else:
        result = ["Transaction unsuccessful", "Unsuccessful", request_id]
        return result



def ms2_giftinglite(network, plan, phone):
    def request_id_gen():
        # Request ID generator
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        tok = uuid.uuid4()
        token = tok.hex
        req = the_date + token
        request_id = req[0:25]
        return request_id

    request_id = request_id_gen()

    table = Config.objects.get(pk=1)

    url = f"{table.ms_url_2}/api/data/"
    payload = {
        "network": "1",
        "plan": plan.ms_id_2,
        "mobile_number": phone,
        "Ported_number":True
    }

    headers = {
        'Content-Type':'application/json',
        'Authorization': f'Token {table.ms_api_key_2}'
    }
  
    try:
        responses = requests.post(url, headers=headers, json=payload)
        response = responses.json()
        
        if responses.status_code == 200 or responses.status_code == 201:
            if "Status" in response and response["Status"]  == "successful" :
                status = 'successful'
                if "api_response" in response:
                    api = response["api_response"]
                else:
                    api = "Transaction successful"
            elif "Status" in response and response["Status"]  == "processing":
                status = 'processing'
                api = 'Transaction processing'
            else:
                status = 'failed'
                api = "Transaction Failed"
        else:
            status = 'failed'
            api = "Transaction Failed"
    except:
        status = 'failed'
        api = "Transaction Failed"
        
        
    if status == "successful":
        result = [f"Successful {network}  {api}", "Successful", request_id]
        return result
    elif status == "processing":
        result = [f"Pending, {network}  {api}", "Pending", request_id]
        return result
    elif status == "failed":
        result = [f" Oops Unsuccessful {network},  {api}", "Unsuccessful", request_id]
        return result
    else:
        result = ["Transaction unsuccessful", "Unsuccessful", request_id]
        return result
  





