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, recharge_card, mtn_giftinglite, glo_awoof, glo_awoof,glo_talkmore,mtn_talkmore,airtel_talkmore
from .models import *
from base64 import b64encode
from django.http import HttpResponse
import requests
from .atuns import zone
from .sales import trans_limit
from django.db import transaction
from django.core.cache import cache
import re




def black(num):
    try:
        Blacklist.objects.get(number=num)
        return True
    except:
        return False

def save_transaction_delivery(transaction, delivery_type, data):
    """
    Store sensitive transaction delivery data separately from Transact.

    transaction:
        Existing Transact object.

    delivery_type:
        ELECTRICITY or EXAM_PIN.

    data:
        Python dictionary containing the delivery information.

    This function intentionally does not alter the transaction result
    if delivery storage fails. The actual transaction status remains
    controlled by the provider response.
    """

    try:
        TransactionDelivery.objects.update_or_create(
            transaction_id=transaction.id,
            defaults={
                "delivery_type": delivery_type,
                "data": json.dumps(data),
            }
        )

        return True

    except Exception as exc:

        logger.exception(
            "Failed to save transaction delivery. "
            "Transaction ID: %s | Delivery type: %s | Error: %s",
            getattr(transaction, "id", None),
            delivery_type,
            exc
        )

        return False

def validate_airtel(phone):
    n = phone[0] + phone[1] + phone[2] + phone[3]
    if n == "0802" or n == "0808" or n == "0708" or n == "0812" or n == "0701" or n == "0902" or n == "0901" or n == "0904" or n == "0907" or n == "0912":
        return True
    else:
        return False


def validate_glo(phone):
    n = phone[0] + phone[1] + phone[2] + phone[3]
    if n == "0805" or n == "0807" or n == "0705" or n == "0815" or n == "0811" or n == "0905" or n == "0915":
        return True
    else:
        return False


def validate_mobile(phone):
    n = phone[0] + phone[1] + phone[2] + phone[3]
    if n == "0809" or n == "0818" or n == "0817" or n == "0909" or n == "0908":
        return True
    else:
        return False


def validate_mtn(phone):
    n = phone[0] + phone[1] + phone[2] + phone[3]
    m = phone[0] + phone[1] + phone[2] + phone[3] + phone[4]
    if n == "0803" or n == "0806" or n == "0703" or n == "0706" or n == "0813" or n == "0816" or n == "0810" or n == "0814" or n == "0903" or n == "0906" or n == "0913" or n == "0916" or n == "0704" or m == "07025" or m == "07026":
        return True
    else:
        return False



def validate_data(network, phone, validate):
    if network == "MTN-SME" and validate is False:
        val = validate_mtn(phone)
        if val:
            return True
        else:
            return False
    elif network == "GLO" and validate is False:
        val = validate_glo(phone)
        if val:
            return True
        else:
            return False
    elif network == "AIRTEL" and validate is False:
        val = validate_airtel(phone)
        if val:
            return True
        else:
            return False
    elif network == "ETISALAT" and validate is False:
        val = validate_mobile(phone)
        if val:
            return True
        else:
            return False
    elif network == "MTN-CG" and validate is False:
        val = validate_mtn(phone)
        if val:
            return True
        else:
            return False
    elif network == "MTN-CG-LITE" and validate is False:
        val = validate_mtn(phone)
        if val:
            return True
        else:
            return False
    elif network == "MTN-DG" and validate is False:
        val = validate_mtn(phone)
        if val:
            return True
        else:
            return False
    elif network == "MTN-SPECIAL-DATA" and validate is False:
        val = validate_mtn(phone)
        if val:
            return True
        else:
            return False
    elif network == "MTNDIRECT-COUPON" and validate is False:
        val = validate_mtn(phone)
        if val:
            return True
        else:
            return False
    elif network == "GLO-CG" and validate is False:
        val = validate_glo(phone)
        if val:
            return True
        else:
            return False
    elif network == "GLO-AWOOF-GIFTING" and validate is False:
        val = validate_glo(phone)
        if val:
            return True
        else:
            return False
    elif network == "AIRTEL-CG" and validate is False:
        val = validate_airtel(phone)
        if val:
            return True
        else:
            return False
    elif network == "AIRTEL-AWOOF" and validate is False:
        val = validate_airtel(phone)
        if val:
            return True
        else:
            return False
    elif network == "9MOBILE-CG" and validate is False:
        val = validate_mobile(phone)
        if val:
            return True
        else:
            return False
    else:
        return True


def validate_airtime(network, phone, validate):
    if network == "MTN" and validate is False:
        val = validate_mtn(phone)
        if val:
            return True
        else:
            return False
    elif network == "GLO" and validate is False:
        val = validate_glo(phone)
        if val:
            return True
        else:
            return False
    elif network == "AIRTEL" and validate is False:
        val = validate_airtel(phone)
        if val:
            return True
        else:
            return False
    elif network == "ETISALAT" and validate is False:
        val = validate_mobile(phone)
        if val:
            return True
        else:
            return False
    else:
        return True
        
        
        
def check_limit(user, plan):
    
    if user.category == "EARNER":
        price = plan.amount
    elif user.category == "AFFILIATE":
        price = plan.amount2
    elif user.category == "AMBASSADOR":
        price = plan.amount3
    
    else:
        return False

    limit = trans_limit(user, price)
    return limit

        


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 pro_cess(network, plan, phone, validate, 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 = fetch_vendor("Mtndatashare",files.mtn_datashare,"mtn_datashare_medium",plan)
    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'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")
    else:
        pass
    check = validate_data(network, phone, validate)
    if check:
        pass
    else:
        data = {'message': f'You entered an invalid {network} number', 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")

    
    if 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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
                
            # CHECK TRANSACTION LIMIT 
            exceed_limit = check_limit(user,plan_d)
            if exceed_limit:
                data = {'message': 'Dear Customer, You Have Exceeded Your Daily Transaction Limit, Kindly Verify Your Account To Transact On The Platform Without Restrictions', 'status': 'Unsuccessful'}
                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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    elif 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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
                    
            # CHECK TRANSACTION LIMIT 
            exceed_limit = check_limit(user,plan_d)
            if exceed_limit:
                data = {'message': 'Dear Customer, You Have Exceeded Your Daily Transaction Limit, Kindly Verify Your Account To Transact On The Platform Without Restrictions', 'status': 'Unsuccessful'}
                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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
            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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
                
                
            # CHECK TRANSACTION LIMIT 
            exceed_limit = check_limit(user,plan_d)
            if exceed_limit:
                data = {'message': 'Dear Customer, You Have Exceeded Your Daily Transaction Limit, Kindly Verify Your Account To Transact On The Platform Without Restrictions', 'status': 'Unsuccessful'}
                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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
            
    elif 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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
                
                
            # CHECK TRANSACTION LIMIT 
            exceed_limit = check_limit(user,plan_d)
            if exceed_limit:
                data = {'message': 'Dear Customer, You Have Exceeded Your Daily Transaction Limit, Kindly Verify Your Account To Transact On The Platform Without Restrictions', 'status': 'Unsuccessful'}
                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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
            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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
                
                
            # CHECK TRANSACTION LIMIT 
            exceed_limit = check_limit(user,plan_d)
            if exceed_limit:
                data = {'message': 'Dear Customer, You Have Exceeded Your Daily Transaction Limit, Kindly Verify Your Account To Transact On The Platform Without Restrictions', 'status': 'Unsuccessful'}
                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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
            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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
                
                
            # CHECK TRANSACTION LIMIT 
            exceed_limit = check_limit(user,plan_d)
            if exceed_limit:
                data = {'message': 'Dear Customer, You Have Exceeded Your Daily Transaction Limit, Kindly Verify Your Account To Transact On The Platform Without Restrictions', 'status': 'Unsuccessful'}
                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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
            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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
                
                
            # CHECK TRANSACTION LIMIT 
            exceed_limit = check_limit(user,plan_d)
            if exceed_limit:
                data = {'message': 'Dear Customer, You Have Exceeded Your Daily Transaction Limit, Kindly Verify Your Account To Transact On The Platform Without Restrictions', 'status': 'Unsuccessful'}
                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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
            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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
                
                
            # CHECK TRANSACTION LIMIT 
            exceed_limit = check_limit(user,plan_d)
            if exceed_limit:
                data = {'message': 'Dear Customer, You Have Exceeded Your Daily Transaction Limit, Kindly Verify Your Account To Transact On The Platform Without Restrictions', 'status': 'Unsuccessful'}
                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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
            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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
                
            # CHECK TRANSACTION LIMIT 
            exceed_limit = check_limit(user,plan_d)
            if exceed_limit:
                data = {'message': 'Dear Customer, You Have Exceeded Your Daily Transaction Limit, Kindly Verify Your Account To Transact On The Platform Without Restrictions', 'status': 'Unsuccessful'}
                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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
            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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
                
                
            # CHECK TRANSACTION LIMIT 
            exceed_limit = check_limit(user,plan_d)
            if exceed_limit:
                data = {'message': 'Dear Customer, You Have Exceeded Your Daily Transaction Limit, Kindly Verify Your Account To Transact On The Platform Without Restrictions', 'status': 'Unsuccessful'}
                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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    elif 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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
                
            # CHECK TRANSACTION LIMIT 
            exceed_limit = check_limit(user,plan_d)
            if exceed_limit:
                data = {'message': 'Dear Customer, You Have Exceeded Your Daily Transaction Limit, Kindly Verify Your Account To Transact On The Platform Without Restrictions', 'status': 'Unsuccessful'}
                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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    elif 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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
                
            # CHECK TRANSACTION LIMIT 
            exceed_limit = check_limit(user,plan_d)
            if exceed_limit:
                data = {'message': 'Dear Customer, You Have Exceeded Your Daily Transaction Limit, Kindly Verify Your Account To Transact On The Platform Without Restrictions', 'status': 'Unsuccessful'}
                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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
            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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
                
            # CHECK TRANSACTION LIMIT 
            exceed_limit = check_limit(user,plan_d)
            if exceed_limit:
                data = {'message': 'Dear Customer, You Have Exceeded Your Daily Transaction Limit, Kindly Verify Your Account To Transact On The Platform Without Restrictions', 'status': 'Unsuccessful'}
                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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
            
    elif network == "MTN-AWOOF-GIFTING":
        itema = Lockdata.objects.get(pk=13)
        if itema.availability == "ENABLE":
            try:
                plan_d = Mtnawoofgifting.objects.get(volume=plan)
            except:
                data = {'message': "Invalid plan Type", 'status': 'Unsuccessful'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
                
            # CHECK TRANSACTION LIMIT 
            exceed_limit = check_limit(user,plan_d)
            if exceed_limit:
                data = {'message': 'Dear Customer, You Have Exceeded Your Daily Transaction Limit, Kindly Verify Your Account To Transact On The Platform Without Restrictions', 'status': 'Unsuccessful'}
                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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    
    
    elif 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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
                
            # CHECK TRANSACTION LIMIT 
            exceed_limit = check_limit(user,plan_d)
            if exceed_limit:
                data = {'message': 'Dear Customer, You Have Exceeded Your Daily Transaction Limit, Kindly Verify Your Account To Transact On The Platform Without Restrictions', 'status': 'Unsuccessful'}
                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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
            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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
                
            # CHECK TRANSACTION LIMIT 
            exceed_limit = check_limit(user,plan_d)
            if exceed_limit:
                data = {'message': 'Dear Customer, You Have Exceeded Your Daily Transaction Limit, Kindly Verify Your Account To Transact On The Platform Without Restrictions', 'status': 'Unsuccessful'}
                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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
            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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
                
            # CHECK TRANSACTION LIMIT 
            exceed_limit = check_limit(user,plan_d)
            if exceed_limit:
                data = {'message': 'Dear Customer, You Have Exceeded Your Daily Transaction Limit, Kindly Verify Your Account To Transact On The Platform Without Restrictions', 'status': 'Unsuccessful'}
                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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
            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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
                
            # CHECK TRANSACTION LIMIT 
            exceed_limit = check_limit(user,plan_d)
            if exceed_limit:
                data = {'message': 'Dear Customer, You Have Exceeded Your Daily Transaction Limit, Kindly Verify Your Account To Transact On The Platform Without Restrictions', 'status': 'Unsuccessful'}
                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'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    
    else:
        data = {'message': "Invalid Network Type", 'status': 'Unsuccessful'}
        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"),
    )

    data = {
        'message': (
            "Transaction failed. If your wallet was debited, "
            "your refund will be processed automatically."
            if outcome[1] == "Unsuccessful"
            else outcome[0]
        ),
        'status': outcome[1],
        'request_id': working_trans.request_id,
    }

    datas = json.dumps(data)
    return HttpResponse(datas, content_type="application/json")
        

def check_limit_airtime(user,network,amount):
    
    network_list = Airtime.objects.all()
    for item in network_list:
        if item.network == network:
            if user.category == 'API1' or user.category == 'API2' or user.category == 'API3':
                return False
            else:
                disct = item.discount
            price = int(amount) - (disct / 100) * int(amount)

    limit = trans_limit(user, price)
    return limit


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 pro_cess_airtime(network, amount, phone, validate, 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 HttpResponse(datas, content_type="application/json")
    else:
        pass
    check = validate_airtime(network, phone, validate)
    if check:
        pass
    else:
        data = {'message': f'You entered an invalid {network} number', 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")
        
    if int(amount) < 50:
        data = {'message': f'You cannot vend airtime below 50 Naira', 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")

    item = Lockservice.objects.get(pk=1)
    if item.availability == "ENABLE":
        
        # CHECK TRANSACTION LIMIT 
        exceed_limit = check_limit_airtime(user,network,amount)
        if exceed_limit:
            data = {'message': 'Dear Customer, You Have Exceeded Your Daily Transaction Limit, Kindly Verify Your Account To Transact On The Platform Without Restrictions', 'status': 'Unsuccessful'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
                
        
        
        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 HttpResponse(datas, content_type="application/json")
    else:
        data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")


    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': outcome[0],
        'status': outcome[1],
        'network': network,
        'phone': phone,
        'cost': price,
        'balance_before': old_bal,
        'balance_after': new_bal,
        'request_id': working_trans.request_id
    }

    datas = json.dumps(data)
    return HttpResponse(datas, content_type="application/json")


def check_limit_cable(user, price_list, plan):

    # Find the selected cable package.
    for item in price_list:

        if item.package == plan:

            try:

                # API users use API price + API service charge.
                if user.category == 'API1' or user.category == 'API2' or user.category == 'API3':

                    price = int(item.api) + int(item.api_charge)

                else:

                    # Normal users use normal price + normal service charge.
                    price = int(item.amount) + int(item.charge)

            except (TypeError, ValueError):

                # The package exists, but its pricing information
                # cannot be converted into a valid numeric amount.
                return "INVALID_PRICE"

            # A cable package should not have a negative price.
            if price < 0:

                return "INVALID_PRICE"

            # API users retain the existing transaction-limit bypass.
            if user.category == 'API1' or user.category == 'API2' or user.category == 'API3':

                return False

            # Check the normal user's daily transaction limit.
            return trans_limit(user, price)

    # The selected package does not exist.
    return "INVALID_PLAN"


def tv_debit(user, plan, price_list, iuc_number):

    price = None

    # Find the selected cable package.
    for item in price_list:

        if item.package == plan:

            try:

                # API users pay API price + API service charge.
                if user.category == 'API1' or user.category == 'API2' or user.category == 'API3':

                    price = int(item.api) + int(item.api_charge)

                else:

                    # Normal users pay normal price + normal service charge.
                    price = int(item.amount) + int(item.charge)

            except (TypeError, ValueError):

                # The package exists, but its pricing information
                # is invalid.
                return "INVALID_PRICE"

            break

    # The selected package does not exist.
    if price is None:

        return "INVALID_PLAN"

    # The calculated price must not be negative.
    if price < 0:

        return "INVALID_PRICE"

    with transaction.atomic():

        # Lock the user's wallet row before reading the balance.
        account = AppUser.objects.select_for_update().get(
            id=user.id
        )

        # Read the actual balance from the locked database row.
        bal = account.balance

        # Check whether the user's wallet can cover the total price.
        if bal < price:

            return False

        # Debit the already locked wallet row.
        account.balance -= price

        # Keep the balance rounded to two decimal places.
        account.balance = round(
            account.balance,
            2
        )

        account.save(
            update_fields=['balance']
        )

        # Calculate the balance after the successful debit.
        new_bal = account.balance

        # Create the initial wallet summary as Pending.
        working_wallet = Wallet_summary.objects.create(
            user=user,
            product=f"{plan} purchased to {iuc_number}",
            amount=price,
            previous_balance=bal,
            after_balance=new_bal,
            status="Pending"
        )

        # Create the initial transaction record as Pending.
        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,
            working_wallet
        )
# process tv
def pro_cess_tv(service, plan, iuc_number, user):

    files = Switch.objects.get(pk=1)

    # ---------------------------------------------------------
    # Select the active provider for the selected cable service.
    # ---------------------------------------------------------

    if service == "dstv":

        DSTV = files.dstv
        sell_tv = getattr(dstv, DSTV)

        item = Lockservice.objects.get(pk=2)
        price_list = Dstv.objects.all()

    elif service == "gotv":

        GOTV = files.gotv
        sell_tv = getattr(gotv, GOTV)

        item = Lockservice.objects.get(pk=3)
        price_list = Gotv.objects.all()

    elif service == "startimes":

        STARTIMES = files.startimes
        sell_tv = getattr(startimes, STARTIMES)

        item = Lockservice.objects.get(pk=4)
        price_list = Startimes.objects.all()

    else:

        data = {
            'message': 'Invalid cable service selected',
            'status': 'Unsuccessful'
        }

        datas = json.dumps(data)

        return HttpResponse(
            datas,
            content_type="application/json"
        )


    # ---------------------------------------------------------
    # Check whether the selected cable service is available.
    # ---------------------------------------------------------

    if item.availability != "ENABLE":

        data = {
            'message': "Sorry, this service is currently unavailable",
            'status': 'Unsuccessful'
        }

        datas = json.dumps(data)

        return HttpResponse(
            datas,
            content_type="application/json"
        )


    # ---------------------------------------------------------
    # Check the user's daily transaction limit.
    #
    # check_limit_cable() already handles:
    #
    # Normal users:
    #     amount + charge
    #
    # API users:
    #     API users bypass the transaction limit.
    # ---------------------------------------------------------

    exceed_limit = check_limit_cable(
        user,
        price_list,
        plan
    )


    # ---------------------------------------------------------
    # Handle invalid cable package.
    # ---------------------------------------------------------

    if exceed_limit == "INVALID_PLAN":

        data = {
            'message': 'The selected cable package is not available.',
            'status': 'Unsuccessful'
        }

        datas = json.dumps(data)

        return HttpResponse(
            datas,
            content_type="application/json"
        )


    # ---------------------------------------------------------
    # Handle invalid cable package pricing.
    # ---------------------------------------------------------

    if exceed_limit == "INVALID_PRICE":

        data = {
            'message': 'The selected cable package currently has invalid pricing information. Please try again later.',
            'status': 'Unsuccessful'
        }

        datas = json.dumps(data)

        return HttpResponse(
            datas,
            content_type="application/json"
        )


    # ---------------------------------------------------------
    # Handle daily transaction limit.
    # ---------------------------------------------------------

    if exceed_limit:

        data = {
            'message': 'Dear Customer, You Have Exceeded Your Daily Transaction Limit, Kindly Verify Your Account To Transact On The Platform Without Restrictions',
            'status': 'Unsuccessful'
        }

        datas = json.dumps(data)

        return HttpResponse(
            datas,
            content_type="application/json"
        )


    # ---------------------------------------------------------
    # Debit the user's wallet.
    #
    # tv_debit() handles:
    #
    # Normal users:
    #     amount + charge
    #
    # API users:
    #     api + api_charge
    #
    # It also creates the initial Pending Wallet_summary
    # and Pending Transact records.
    # ---------------------------------------------------------

    receipt = tv_debit(
        user,
        plan,
        price_list,
        iuc_number
    )


    # ---------------------------------------------------------
    # Handle invalid cable package returned by tv_debit().
    # ---------------------------------------------------------

    if receipt == "INVALID_PLAN":

        data = {
            'message': 'The selected cable package is not available.',
            'status': 'Unsuccessful'
        }

        datas = json.dumps(data)

        return HttpResponse(
            datas,
            content_type="application/json"
        )


    # ---------------------------------------------------------
    # Handle invalid pricing returned by tv_debit().
    # ---------------------------------------------------------

    if receipt == "INVALID_PRICE":

        data = {
            'message': 'The selected cable package currently has invalid pricing information. Please try again later.',
            'status': 'Unsuccessful'
        }

        datas = json.dumps(data)

        return HttpResponse(
            datas,
            content_type="application/json"
        )


    # ---------------------------------------------------------
    # Handle insufficient wallet balance.
    # ---------------------------------------------------------

    if receipt is False:

        data = {
            'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
            'status': 'Unsuccessful'
        }

        datas = json.dumps(data)

        return HttpResponse(
            datas,
            content_type="application/json"
        )


    # ---------------------------------------------------------
    # Get the values returned by tv_debit().
    # ---------------------------------------------------------

    old_bal = receipt[0]
    new_bal = receipt[1]
    price = receipt[2]
    working_trans = receipt[3]
    working_wallet = receipt[4]


    # ---------------------------------------------------------
    # Call the cable provider.
    #
    # IMPORTANT:
    # The external provider API call is intentionally NOT placed
    # inside transaction.atomic().
    #
    # This prevents a slow or unavailable provider API from
    # unnecessarily keeping a database transaction open.
    # ---------------------------------------------------------

    try:

        outcome = sell_tv(
            service=service,
            plan=plan,
            iuc_number=iuc_number,
            user=user
        )

    except Exception as e:

        # -----------------------------------------------------
        # If the provider throws an exception, the actual
        # transaction result is unknown.
        #
        # Therefore:
        #
        # - Do NOT refund automatically.
        # - Mark the transaction as Pending.
        # - Use the original transaction request ID so the
        #   transaction can be traced.
        # -----------------------------------------------------

        print("Cable provider error:", e)

        outcome = [
            "Transaction is pending. Please confirm your transaction status or contact support.",
            "Pending",
            working_trans.request_id
        ]


    # ---------------------------------------------------------
    # Extract the provider result.
    #
    # Provider functions should return:
    #
    # [message, status, request_id]
    # ---------------------------------------------------------

    message = outcome[0]
    status = outcome[1]
    request_id = outcome[2]


    # ---------------------------------------------------------
    # Final accounting stage.
    #
    # The refund, transaction update, wallet summary update,
    # and Sale record are handled inside one database
    # transaction.
    #
    # The provider API call has already completed above.
    # ---------------------------------------------------------

    with transaction.atomic():

        # -----------------------------------------------------
        # Refund the customer if the provider reports
        # "Unsuccessful".
        # -----------------------------------------------------

        if status == "Unsuccessful":

            # Restore the balance to what it was before
            # the original cable purchase.
            new_bal = old_bal

            user.fund(
                user.id,
                price
            )

            # Create a separate wallet summary record for
            # the refund.
            Wallet_summary.objects.create(
                user=user,
                product=f"{plan} purchased to {iuc_number} has been Refunded",
                amount=price,
                previous_balance=old_bal - price,
                after_balance=old_bal,
                status="Successful",
                request_id=working_trans.request_id
            )


        # -----------------------------------------------------
        # Update the original transaction record.
        # -----------------------------------------------------

        working_trans.transaction = message
        working_trans.status = status
        working_trans.request_id = request_id
        working_trans.new_balance = new_bal

        working_trans.save()


        # -----------------------------------------------------
        # Update the original wallet summary.
        # -----------------------------------------------------

        working_wallet.status = status

        working_wallet.save()


        # -----------------------------------------------------
        # Create the Sale record.
        # -----------------------------------------------------

        Sale.objects.create(
            user=user,
            network=service,
            plan=plan,
            status=status,
            cost=price,
            date=date.today().strftime("%Y-%m-%d"),
            request_id=request_id,
        )


    # ---------------------------------------------------------
    # Return the provider result to the frontend.
    # ---------------------------------------------------------

    data = {
        'message': message,
        'status': status
    }

    datas = json.dumps(data)

    return HttpResponse(
        datas,
        content_type="application/json"
    )

def check_limit_bill(user, service, amount):
    service_list = Electricity.objects.all()
    for item in service_list:
        if item.service == service:
            if user.category == 'API1' or user.category == 'API2' or user.category == 'API3':
                return False
            else:
                charges = int(item.discount)
                
            price = int(amount) + charges

    limit = trans_limit(user, price)
    return limit


def electric_debit(user, service, amount, meter_num):

    service_list = Electricity.objects.all()

    bal = user.balance

    price = None

    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)

            try:
                amount = int(amount)
            except (TypeError, ValueError):
                return False

            if amount <= 0:
                return False

            price = amount + charges
            break

    if price is None:
        return False

    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:

                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",
                )

                Wallet_summary.objects.create(
                    user=user,
                    product=f"{service} purhased to {meter_num}",
                    amount=price,
                    previous_balance=bal,
                    after_balance=new_bal,
                    status="Pending",
                    request_id=working_trans.request_id
                )

                return bal, new_bal, price, working_trans

    else:
        return False


# process electricity
def pro_cess_electricity(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":
        
        # CHECK TRANSACTION LIMIT 
        exceed_limit = check_limit_bill(user, service, amount)
        if exceed_limit:
            data = {'message': 'Dear Customer, You Have Exceeded Your Daily Transaction Limit, Kindly Verify Your Account To Transact On The Platform Without Restrictions', 'status': 'Unsuccessful'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
            
        receipt = electric_debit(user, service, amount, meter_num)

        if receipt is not False:
            working_trans = receipt[3]

            try:
                outcome = sell_electricity(
                    service=service,
                    amount=amount,
                    meter_num=meter_num,
                    user=user
                )
            except Exception as e:
                outcome = [
                    "Transaction is pending. Please confirm your transaction status or contact support.",
                    "Pending",
                    working_trans.request_id
                ]
        else:
            data = {
                'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                'status': 'Unsuccessful'
            }
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    else:
        data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")

    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

    Wallet_summary.objects.filter(
        user=user,
        request_id=working_trans.request_id
    ).update(
        status=outcome[1],
        request_id=outcome[2]
    )

    working_trans.request_id = outcome[2]
    working_trans.save()

    # ---------------------------------------------------------
    # SAVE ELECTRICITY TOKEN FOR RECEIPT
    # ---------------------------------------------------------

    # ---------------------------------------------------------
    # SAVE ELECTRICITY DELIVERY DATA
    # ---------------------------------------------------------

    if outcome[1] == "Successful":

        token = ""
        units = ""

        # -----------------------------------------------------
        # GET TOKEN
        #
        # Some existing providers return token at outcome[7].
        # MerryBills returns token at outcome[3].
        # Preserve support for both.
        # -----------------------------------------------------

        try:
            if len(outcome) > 7 and outcome[7]:
                token = outcome[7]
            elif len(outcome) > 3 and outcome[3]:
                token = outcome[3]
        except Exception:
            token = ""

        # -----------------------------------------------------
        # GET UNITS
        #
        # MerryBills returns units at outcome[4].
        # -----------------------------------------------------

        try:
            if len(outcome) > 4 and outcome[4]:
                units = outcome[4]
        except Exception:
            units = ""

        # -----------------------------------------------------
        # FALLBACK
        #
        # Some providers may include units only inside the
        # transaction message:
        #
        # "Successful ... Token: XXXXX, Units: 12.50"
        #
        # Extract units if they were not supplied separately.
        # -----------------------------------------------------

        if not units:

            try:
                message_text = str(outcome[0] or "")

                match = re.search(
                    r"\bUnits?\s*:\s*([0-9]+(?:\.[0-9]+)?)",
                    message_text,
                    re.IGNORECASE
                )

                if match:
                    units = match.group(1)

            except Exception:
                units = ""

        # -----------------------------------------------------
        # PREPARE RECEIPT DATA
        # -----------------------------------------------------

        delivery_payload = {
            "service": service,
            "meter_number": meter_num,
            "token": str(token or "").strip(),
            "units": str(units or "").strip(),
        }

        # -----------------------------------------------------
        # SAVE ONLY IF WE ACTUALLY HAVE DELIVERY DATA
        # -----------------------------------------------------

        if (
            delivery_payload["token"]
            or delivery_payload["units"]
        ):

            save_transaction_delivery(
                working_trans,
                "ELECTRICITY",
                delivery_payload
            )

    
    
def check_limit_exam(user, exam, quantity):

    # ---------------------------------------------------------
    # VALIDATE QUANTITY
    # ---------------------------------------------------------

    try:
        quantity = int(quantity)

    except (TypeError, ValueError):
        return True

    if quantity < 1:
        return True

    # ---------------------------------------------------------
    # FIND EXAM PRODUCT
    # ---------------------------------------------------------

    network_list = ResultPin.objects.all()

    price = None

    for item in network_list:

        if item.exam_type == exam:

            try:

                if user.category in ['API1', 'API2', 'API3']:
                    unit_price = float(item.api)

                else:
                    unit_price = float(item.price)

            except (TypeError, ValueError):
                return True

            # -------------------------------------------------
            # INVALID PRICE
            # -------------------------------------------------

            if unit_price < 0:
                return True

            price = unit_price * quantity

            break

    # ---------------------------------------------------------
    # EXAM TYPE DOES NOT EXIST
    # ---------------------------------------------------------

    if price is None:
        return True

    # ---------------------------------------------------------
    # CHECK DAILY TRANSACTION LIMIT
    # ---------------------------------------------------------

    limit = trans_limit(
        user,
        price
    )

    return limit
# =========================================================
# EXAM / RESULT PIN WALLET DEBIT
# =========================================================
def result_debit(user, exam_type, quantity):

    # ---------------------------------------------------------
    # VALIDATE QUANTITY
    # ---------------------------------------------------------

    try:
        quantity = int(quantity)
    except (TypeError, ValueError):
        return False

    if quantity < 1:
        return False

    # ---------------------------------------------------------
    # FIND EXAM PRODUCT
    # ---------------------------------------------------------

    network_list = ResultPin.objects.all()

    price = None

    for item in network_list:

        if item.exam_type == exam_type:

            try:
                if user.category in ['API1', 'API2', 'API3']:
                    unit_price = float(item.api)
                else:
                    unit_price = float(item.price)

            except (TypeError, ValueError):
                return False

            price = unit_price * quantity
            break

    # ---------------------------------------------------------
    # EXAM TYPE DOES NOT EXIST
    # ---------------------------------------------------------

    if price is None:
        return False

    # ---------------------------------------------------------
    # INVALID PRICE
    # ---------------------------------------------------------

    if price <= 0:
        return False

    # ---------------------------------------------------------
    # LOCK USER + CHECK LIMIT + DEBIT
    # ---------------------------------------------------------

    with transaction.atomic():

        # -----------------------------------------------------
        # LOCK USER ROW
        # -----------------------------------------------------

        account = AppUser.objects.select_for_update().get(
            id=user.id
        )

        # -----------------------------------------------------
        # CURRENT BALANCE
        # -----------------------------------------------------

        bal = float(account.balance)

        # -----------------------------------------------------
        # DAILY TRANSACTION LIMIT
        #
        # IMPORTANT:
        # The user row is locked before this check.
        # This serializes simultaneous transactions from
        # the same user.
        # -----------------------------------------------------

        today_date = date.today().strftime("%Y-%m-%d")

        config = Config.objects.get(pk=1)

        # -----------------------------------------------------
        # TRANSACTION LIMIT DISABLED
        # -----------------------------------------------------

        if config.set_transaction_limit:

            # -------------------------------------------------
            # VERIFIED USERS ARE NOT RESTRICTED
            # -------------------------------------------------

            if not account.verify:

                # ---------------------------------------------
                # GET USER CATEGORY LIMIT
                # ---------------------------------------------

                if account.category == 'EARNER':

                    limit = float(
                        config.earner_transaction_limit
                    )

                elif account.category == 'AFFILIATE':

                    limit = float(
                        config.affiliate_transaction_limit
                    )

                else:

                    limit = float(
                        config.ambassador_transaction_limit
                    )

                # ---------------------------------------------
                # COMPLETED/PENDING SALES FOR TODAY
                #
                # Wallet Funding is excluded.
                # ---------------------------------------------

                sales = Sale.objects.filter(
                    user=account,
                    date=today_date,
                    status__in=[
                        'Successful',
                        'Pending'
                    ]
                ).exclude(
                    plan='Wallet Funding'
                )

                # ---------------------------------------------
                # CALCULATE TODAY'S SALES
                # ---------------------------------------------

                today_sale = 0.0

                for sale in sales:

                    try:
                        today_sale += float(sale.cost)
                    except (TypeError, ValueError):
                        continue

                # ---------------------------------------------
                # ALSO COUNT EXISTING PENDING TRANSACTIONS
                #
                # This prevents another transaction from
                # bypassing the limit while the provider
                # request for a previous transaction is still
                # being processed.
                #
                # Only EXAM transactions are counted here
                # because this function is specifically used
                # for exam purchases.
                # ---------------------------------------------

                pending_transactions = Transact.objects.filter(
                    user=account,
                    status='Pending',
                    date=today_date,
                    value='EXAM'
                )

                pending_total = 0.0

                for pending in pending_transactions:

                    try:
                        pending_total += float(pending.cost)
                    except (TypeError, ValueError):
                        continue

                # ---------------------------------------------
                # CURRENT TRANSACTION ALREADY EXISTS IN
                # NEITHER TABLE, SO ADD ITS PRICE
                # ---------------------------------------------

                projected_total = (
                    today_sale
                    + pending_total
                    + price
                )

                if projected_total > limit:

                    return False

        # -----------------------------------------------------
        # CHECK CURRENT WALLET BALANCE
        # -----------------------------------------------------

        if bal < price:
            return False

        # -----------------------------------------------------
        # DEBIT WALLET
        # -----------------------------------------------------

        account.balance -= price

        account.balance = round(
            account.balance,
            2
        )

        account.save(
            update_fields=['balance']
        )

        # -----------------------------------------------------
        # BALANCE AFTER DEBIT
        # -----------------------------------------------------

        new_bal = account.balance

        # -----------------------------------------------------
        # CREATE WALLET SUMMARY
        # -----------------------------------------------------

        Wallet_summary.objects.create(
            user=account,
            product=f"{exam_type} PIN purchased",
            amount=price,
            previous_balance=bal,
            after_balance=new_bal,
            status="Pending"
        )

        # -----------------------------------------------------
        # CREATE PENDING TRANSACTION
        # -----------------------------------------------------

        working_trans = Transact.objects.create(
            email=account.email,
            user=account,
            transaction="Transaction Processing....",
            status="Pending",
            cost=price,
            old_balance=bal,
            new_balance=new_bal,
            phone_number=account.phoneNumber,
            d_network=exam_type,
            value="EXAM",
        )

        # -----------------------------------------------------
        # RETURN DEBIT INFORMATION
        # -----------------------------------------------------

        return (
            bal,
            new_bal,
            price,
            working_trans
        )
# =========================================================
# EXAM / RESULT PIN REFUND
# =========================================================

def result_refund(user, price, exam_type):

    # ---------------------------------------------------------
    # VALIDATE REFUND AMOUNT
    # ---------------------------------------------------------
    try:
        price = float(price)
    except (TypeError, ValueError):
        return False

    if price <= 0:
        return False

    # ---------------------------------------------------------
    # REFUND ATOMICALLY
    #
    # The user's wallet is locked before reading the current
    # balance. This is important because the customer may have
    # performed another transaction while the provider was
    # processing the exam PIN request.
    # ---------------------------------------------------------
    with transaction.atomic():

        account = AppUser.objects.select_for_update().get(
            id=user.id
        )

        # -----------------------------------------------------
        # READ ACTUAL CURRENT BALANCE
        # -----------------------------------------------------
        balance_before_refund = account.balance

        # -----------------------------------------------------
        # REFUND
        # -----------------------------------------------------
        account.balance += price

        account.balance = round(
            account.balance,
            2
        )

        account.save(
            update_fields=['balance']
        )

        # -----------------------------------------------------
        # BALANCE AFTER REFUND
        # -----------------------------------------------------
        balance_after_refund = account.balance

        # -----------------------------------------------------
        # RECORD REFUND
        # -----------------------------------------------------
        Wallet_summary.objects.create(
            user=user,
            product=f"{exam_type} PIN purchase refunded",
            amount=price,
            previous_balance=balance_before_refund,
            after_balance=balance_after_refund,
            status="Refunded"
        )

        return (
            balance_before_refund,
            balance_after_refund
        )


# =========================================================
# PROCESS RESULT / EXAM PIN PURCHASE
# =========================================================
def pro_cess_result(exam_type, quantity, phone, user):

    # ---------------------------------------------------------
    # GET ACTIVE RESULT PROVIDER
    # ---------------------------------------------------------

    try:

        files = Switch.objects.get(pk=1)

        RESULT = files.result

        sell_result = getattr(
            result,
            RESULT
        )

    except Exception:

        data = {
            "message": (
                "Sorry, result PIN service is currently "
                "unavailable"
            ),
            "status": "Unsuccessful"
        }

        return HttpResponse(
            json.dumps(data),
            content_type="application/json"
        )

    # ---------------------------------------------------------
    # VALIDATE QUANTITY
    # ---------------------------------------------------------

    try:

        quantity = int(quantity)

    except (TypeError, ValueError):

        data = {
            "message": "Invalid quantity.",
            "status": "Unsuccessful"
        }

        return HttpResponse(
            json.dumps(data),
            content_type="application/json"
        )

    if quantity < 1:

        data = {
            "message": "Quantity must be at least 1.",
            "status": "Unsuccessful"
        }

        return HttpResponse(
            json.dumps(data),
            content_type="application/json"
        )

    # ---------------------------------------------------------
    # CHECK SERVICE AVAILABILITY
    # ---------------------------------------------------------

    try:

        item = Lockservice.objects.get(pk=6)

    except Exception:

        data = {
            "message": (
                "Sorry, this service is currently unavailable"
            ),
            "status": "Unsuccessful"
        }

        return HttpResponse(
            json.dumps(data),
            content_type="application/json"
        )

    if item.availability != "ENABLE":

        data = {
            "message": (
                "Sorry, this service is currently unavailable"
            ),
            "status": "Unsuccessful"
        }

        return HttpResponse(
            json.dumps(data),
            content_type="application/json"
        )

    # ---------------------------------------------------------
    # DEBIT WALLET
    #
    # result_debit() performs the balance and transaction
    # limit protection.
    # ---------------------------------------------------------

    receipt = result_debit(
        user,
        exam_type,
        quantity
    )

    if receipt is False:

        data = {
            "message": (
                "Dear customer, your balance is insufficient, "
                "kindly fund your wallet"
            ),
            "status": "Unsuccessful"
        }

        return HttpResponse(
            json.dumps(data),
            content_type="application/json"
        )

    # ---------------------------------------------------------
    # TRANSACTION INFORMATION
    # ---------------------------------------------------------

    old_bal = receipt[0]
    new_bal = receipt[1]
    price = receipt[2]
    working_trans = receipt[3]

    # ---------------------------------------------------------
    # CALL RESULT PROVIDER
    # ---------------------------------------------------------

    try:

        outcome = sell_result(
            exam_type=exam_type,
            quantity=quantity,
            phone=phone
        )

    except Exception:

        outcome = [
            (
                "Transaction is pending. Please confirm your "
                "transaction status or contact support."
            ),
            "Pending",
            working_trans.request_id
        ]

    # ---------------------------------------------------------
    # VALIDATE PROVIDER RESPONSE
    # ---------------------------------------------------------

    if not isinstance(outcome, (list, tuple)):

        outcome = [
            (
                "Transaction is pending. Please confirm your "
                "transaction status or contact support."
            ),
            "Pending",
            working_trans.request_id
        ]

    if len(outcome) < 2:

        outcome = [
            (
                "Transaction is pending. Please confirm your "
                "transaction status or contact support."
            ),
            "Pending",
            working_trans.request_id
        ]

    # ---------------------------------------------------------
    # PROVIDER MESSAGE
    # ---------------------------------------------------------

    provider_message = str(
        outcome[0]
    )

    # ---------------------------------------------------------
    # PROVIDER STATUS
    # ---------------------------------------------------------

    provider_status = str(
        outcome[1]
    ).strip()

    # ---------------------------------------------------------
    # NORMALIZE STATUS
    # ---------------------------------------------------------

    if provider_status not in [
        "Successful",
        "Unsuccessful",
        "Pending"
    ]:

        provider_status = "Pending"

        provider_message = (
            "Transaction is pending. Please confirm your "
            "transaction status or contact support."
        )

    # ---------------------------------------------------------
    # UNSUCCESSFUL → REFUND
    # ---------------------------------------------------------

    if provider_status == "Unsuccessful":

        try:

            refund_result = result_refund(
                user,
                price,
                exam_type
            )

        except Exception as e:

            print(
                "Result PIN refund error:",
                e
            )

            refund_result = False

        # -----------------------------------------------------
        # REFUND FAILED
        # -----------------------------------------------------

        if refund_result is False:

            provider_status = "Pending"

            provider_message = (
                "Your transaction was unsuccessful, but the "
                "refund is currently pending. Please contact "
                "support if the refund is not reflected."
            )

            new_bal = receipt[1]

        # -----------------------------------------------------
        # REFUND SUCCESSFUL
        # -----------------------------------------------------

        else:

            new_bal = refund_result[1]

    # ---------------------------------------------------------
    # PENDING
    # ---------------------------------------------------------

    elif provider_status == "Pending":

        # Never automatically refund a pending provider request.

        new_bal = receipt[1]

    # ---------------------------------------------------------
    # SUCCESSFUL
    # ---------------------------------------------------------

    elif provider_status == "Successful":

        new_bal = receipt[1]

    # ---------------------------------------------------------
    # UNKNOWN STATUS
    # ---------------------------------------------------------

    else:

        provider_status = "Pending"

        provider_message = (
            "Your transaction is currently pending. "
            "Please confirm the transaction status later "
            "or contact support."
        )

        new_bal = receipt[1]

    # ---------------------------------------------------------
    # SAVE PROVIDER REQUEST ID
    # ---------------------------------------------------------

    provider_request_id = None

    if len(outcome) >= 3:

        provider_request_id = outcome[2]

        if provider_request_id:

            working_trans.request_id = provider_request_id

    # ---------------------------------------------------------
    # UPDATE TRANSACTION
    # ---------------------------------------------------------

    working_trans.transaction = provider_message
    working_trans.status = provider_status
    working_trans.new_balance = new_bal

    working_trans.save()

    # ---------------------------------------------------------
    # SAVE EXAM PIN DELIVERY DATA
    #
    # result_manual():
    #
    # outcome[3] = [
    #     {
    #         "exam": "WAEC",
    #         "pin": "...",
    #         "serial": "..."
    #     }
    # ]
    #
    # result_vtpass():
    #
    # outcome[3] = purchased PIN
    # ---------------------------------------------------------

    if provider_status == "Successful":

        delivery_data = None

        # -----------------------------------------------------
        # MANUAL PROVIDER
        # -----------------------------------------------------

        if (
            len(outcome) >= 4
            and isinstance(outcome[3], list)
        ):

            delivery_data = {
                "exam": str(exam_type).upper(),
                "pins": outcome[3]
            }

        # -----------------------------------------------------
        # VTPASS / OTHER PROVIDER RETURNING A SINGLE PIN
        # -----------------------------------------------------

        elif (
            len(outcome) >= 4
            and outcome[3]
        ):

            delivery_data = {
                "exam": str(exam_type).upper(),
                "pins": [
                    {
                        "pin": str(outcome[3]),
                        "serial": ""
                    }
                ]
            }

        # -----------------------------------------------------
        # SAVE DELIVERY DATA
        # -----------------------------------------------------

        if delivery_data:

            try:

                save_transaction_delivery(
                    working_trans,
                    "EXAM_PIN",
                    delivery_data
                )

            except Exception as e:

                # Do not change the successful transaction status
                # merely because receipt storage encountered an
                # application error. The transaction itself has
                # already been processed.
                print(
                    "Exam PIN delivery storage error:",
                    e
                )

    # ---------------------------------------------------------
    # CREATE SALE RECORD
    # ---------------------------------------------------------

    Sale.objects.create(
        user=user,
        network=exam_type,
        plan="Exam pin",
        status=provider_status,
        cost=price,
        date=date.today().strftime("%Y-%m-%d"),
        request_id=working_trans.request_id
    )

    # ---------------------------------------------------------
    # RETURN RESPONSE
    #
    # IMPORTANT:
    #
    # Keep the existing Flutter response contract.
    #
    # The Flutter application receives:
    #
    # {
    #     "message": "...",
    #     "status": "Successful"
    # }
    #
    # We do NOT expose the PIN in this response.
    # The website receipt obtains it securely from
    # TransactionDelivery.
    # ---------------------------------------------------------

    data = {
        "message": provider_message,
        "status": provider_status
    }

    return HttpResponse(
        json.dumps(data),
        content_type="application/json"
    )
# NEW UPDATE RECHARGE CARD PRINTING

def check_limit_card(user, network, amount,quantity):
    network_list = Airtime.objects.all()
    try:
        qs = len(Recharge_pin.objects.filter(network=network).filter(available=True).filter(amount=amount)[:quantity])
        # print(qs)
    except:
        qs = quantity
    
    for item in network_list:
        if item.network == network:
            disct = item.recharge_pin_discount
            price = (int(amount) - (disct / 100) * int(amount)) * int(qs)

    limit = trans_limit(user, price)
    return limit



def recharge_debit(user, network, amount, quantity):
    network_list = Airtime.objects.all()
    bal = user.balance
    try:
        qs = len(Recharge_pin.objects.filter(network=network).filter(available=True).filter(amount=amount)[:quantity])
        # print(qs)
    except:
        qs = quantity
    
    for item in network_list:
        if item.network == network:
            disct = item.recharge_pin_discount
            price = (int(amount) - (disct / 100) * int(amount)) * int(qs)
            # print(price)
    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} recharge card 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=network,
                value="RECHARGE PIN",
                )
                return bal, new_bal, price,working_trans
    else:
        return False


# process recharge card

def pro_cess_recharge(network, amount, quantity, user):
    # GET FILE
    files = Switch.objects.get(pk=1)
    CARD = files.recharge_card_printing
    sell_card = getattr(recharge_card, CARD)
    # END
        
    if int(amount) < 100:
        data = {'message': f'You cannot vend recharge card below 100 Naira', 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")

    item = Lockservice.objects.get(pk=7)
    if item.availability == "ENABLE":
        
        # CHECK TRANSACTION LIMIT 
        exceed_limit = check_limit_card(user, network, amount,quantity)
        if exceed_limit:
            data = {'message': 'Dear Customer, You Have Exceeded Your Daily Transaction Limit, Kindly Verify Your Account To Transact On The Platform Without Restrictions', 'status': 'Unsuccessful'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
        
        receipt = recharge_debit(user, network, amount, quantity)
        if receipt is not False:
            outcome = sell_card(network=network, amount=amount, quantity=quantity)
        else:
            data = {'message': 'Dear customer, your balance is insufficient, kindly fund your wallet',
                    'status': 'Unsuccessful'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    else:
        data = {'message': "Sorry, this service is currently unavailable", 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")


    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} recharge card 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=network,
        plan="Recharge Card",
        status=outcome[1],
        cost=price,
        date=date.today().strftime("%Y-%m-%d"),
    )
    data = {
        'message': outcome[0],
        'status': outcome[1],
        'request_id': working_trans.request_id,
    }
    datas = json.dumps(data)
    return HttpResponse(datas, content_type="application/json")





