import json
from datetime import datetime, date
from . import mtn_sme, mtn_gifting, glo, glo_cg, airtel, airtel_cg, mobile, mobile_sme, dstv,gotv,startimes,airtime,electricity, result, mtn_coupon, mtn_datashare, mtn_directgifting, airtel_awoof, mtn_awoofgifting, mtn_giftinglite,glo_awoof,glo_talkmore,mtn_talkmore,airtel_talkmore
from .models import *
from .models import *
from base64 import b64encode
from django.http import HttpResponse
import requests
from .atuns import zone
from django.db import transaction
from django.core.cache import cache




def black(num):
    try:
        Blacklist.objects.get(number=num)
        return True
    except:
        return False



def series_vendor(s_medium):
    # Cache the mediums list (performance)
    mediums = cache.get(s_medium)
    if not mediums:
        mediums = list(
            Series_vending_medium.objects.only('id', s_medium).order_by('id')
        )
        cache.set(s_medium, mediums, timeout=60)

    if not mediums:
        return False

    # DB counter (atomic + concurrency safe)
    with transaction.atomic():
        counter, _ = VendorCounter.objects.select_for_update().get_or_create(
            name=s_medium
        )

        index = counter.value % len(mediums)
        medium = mediums[index]
        vendor = getattr(medium, s_medium)
        # vendor = medium.mtn_medium

        # increment for next request
        counter.value += 1
        counter.save()

    return vendor


def fetch_vendor(model_name,present_medium,s_medium,plan):
    provider_source = present_medium
    if present_medium ==  "SERIES_VENDING":
        vendor = series_vendor(s_medium)
        if vendor is not False:
            provider_source = vendor
        else:
            provider_source = present_medium
    elif present_medium ==  "plan_code":
        model_class = globals().get(model_name)
        plan = model_class.objects.get(volume=plan)
        
        if plan.vending_medium == "SERIES_VENDING":
            vendor = series_vendor(s_medium)
            if vendor is not False:
                provider_source = vendor
            else:
                provider_source = present_medium
        else:        
            provider_source = plan.vending_medium
    else:
        provider_source = present_medium
        
    return provider_source




def debiting_system(user, plan, bucket, bucket_bal, bucket_refund, network, phone,source):
    if bucket_bal:
        if plan.volume[-2] == "M":
            b = plan.volume.strip("MB")
            a = float(b) / 1000
        else:
            c = plan.volume.strip("GB")
            a = float(c)
        if a > bucket_bal:
            pass
        else:
            worker = BucketTransact.objects.create(
            email=user.email,
            user=user,
            transaction="Transaction Processing...",
            status="Pending",
            cost=a,
            old_balance=bucket_bal,
            new_balance=bucket_bal-a,
            phone_number=phone,
            d_network=network,
        )
            bucket(user.id, a)
            return bucket_bal, bucket_bal-a, a, bucket_refund, worker

    bal = user.balance
    if user.category == "EARNER":
        price = plan.amount
    elif user.category == "AFFILIATE":
        price = plan.amount2
    elif user.category == "AMBASSADOR":
        price = plan.amount3
    elif user.category == "API1":
        price = plan.api1
    elif user.category == "API2":
        price = plan.api2
    elif user.category == "API3":
        price = plan.api3
    else:
        price = plan.amount

    if bal < price or price < 0:
        return False
    elif bal > price or bal == price:
        new_bal = bal - price
        with transaction.atomic():
            check = user.debit(user.id, price)
            if check == False:
                return False
            else:
                Wallet_summary.objects.create(user= user, product=f"{plan.volume} {network} Data purchase to {phone}", amount = price, previous_balance = bal, after_balance= new_bal)
        
                working_trans = Transact.objects.create(
                email=user.email,
                user=user,
                transaction="Transaction Processing....",
                status="Pending",
                cost=price,
                old_balance=bal,
                new_balance=new_bal,
                phone_number=phone,
                d_network=network,
                value="DATA",
                volume=plan.volume,
                provider_source=source,
                )
                return bal, new_bal, price,working_trans
    else:
        return False




# process data
def process_data_api(network, plan, phone, user):
    # GET FILES
    files = Switch.objects.get(pk=1)
    MTN = files.mtn_sme
    GIFTING = files.mtn_gifting
    GIFTINGLITE = files.mtn_cg_lite
    GLO = files.glo
    GLO_CG = fetch_vendor("Glocgdata",files.glo_cg,"glo_cg_medium",plan)
    # GLO_CG = files.glo_cg
    GLO_AWOOF = files.glo_awoof_gifting
    AIRTEL = files.airtel
    AIRTEL_CG = files.airtel_cg
    AIRTEL_AWOOF = files.airtel_awoof
    MOBILE = files.mobile
    MOBILE_SME = files.mobile_sme
    MTN_COUPON = files.mtn_coupon
    MTN_DATASHARE = files.mtn_datashare
    # MTN_DATASHARE = files.mtn_datashare
    MTN_DIRECTGIFTING = files.mtn_directgifting
    MTN_AWOOFGIFTING = files.mtn_awoofgifting
    MTN_TALKMORE = files.mtn_talkmore
    GLO_TALKMORE = files.glo_talkmore
    AIRTEL_TALKMORE = files.airtel_talkmore

    sell_mtn = getattr(mtn_sme, MTN)
    sell_gifting = getattr(mtn_gifting, GIFTING)
    sell_giftinglite = getattr(mtn_giftinglite, GIFTINGLITE)
    sell_glo = getattr(glo, GLO)
    sell_glocg = getattr(glo_cg, GLO_CG)
    sell_mobile = getattr(mobile, MOBILE)
    sell_mobilesme = getattr(mobile_sme, MOBILE_SME)
    sell_airtel = getattr(airtel, AIRTEL)
    sell_airtelcg = getattr(airtel_cg, AIRTEL_CG)
    sell_airtelawoof = getattr(airtel_awoof, AIRTEL_AWOOF)
    sell_coupon = getattr(mtn_coupon, MTN_COUPON)
    sell_directgifting = getattr(mtn_directgifting, MTN_DIRECTGIFTING)
    sell_awoofgifting = getattr(mtn_awoofgifting, MTN_AWOOFGIFTING)
    sell_gloawoofgifting = getattr(glo_awoof, GLO_AWOOF)
    sell_glotalkmore = getattr(glo_talkmore, GLO_TALKMORE)
    sell_mtntalkmore = getattr(mtn_talkmore, MTN_TALKMORE)
    sell_airteltalkmore = getattr(airtel_talkmore, AIRTEL_TALKMORE)
    # END OF GET FILES
    blist = black(phone)
    if blist:
        data = {'message': "The transaction cannot procceed", 'status': 'Unsuccessful', 'api_response': "The transaction cannot procceed", 'Status': 'failed'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")
    else:
        pass
    
    if network == "MTN-SME" or network == "MTN":
        network = "MTN-SME"
        item1 = Lockdata.objects.get(pk=1)
        if item1.availability == "ENABLE":
            try:
                plan_d = Mtnsmedata.objects.get(volume=plan)
            except:
                data = {'message': "Invalid plan Type", 'status': 'Unsuccessful','api_response': "Invalid plan Type", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            receipt = debiting_system(user, plan_d, user.debitmtnsme, user.mtn_sme, user.fundmtnsme, network, phone,MTN)
            if receipt is not False:
                outcome = sell_mtn(network=network, plan=plan_d, phone=phone)
            else:
                data = {'message': 'Dear Customer, your balance is insufficient, kindly fund your wallet',
                        'status': 'Unsuccessful','api_response': "Dear Customer, your balance is insufficient, kindly fund your wallet", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful','api_response': "Sorry, this service is currently unavailable", 'Status': 'failed'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    elif network == "MTN-CG" or network == "GIFTING":
        network = "MTN-CG"
        item2 = Lockdata.objects.get(pk=2)
        if item2.availability == "ENABLE":
            try:
                plan_d = Giftingdata.objects.get(volume=plan)
            except:
                data = {'message': "Invalid plan Type", 'status': 'Unsuccessful','api_response': "Invalid plan Type", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            receipt = debiting_system(user, plan_d, user.debitmtncg, user.mtn_cg, user.fundmtncg, network, phone,GIFTING)
            if receipt is not False:
                outcome = sell_gifting(network=network, plan=plan_d, phone=phone)
            else:
                data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                        'status': 'Unsuccessful','api_response': "Dear Customer, your balance is insufficient, kindly fund your wallet", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful','api_response': "Sorry, this service is currently unavailable", 'Status': 'failed'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    
    elif network == "MTN-CG-LITE":
        itemz = Lockdata.objects.get(pk=14)
        if itemz.availability == "ENABLE":
            try:
                plan_d = Giftinglitedata.objects.get(volume=plan)
            except:
                data = {'message': "Invalid plan Type", 'status': 'Unsuccessful','api_response': "Invalid plan Type", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            receipt = debiting_system(user, plan_d, None, None, None, network, phone,GIFTINGLITE)
            if receipt is not False:
                outcome = sell_giftinglite(network=network, plan=plan_d, phone=phone)
            else:
                data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                        'status': 'Unsuccessful','api_response': "Dear Customer, your balance is insufficient, kindly fund your wallet", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful','api_response': "Sorry, this service is currently unavailable", 'Status': 'failed'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    elif network == "MTNDIRECT-COUPON" or network == "MTNDIRECT_COUPON":
        network = "MTNDIRECT-COUPON"
        item9 = Lockdata.objects.get(pk=9)
        if item9.availability == "ENABLE":
            try:
                plan_d = Mtncoupon.objects.get(volume=plan)
            except:
                data = {'message': "Invalid plan Type", 'status': 'Unsuccessful','api_response': "Invalid plan Type", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            receipt = debiting_system(user, plan_d, None, None, None, network, phone,MTN_COUPON)
            if receipt is not False:
                outcome = sell_coupon(network=network, plan=plan_d, phone=phone)
            else:
                data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                        'status': 'Unsuccessful','api_response': "Dear Customer, your balance is insufficient, kindly fund your wallet", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful','api_response': "Sorry, this service is currently unavailable", 'Status': 'failed'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    elif network == "GLO":
        item5 = Lockdata.objects.get(pk=5)
        if item5.availability == "ENABLE":
            try:
                plan_d = Glodata.objects.get(volume=plan)
            except:
                data = {'message': "Invalid plan Type", 'status': 'Unsuccessful','api_response': "Invalid plan Type", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            receipt = debiting_system(user, plan_d, None, None, None, network, phone,GLO)
            if receipt is not False:
                outcome = sell_glo(network=network, plan=plan_d, phone=phone)
            else:
                data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                        'status': 'Unsuccessful','api_response': "Dear Customer, your balance is insufficient, kindly fund your wallet", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful','api_response': "Sorry, this service is currently unavailable", 'Status': 'failed'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    elif network == "GLO-AWOOF-GIFTING":
        itemG = Lockdata.objects.get(pk=15)
        if itemG.availability == "ENABLE":
            try:
                plan_d = Glospecialdata.objects.get(volume=plan)
            except:
                data = {'message': "Invalid plan Type", 'status': 'Unsuccessful','api_response': "Invalid plan Type", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            receipt = debiting_system(user, plan_d, None, None, None, network, phone,GLO_AWOOF)
            if receipt is not False:
                outcome = sell_gloawoofgifting(network=network, plan=plan_d, phone=phone)
            else:
                data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                        'status': 'Unsuccessful','api_response': "Dear Customer, your balance is insufficient, kindly fund your wallet", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful','api_response': "Sorry, this service is currently unavailable", 'Status': 'failed'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    elif network == "GLO-CG":
        item6 = Lockdata.objects.get(pk=6)
        if item6.availability == "ENABLE":
            try:
                plan_d = Glocgdata.objects.get(volume=plan)
            except:
                data = {'message': "Invalid plan Type", 'status': 'Unsuccessful','api_response': "Invalid plan Type", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            receipt = debiting_system(user, plan_d, user.debitglocg, user.glo_cg, user.fundglocg, network, phone,GLO_CG)
            if receipt is not False:
                outcome = sell_glocg(network=network, plan=plan_d, phone=phone)
            else:
                data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                        'status': 'Unsuccessful','api_response': "Dear Customer, your balance is insufficient, kindly fund your wallet", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful','api_response': "Sorry, this service is currently unavailable", 'Status': 'failed'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    elif network == "AIRTEL":
        item3 = Lockdata.objects.get(pk=3)
        if item3.availability == "ENABLE":
            try:
                plan_d = Airteldata.objects.get(volume=plan)
            except:
                data = {'message': "Invalid plan Type", 'status': 'Unsuccessful','api_response': "Invalid plan Type", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            receipt = debiting_system(user, plan_d, None, None, None, network, phone,AIRTEL)
            if receipt is not False:
                outcome = sell_airtel(network=network, plan=plan_d, phone=phone)
            else:
                data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                        'status': 'Unsuccessful','api_response': "Dear Customer, your balance is insufficient, kindly fund your wallet", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful','api_response': "Sorry, this service is currently unavailable", 'Status': 'failed'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    elif network == "AIRTEL-AWOOF":
        item3 = Lockdata.objects.get(pk=12)
        if item3.availability == "ENABLE":
            try:
                plan_d = Airtelawoofgifting.objects.get(volume=plan)
            except:
                data = {'message': "Invalid plan Type", 'status': 'Unsuccessful','api_response': "Invalid plan Type", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            receipt = debiting_system(user, plan_d, None, None, None, network, phone,AIRTEL_AWOOF)
            if receipt is not False:
                outcome = sell_airtelawoof(network=network, plan=plan_d, phone=phone)
            else:
                data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                        'status': 'Unsuccessful','api_response': "Dear Customer, your balance is insufficient, kindly fund your wallet", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful','api_response': "Sorry, this service is currently unavailable", 'Status': 'failed'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    elif network == "AIRTEL-CG":
        item4 = Lockdata.objects.get(pk=4)
        if item4.availability == "ENABLE":
            try:
                plan_d = Airtelcgdata.objects.get(volume=plan)
            except:
                data = {'message': "Invalid plan Type", 'status': 'Unsuccessful','api_response': "Invalid plan Type", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            receipt = debiting_system(user, plan_d, user.debitairtelcg, user.airtel_cg, user.fundairtelcg, network, phone,AIRTEL_CG)
            if receipt is not False:
                outcome = sell_airtelcg(network=network, plan=plan_d, phone=phone)
            else:
                data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                        'status': 'Unsuccessful','api_response': "Dear Customer, your balance is insufficient, kindly fund your wallet", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful','api_response': "Sorry, this service is currently unavailable", 'Status': 'failed'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    elif network == "9MOBILE" or network == "ETISALAT":
        network = "9MOBILE"
        item7 = Lockdata.objects.get(pk=7)
        if item7.availability == "ENABLE":
            try:
                plan_d = Mobiledata.objects.get(volume=plan)
            except:
                data = {'message': "Invalid plan Type", 'status': 'Unsuccessful','api_response': "Invalid plan Type", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            receipt = debiting_system(user, plan_d, None, None, None, network, phone,MOBILE)
            if receipt is not False:
                outcome = sell_mobile(network=network, plan=plan_d, phone=phone)
            else:
                data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                        'status': 'Unsuccessful','api_response': "Dear Customer, your balance is insufficient, kindly fund your wallet", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful','api_response': "Sorry, this service is currently unavailable", 'Status': 'failed'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")

    elif network == "MTN-DATASHARE" or network == "MTN_SME1":
        network = "MTN-DATASHARE"
        item9 = Lockdata.objects.get(pk=10)
        if item9.availability == "ENABLE":
            try:
                plan_d = Mtndatashare.objects.get(volume=plan)
            except:
                data = {'message': "Invalid plan Type", 'status': 'Unsuccessful','api_response': "Invalid plan Type", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            receipt = debiting_system(user, plan_d, None, None, None, network, phone,MTN_DATASHARE)
            if receipt is not False:
                outcome = mtn_datashare.sell_with_fallback(
                    network=network,
                    plan=plan_d,
                    phone=phone,
                    primary_provider=files.mtn_datashare,
                    fallback_provider=files.mtn_datashare_fallback
                )
            else:
                data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                        'status': 'Unsuccessful','api_response': "Dear Customer, your balance is insufficient, kindly fund your wallet", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful','api_response': "Sorry, this service is currently unavailable", 'Status': 'failed'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
            
    elif network == "MTN-DG":
        itemm = Lockdata.objects.get(pk=11)
        if itemm.availability == "ENABLE":
            try:
                plan_d = Mtndirectgifting.objects.get(volume=plan)
            except:
                data = {'message': "Invalid plan Type", 'status': 'Unsuccessful','api_response': "Invalid plan Type", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            receipt = debiting_system(user, plan_d, None, None, None, network, phone,MTN_DIRECTGIFTING)
            if receipt is not False:
                outcome = sell_directgifting(network=network, plan=plan_d, phone=phone)
            else:
                data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                        'status': 'Unsuccessful','api_response': "Dear Customer, your balance is insufficient, kindly fund your wallet", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful','api_response': "Sorry, this service is currently unavailable", 'Status': 'failed'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
            
    elif network == "MTN-AWOOF-GIFTING":
        itemm = Lockdata.objects.get(pk=13)
        if itemm.availability == "ENABLE":
            try:
                plan_d = Mtnawoofgifting.objects.get(volume=plan)
            except:
                data = {'message': "Invalid plan Type", 'status': 'Unsuccessful','api_response': "Invalid plan Type", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            receipt = debiting_system(user, plan_d, None, None, None, network, phone,MTN_AWOOFGIFTING)
            if receipt is not False:
                outcome = sell_awoofgifting(network=network, plan=plan_d, phone=phone)
            else:
                data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                        'status': 'Unsuccessful','api_response': "Dear Customer, your balance is insufficient, kindly fund your wallet", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful','api_response': "Sorry, this service is currently unavailable", 'Status': 'failed'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    

    elif network == "9MOBILE-CG" or network == "9mobile_sme_cg":
        network = "9MOBILE-CG"
        item8 = Lockdata.objects.get(pk=8)
        if item8.availability == "ENABLE":
            try:
                plan_d = Mobilesmedata.objects.get(volume=plan)
            except:
                data = {'message': "Invalid plan Type", 'status': 'Unsuccessful','api_response': "Invalid plan Type", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            receipt = debiting_system(user, plan_d, user.debitmobilecg, user.mobile_cg, user.fundmobilecg, network, phone,MOBILE_SME)
            if receipt is not False:
                outcome = sell_mobilesme(network=network, plan=plan_d, phone=phone)
            else:
                data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                        'status': 'Unsuccessful','api_response': "Dear Customer, your balance is insufficient, kindly fund your wallet", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful','api_response': "Sorry, this service is currently unavailable", 'Status': 'failed'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
            
    elif network == "AIRTEL-TALKMORE-AIRTIME":
        item3 = Lockdata.objects.get(pk=18)
        if item3.availability == "ENABLE":
            try:
                plan_d = Airteltalkmore.objects.get(volume=plan)
            except:
                data = {'message': "Invalid plan Type", 'status': 'Unsuccessful','api_response': "Invalid plan Type", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            receipt = debiting_system(user, plan_d, None, None, None, network, phone,AIRTEL_TALKMORE)
            if receipt is not False:
                outcome = sell_airteltalkmore(network=network, plan=plan_d, phone=phone)
            else:
                data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                        'status': 'Unsuccessful','api_response': "Dear Customer, your balance is insufficient, kindly fund your wallet", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful','api_response': "Sorry, this service is currently unavailable", 'Status': 'failed'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
            
    elif network == "GLO-TALKMORE-AIRTIME":
        item3 = Lockdata.objects.get(pk=19)
        if item3.availability == "ENABLE":
            try:
                plan_d = Glotalkmore.objects.get(volume=plan)
            except:
                data = {'message': "Invalid plan Type", 'status': 'Unsuccessful','api_response': "Invalid plan Type", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            receipt = debiting_system(user, plan_d, None, None, None, network, phone,GLO_TALKMORE)
            if receipt is not False:
                outcome = sell_glotalkmore(network=network, plan=plan_d, phone=phone)
            else:
                data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                        'status': 'Unsuccessful','api_response': "Dear Customer, your balance is insufficient, kindly fund your wallet", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful','api_response': "Sorry, this service is currently unavailable", 'Status': 'failed'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
            
    elif network == "MTN-TALKMORE-AIRTIME":
        item3 = Lockdata.objects.get(pk=17)
        if item3.availability == "ENABLE":
            try:
                plan_d = Mtntalkmore.objects.get(volume=plan)
            except:
                data = {'message': "Invalid plan Type", 'status': 'Unsuccessful','api_response': "Invalid plan Type", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            receipt = debiting_system(user, plan_d, None, None, None, network, phone,MTN_TALKMORE)
            if receipt is not False:
                outcome = sell_mtntalkmore(network=network, plan=plan_d, phone=phone)
            else:
                data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                        'status': 'Unsuccessful','api_response': "Dear Customer, your balance is insufficient, kindly fund your wallet", 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful','api_response': "Sorry, this service is currently unavailable", 'Status': 'failed'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    else:
        data = {'message': "Invalid Network Type", 'status': 'Unsuccessful','api_response': "Invalid Network Type", 'Status': 'failed'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")

    old_bal = receipt[0]
    new_bal = receipt[1]
    price = receipt[2]
    if outcome[1] == "Unsuccessful":
        new_bal = old_bal

        if len(receipt) == 5:
            # Bucket transaction
            refund_bucket = receipt[3]
            refund_bucket(user.id, price)

        elif len(receipt) == 4:
            # Normal wallet transaction
            with transaction.atomic():
                user.fund(user.id, price)

                Wallet_summary.objects.create(
                    user=user,
                    product=f"Refund for {plan} {network} Data purchase to {phone}",
                    amount=price,
                    previous_balance=old_bal - price,
                    after_balance=old_bal
                )

        else:
            raise ValueError(
                "Unexpected receipt structure during MTN DataShare update"
            )

    if len(receipt) == 5:
        working_trans = receipt[4]
    elif len(receipt) == 4:
        working_trans = receipt[3]
    else:
        raise ValueError(
            "Unexpected receipt structure during MTN DataShare transaction update"
        )

    working_trans.transaction = outcome[0]
    working_trans.status = outcome[1]
    working_trans.new_balance = new_bal
    working_trans.save()

    Sale.objects.create(
        user=user,
        network=network,
        plan=plan,
        status=outcome[1],
        cost=price,
        date=date.today().strftime("%Y-%m-%d"),
    )
    if outcome[1] == "Successful":
        real_status = "successful"
    elif outcome[1] == "Pending":
        real_status = "processing"
    else:
        real_status = "failed"

    data = {'message': f"{outcome[0]} \n\n You can view your receipt at https://exactsub.com/receipt/?ident={working_trans.request_id}", 'status': outcome[1], 'network': network, 'plan': plan, 'phone': phone, 'cost': price, 'balance_before': old_bal, 'balance_after': new_bal, 'Status': real_status, 'api_response': outcome[0]}
    # datas = json.dumps(data)
    return data



def airtime_debit(user, network, amount, phone):
    network_list = Airtime.objects.all()
    bal = user.balance
    for item in network_list:
        if item.network == network:
            if user.category == 'API1' or user.category == 'API2' or user.category == 'API3':
                disct = item.api
            else:
                disct = item.discount
            price = int(amount) - (disct / 100) * int(amount)
    if bal < price or price < 0:
        return False
    elif bal > price or bal == price:
        new_bal = bal - price
        with transaction.atomic():
            check = user.debit(user.id, price)
            if check == False:
                return False
            else:
                Wallet_summary.objects.create(user= user, product=f"{network} Airtime purchased on {phone}", amount = price, previous_balance = bal, after_balance= new_bal)
        
                working_trans = Transact.objects.create(
                email=user.email,
                user=user,
                transaction="Transaction Processing....",
                status="Pending",
                cost=price,
                old_balance=bal,
                new_balance=new_bal,
                phone_number=phone,
                d_network=network,
                value="AIRTIME",
                volume=amount,
                )
                return bal, new_bal, price, working_trans
    else:
        return False

# process airtime
def process_airtime_api(network, amount, phone, user):
    # GET FILE
    files = Airtime_Switch.objects.get(pk=1)
    MTN = files.mtn
    AIRTEL = files.airtel
    GLO = files.glo
    MOBILE = files.etisalat
    sell_mtn = getattr(airtime, MTN)
    sell_airtel = getattr(airtime, AIRTEL)
    sell_glo = getattr(airtime, GLO)
    sell_mobile = getattr(airtime, MOBILE)
    # END
    blist = black(phone)
    if blist:
        data = {'message': "The transaction cannot procceed", 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return data
    else:
        pass
    if int(amount) < 50:
        data = {'message': f'You cannot vend airtime below 50 Naira', 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return data
    item = Lockservice.objects.get(pk=1)
    if item.availability == "ENABLE":
        receipt = airtime_debit(user, network, amount, phone)
        if receipt is not False:
            if network == 'MTN':
                outcome = sell_mtn(network=network, amount=amount, phone=phone)
            elif network == 'AIRTEL':
               outcome = sell_airtel(network=network, amount=amount, phone=phone) 
            elif network == 'GLO':
               outcome = sell_glo(network=network, amount=amount, phone=phone)
            elif network == 'ETISALAT':
               outcome = sell_mobile(network=network, amount=amount, phone=phone)
        else:
            data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                    'status': 'Unsuccessful'}
            datas = json.dumps(data)
            return data
    else:
        data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return data


    old_bal = receipt[0]
    new_bal = receipt[1]
    price = receipt[2]
    working_trans = receipt[3]
    if outcome[1] == "Unsuccessful":
        new_bal = old_bal
        user.fund(user.id, price)
        Wallet_summary.objects.create(user= user, product=f"{network} Airtime purchased on {phone} has been Refunded", amount = price, previous_balance = new_bal-price, after_balance= new_bal)
        
    working_trans.transaction=outcome[0]
    working_trans.status=outcome[1]
    working_trans.new_balance=new_bal
    working_trans.save()
    
    Sale.objects.create(
        user=user,
        network=network,
        plan="Airtime",
        status=outcome[1],
        cost=price,
        date=date.today().strftime("%Y-%m-%d"),
    )
    data = {'message': f"{outcome[0]} \n\n You can view your receipt at https://almubconnect.com.ng/receipt/?ident={working_trans.request_id}", 'status': outcome[1], 'network': network, 'phone': phone, 'cost': price,
            'balance_before': old_bal, 'balance_after': new_bal}
    return data



def tv_debit(user,plan, price_list, iuc_number):
    bal = user.balance
    for item in price_list:
        if item.package == plan:
            if user.category == 'API1' or user.category == 'API2' or user.category == 'API3':
                price = item.api
            else:
                price = item.amount
    if bal < price or price < 0:
        return False
    elif bal > price or bal == price:
        new_bal = bal - price
        
        with transaction.atomic():
            check = user.debit(user.id, price)
            if check == False:
                return False
            else:
                Wallet_summary.objects.create(user= user, product=f"{plan} purhased to {iuc_number}", amount = price, previous_balance = bal, after_balance= new_bal)
        
                working_trans = Transact.objects.create(
                email=user.email,
                user=user,
                transaction="Transaction Processing....",
                status="Pending",
                cost=price,
                old_balance=bal,
                new_balance=new_bal,
                phone_number=iuc_number,
                d_network=plan,
                value="CABLE",
                )
                return bal, new_bal, price,working_trans
    else:
        return False


# process tv
def process_tv_api(service, plan, iuc_number, user):
    # GET FILES
    files = Switch.objects.get(pk=1)
    DSTV = files.dstv
    GOTV = files.gotv
    STARTIMES = files.startimes

    sell_dstv = getattr(dstv, DSTV)
    sell_gotv = getattr(gotv, GOTV)
    sell_startimes = getattr(startimes, STARTIMES)

    # END
    global outcome
    table = Config.objects.get(pk=1)
    vtpass_key = table.vtpass_api_key.encode()
    vtpass_api_key = b64encode(vtpass_key).decode()
    urls = "https://api-service.vtpass.com/api/merchant-verify"
    headers = {
             "Authorization": f"Basic {vtpass_api_key}",
             "Content-Type": "application/json",
             }
    parameters = {
        "billersCode": iuc_number,
        "serviceID": service,
    }
    # responses = requests.post(urls, headers=headers, json=parameters)
    # response = responses.json()
    # if 'content' in response:
    #     res = response["content"]["Customer_Name"]
    #     stat = True
    # else:
    #     stat = False
    stat = True
    if stat is True:
        if service == "dstv":
            item2 = Lockservice.objects.get(pk=2)
            if item2.availability == "ENABLE":
                price_list = Dstv.objects.all()
                receipt = tv_debit(user, plan, price_list, iuc_number)
                if receipt is not False:
                    outcome = sell_dstv(service, plan, iuc_number, user)
                else:
                    data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                            'status': 'Unsuccessful'}
                    datas = json.dumps(data)
                    return data
            else:
                data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
                datas = json.dumps(data)
                return data

        elif service == "gotv":
            item3 = Lockservice.objects.get(pk=3)
            if item3.availability == "ENABLE":
                price_list = Gotv.objects.all()
                receipt = tv_debit(user, plan, price_list, iuc_number)
                if receipt is not False:
                    outcome = sell_gotv(service, plan, iuc_number, user)
                else:
                    data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                            'status': 'Unsuccessful'}
                    datas = json.dumps(data)
                    return data
            else:
                data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
                datas = json.dumps(data)
                return data

        elif service == "startimes":
            item4 = Lockservice.objects.get(pk=4)
            if item4.availability == "ENABLE":
                price_list = Startimes.objects.all()
                receipt = tv_debit(user, plan, price_list, iuc_number)
                if receipt is not False:
                    outcome = sell_startimes(service, plan, iuc_number, user)
                else:
                    data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                            'status': 'Unsuccessful'}
                    datas = json.dumps(data)
                    return data
            else:
                data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
                datas = json.dumps(data)
                return data
        else:
            data = {'message': "Ivalid Cable Type", 'status': 'Unsuccessful'}
            datas = json.dumps(data)
            return data

        old_bal = receipt[0]
        new_bal = receipt[1]
        price = receipt[2]
        working_trans = receipt[3]
        if outcome[1] == "Unsuccessful":
            new_bal = old_bal
            user.fund(user.id, price)
            Wallet_summary.objects.create(user= user, product=f"{plan} purhased to {iuc_number} has been Refunded", amount = price, previous_balance = new_bal-price, after_balance= new_bal)
        
        working_trans.transaction=outcome[0]
        working_trans.status=outcome[1]
        working_trans.new_balance=new_bal
        working_trans.save()

        Sale.objects.create(
            user=user,
            network=service,
            plan=plan,
            status=outcome[1],
            cost=price,
            date=date.today().strftime("%Y-%m-%d"),
        )
        data = {'message': f"{outcome[0]} \n\n You can view your receipt at https://almubconnect.com.ng/receipt/?ident={working_trans.request_id}", 'status': outcome[1], 'service': service, 'plan': plan, 'iuc': iuc_number,
                'cost': price, 'balance_before': old_bal, 'balance_after': new_bal}
        datas = json.dumps(data)
        return data
    else:
        data = {'message': "Invalid IUC number", 'status': 'Unsuccessful'}
        
    return data



def electric_debit(user, service, amount, meter_num):
    service_list = Electricity.objects.all()
    bal = user.balance
    for item in service_list:
        if item.service == service:
            if user.category == 'API1' or user.category == 'API2' or user.category == 'API3':
                charges = int(item.api)
            else:
                charges = int(item.discount)
            price = int(amount) + charges
    if bal < price or price < 0:
        return False
    elif bal > price or bal == price:
        new_bal = bal - price
        
        with transaction.atomic():
            check = user.debit(user.id, price)
            if check == False:
                return False
            else:
                Wallet_summary.objects.create(user= user, product=f"{service} purhased to {meter_num}", amount = price, previous_balance = bal, after_balance= new_bal)
        
                working_trans = Transact.objects.create(
                email=user.email,
                user=user,
                transaction="Transaction Processing....",
                status="Pending",
                cost=price,
                old_balance=bal,
                new_balance=new_bal,
                phone_number=meter_num,
                d_network=service,
                value="ELECTRICITY",
                )
                return bal, new_bal, price,working_trans
    else:
        return False

# process electricity
def process_electricity_api(service, meter_num, amount, user):
    # GET FILE
    files = Switch.objects.get(pk=1)
    ELECTRICITY = files.electricity
    sell_electricity = getattr(electricity, ELECTRICITY)
    # END

    item = Lockservice.objects.get(pk=5)
    print("got here")
    if item.availability == "ENABLE":
        receipt = electric_debit(user, service, amount, meter_num)
        if receipt is not False:
            outcome = sell_electricity(service=service, amount=amount, meter_num=meter_num, user=user)
        else:
            data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                    'status': 'Unsuccessful'}
            datas = json.dumps(data)
            return data
    else:
        data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return data

    old_bal = receipt[0]
    new_bal = receipt[1]
    price = receipt[2]
    working_trans = receipt[3]
    if outcome[1] == "Unsuccessful":
        new_bal = old_bal
        user.fund(user.id, price)
        
        Wallet_summary.objects.create(user= user, product=f"{service} purhased to {meter_num} has been Refunded", amount = price, previous_balance = new_bal-price, after_balance= new_bal)
        
    working_trans.transaction=outcome[0]
    working_trans.status=outcome[1]
    working_trans.new_balance=new_bal
    working_trans.save()

    Sale.objects.create(
        user=user,
        network=service,
        plan="Electricity bill",
        status=outcome[1],
        cost=price,
        date=date.today().strftime("%Y-%m-%d"),
    )
    
    try:
        token = outcome[7]
    except:
        token = ''

    data = {'message': f"{outcome[0]} \n\n You can view your receipt at https://almubconnect.com.ng/receipt/?ident={working_trans.request_id}", 'status': outcome[1], 'service': service, 'meter_number': meter_num, 'token': token, 'cost': price, 'balance_before': old_bal, 'balance_after': new_bal}
    datas = json.dumps(data)
    return data



def result_debit(user, exam_type, quantity):
    network_list = ResultPin.objects.all()
    bal = user.balance
    try:
        qs = len(exam_pin.objects.filter(exam=exam).filter(available=True)[:quantity])
        # print(qs)
    except:
        qs = quantity
    for item in network_list:
        if item.exam_type == exam_type:
            if user.category == 'API1' or user.category == 'API2' or user.category == 'API3':
                # price = item.api
                price = item.api  * int(quantity)
            else:
                # price = item.price
                price = item.price  * int(quantity)
    if bal < price or price < 0:
        return False
    elif bal > price or bal == price:
        new_bal = bal - price
        
        with transaction.atomic():
            check = user.debit(user.id, price)
            if check == False:
                return False
            else:
                Wallet_summary.objects.create(user= user, product=f"{exam_type} pin purhased", amount = price, previous_balance = bal, after_balance= new_bal)
                working_trans = Transact.objects.create(
                email=user.email,
                user=user,
                transaction="Transaction Processing....",
                status="Pending",
                cost=price,
                old_balance=bal,
                new_balance=new_bal,
                phone_number=user.phoneNumber,
                d_network=exam_type,
                value="EXAM",
                )
                return bal, new_bal, price,working_trans
    else:
        return False
        
        
        

# process result checker pin

def process_result_api(exam_type, quantity, phone, user):
    # GET FILE
    files = Switch.objects.get(pk=1)
    RESULT = files.result
    sell_result = getattr(result, RESULT)
    # END
    item = Lockservice.objects.get(pk=6)
    if item.availability == "ENABLE":
        receipt = result_debit(user, exam_type, quantity)
        if receipt is not False:
            outcome = sell_result(exam_type=exam_type, quantity=quantity, phone=phone)
        else:
            data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                    'status': 'Unsuccessful'}
            datas = json.dumps(data)
            return data
    else:
        data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return data

    old_bal = receipt[0]
    new_bal = receipt[1]
    price = receipt[2]
    working_trans = receipt[3]
    if outcome[1] == "Unsuccessful":
        new_bal = old_bal
        user.fund(user.id, price)
        
        Wallet_summary.objects.create(user= user, product=f"{exam_type} pin purhased has been Refunded", amount = price, previous_balance = new_bal-price, after_balance= new_bal)
        
    working_trans.transaction=outcome[0]
    working_trans.status=outcome[1]
    working_trans.new_balance=new_bal
    working_trans.save()


    Sale.objects.create(
        user=user,
        network=exam_type,
        plan="Exam pin",
        status=outcome[1],
        cost=price,
        date=date.today().strftime("%Y-%m-%d"),
    )
    try:
        pin = outcome[7]
    except:
        pin = ''
    data = {'message': f"{outcome[0]} \n\n You can view your receipt at https://almubconnect.com.ng/receipt/?ident={working_trans.request_id}", 'status': outcome[1], 'exam_type': exam_type, 'pin': pin,
            'cost': price, 'balance_before': old_bal, 'balance_after': new_bal}
    datas = json.dumps(data)
    return data

