import requests
from .models import Airtime, Config
from base64 import b64encode
from datetime import datetime
import random
import uuid
import json






# AIRTIME

 # VTpass function


def airtime_vtpass(network, amount, 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()
    # vtpass_key = table.vtpass_api_key.encode()
    # vtpass_api_key = b64encode(vtpass_key).decode()


    net = network.lower()
    url = "https://api-service.vtpass.com/api/pay"
    parameters = {
        "request_id": request_id,
        "serviceID": net,
        "amount": amount,
        "phone": phone,
    }
    # headers = {
    #     "Authorization": f"Basic {vtpass_api_key}",
    #     "Content-Type": "application/json",
    # }
    headers = {
          'Content-Type':'application/json',
          "api-key": "37cbf73ed25cf7eadcc90868ad9ca279",
          "secret-key": "SK_871c545f322d2689c0d02f660e462715ed36771474f",
         }

    try:
            responses = requests.post(url, headers=headers, json=parameters)
            response = responses.json()
            # print(response)
            if response:
                description = response["response_description"]
                code = response["code"]
                if code == "000":
                    result = [f"{description}", "Successful", request_id]
                    return result
                elif code == "099" or code == "044":
                    result = [f"{description}", "Pending", request_id]
                    return result
                
                else:
                    result = [f"{description}", "Unsuccessful", request_id]
                    return result
            else:
                result = [(
                    f"Pending, dear customer, your transaction is pending, you can confirm if the "
                    f"service has being delivered or contact admin"), "Pending", request_id]
                return result
    except:
        
        result = [f"Dear customer, an error occured while processing this transaction", "Pending", request_id]
        return result
        
        
# Merrybills function


def airtime_merrybills(network, amount, 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()
    table = Config.objects.get(pk=1)
    merrykey = table.merrybills_api_key
    

    if network == "MTN":
        pid = "BHMilhAzT2"
    elif network == "GLO":
        pid = "vogjcmKJZi"
    elif network == "AIRTEL":
        pid = "KRUGi4uM1r"
    elif network == "ETISALAT":
        pid = "mIMZeHKoQx"
    url = "https://merrybills.com/api/v2/airtime"
    parameters = {
        "request_id": request_id,
        "phone": phone,
        "product_id": pid,
        "amount": amount,
        "pin": "4734",
    }
    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Authorization": f"Bearer {merrykey}",
    }

    responses = requests.post(url, headers=headers, json=parameters)
    response = responses.json()
    print(response)
    if response:
        if 'data' in response:
            status = response["data"]["transaction"]["status"]
        else:
            status = "processing"
        if status == "completed":
            description = response["data"]["transaction"]["details"]
            result = [f"Successful {network} Airtime  {description}", "Successful", request_id]
            return result
        elif status == "processing":
            result = [f" Oops {network} Airtime Pending", "Pending", request_id]
            return result

        elif status == "refund":
            result = [f" Oops {network} Airtime  Transaction Unsuccessful", "Unsuccessful", request_id]
            return result

        else:
            result = [f" Oops {network} Airtime  Transaction Unsuccessful", "Unsuccessful", request_id]
            return result
    else:
        result = [(
            f"Pending, dear customer, your transaction is pending, you can confirm if the "
            f"service has being delivered or contact admin"), "Pending", request_id]
        return result



def airtime_autopilot(network, amount, 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
    
    if network == "MTN":
        pid = "1"
    elif network == "GLO":
        pid = "3"
    elif network == "AIRTEL":
        pid = "2"
    elif network == "ETISALAT":
        pid = "4"
    
    url = "https://autopilotng.com/api/live/v1/airtime"
    payload = {
        "networkId": pid,
        "airtimeType": "VTU",
        "amount": amount,
        "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 = "Transaction 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 airtime_apisub(network, amount, 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()
    table = Config.objects.get(pk=1)
    apisubportal_key = table.apisubportal_key
    

    url = "https://apisubportal.com/api/buyvtu.php"
    parameters = {
        "api_key": apisubportal_key,
        "network": network,
        "return_url": "korabills.com",
        "amount": amount,
        "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":
        result = [f"Successful {network}  Airtime", "Successful", request_id]
        return result

    elif res == "Unsuccessful":
        result = [f" Oops Unsuccessful {network} Airtime", "Unsuccessful", request_id]
        return result

    else:
        result = [f" Oops Unsuccessful {network} Airtime", "Unsuccessful", request_id]
        return result


def airtime_ogdams(network, amount, 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)
    ogdams_key = table.ogdams_key
    
    
    if network == "MTN":
        pid = "1"
    elif network == "GLO":
        pid = "3"
    elif network == "AIRTEL":
        pid = "2"
    elif network == "ETISALAT":
        pid = "4"
    
    url = "https://simhoster.com/api/v1/vend/airtime.php"

    payload = json.dumps({
        "networkId": pid,
        "amount": int(amount),
        "phoneNumber": phone,
        "type": "vtu",
        "reference": request_id
    })
    print(payload)
    headers = {
        "Authorization": f"Bearer {ogdams_key}",
        "Accept": "application/json",
        "Content-Type": "application/json",
    }
    print(headers)
    
    try:
        responses = requests.post(url, headers=headers, data=payload,verify=False)
        # print(responses.text)
        response = responses.json()
        if 'code' in response:
            stat = response['code']
            if stat == 200 or stat == 201 or stat == 202:
                status = 'successful'
                if 'data' in response:
                    api = "Transaction Successful"
                    # api = response['data']['msg']
                else:
                    api = 'Transaction Successful'
            
            else:
                status = 'failed'
                if 'data' in response:
                    api = response['data']['msg']
                else:
                    api = 'Transaction failed'
        else:
            status = 'processing'
            api = 'processing'
    except:
        status = 'failed'
        api = "Transaction Failed"

    if status == "successful":
        result = [f"{network} Airtime  {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 airtime_atuns(network, amount, 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()

    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/airtime/"
    parameters = {
        "network": network,
        "mobile_number": phone,
        "amount": amount,
    }
    headers = {
        "Authorization": f"Token {Atuns_web_api_key}",
        "Content-Type": "application/json",
    }
    try:
        responses = requests.post(url, headers=headers, json=parameters)
        response = responses.json()
    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 == "Successful":
        description = response["message"]
        result = [description, "Successful", request_id]
        return result
    elif res == "Pending":
        description = response["message"]
        result = [description, "Pending", request_id]
        return result
    elif res == "Unsuccessful":
        description = response["message"]
        result = [description, "Unsuccessful", request_id]
        return result
    else:
        result = ["Transaction unsuccessful", "Unsuccessful", request_id]
        return result

def airtime_ringo(network, amount, 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)
    email = table.ringo_email
    password = table.ringo_password
    
    
    
    if network == "MTN":
        pid = "MFIN-5-OR"
    elif network == "GLO":
        pid = "MFIN-6-OR"
    elif network == "AIRTEL":
        pid = "MFIN-1-OR"
    elif network == "ETISALAT":
        pid = "MFIN-2-OR"
    
    url = "https://www.api.ringo.ng/api/agent/p2"
    # url = "https://messaging.approot.ng/ringo-api/index.php"
    payload = {
        "serviceCode": "VAR",
        "product_id": pid,
        "amount": amount,
        "msisdn": phone,
        "request_id": request_id
    }

    headers = {
        "Content-Type": "application/json",
        "email": email,
        "password": password,
        # "email": 'davinciss@gmail.com',
        # "password": 'davinci',


    }
    try:
        responses = requests.post(url, headers=headers, json=payload)
        response = responses.json()
        print(response)
        if 'status' in response:
            stat = response['status']
            if stat == '200':
                status = 'successful'
                # api = "Transaction Successful"
                api = response['message']
            elif stat == '201':
                status = 'processing'
                api = response['message']
            else:
                status = 'failed'
                api = response['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



