from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib import messages
from django.template import Context
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes, force_str
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.db.models import Q
from .tokens import account_activation_token
import base64
import hmac,csv
import uuid
import hashlib
from .models import *
from .forms import *
from django.contrib.sessions.models import Session
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.forms import AuthenticationForm
from .whatsapp import WhatsApp
from .process import *
from .payment import autofund, crystalDynamic, atmfund, auth, crystal_autofund, monFund, online_fund, crystalVirtual, generate_acct, providusVirtual, payvesselVirtual, payvessel_fund,  payscribe_fund, payscribeVirtual,  paymentpointVirtual, paymentpoint_fund, palmpay_payment_done, getPalmpayAccountTest,getPalmpayAccount,palmpay_payment_done_dynamic
from .sales import sales_analysis, user_sales_analysis, get_trans
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt
import datetime
import requests
from .atuns import generator
from .proccess_api import  *
import json
from django.http import Http404
from django.contrib.auth.decorators import login_required
from .models import Transact, TransactionDelivery
from .services.notifications import (
    send_login_notification,
    send_welcome_email,
    send_activation_email,
    send_airtime_to_cash_admin_notification,
    send_manual_funding_admin_notification,
)

from . firebase_utils import subscribe_to_topic
from django.http import JsonResponse
from django.core.exceptions import ValidationError
from .forms import normalize_nigerian_phone


# Create your views here.


import logging
logger = logging.getLogger(__file__)


site_name = "Exactsub"




        



# Home Page
def home_page(request):
    return render(request=request, template_name='index.html')


# Privacy Page
def privacy_page(request):
    return render(request=request, template_name='privacyp.html')


# Privacy Page
def appdownload_page(request):
    return render(request=request, template_name='appdownload.html')

def public_privacy_policy(request):
    return render(request, "privacy_policy.html")

def public_terms_and_conditions(request):
    return render(request, "terms_and_conditions.html")

def public_waec_result_checker(request):
    return render(
        request,
        "public_result_checker.html",
    )

def about(request):
    return render(request, "about.html")

def public_neco_result_checker(request):
    return render(request, "public_neco_result_checker.html")

def _public_cable_provider_plans(model):
    """
    Build the public catalogue from the same cable TV tables
    used by the existing ExactSub cable service.

    API/internal pricing fields are intentionally not exposed.
    """
    rows = (
        model.objects
        .values("id", "package", "amount")
        .order_by("id")
    )

    plans = []

    for index, row in enumerate(rows):
        package = str(row["package"] or "").strip()

        if not package or row["amount"] is None:
            continue

        plans.append({
            "id": row["id"],
            "name": package,
            "price": int(row["amount"]),
            "duration": "1 Month",
            "popular": len(plans) == 0,
        })

    return plans


def _get_public_cable_catalogue():
    return {
        "dstv": _public_cable_provider_plans(Dstv),
        "gotv": _public_cable_provider_plans(Gotv),
        "startimes": _public_cable_provider_plans(Startimes),
    }


def public_cable_tv(request):
    cable_plans = _get_public_cable_catalogue()

    cable_plan_counts = {
        provider: len(plans)
        for provider, plans in cable_plans.items()
    }

    context = {
        "cable_plans": cable_plans,
        "cable_plan_counts": cable_plan_counts,
        "cable_total_plan_count": sum(cable_plan_counts.values()),
    }

    return render(
        request,
        "public_cable_tv.html",
        context,
    )

def public_electricity(request):
    rows = (
        Electricity.objects
        .values("name", "service")
        .order_by("name", "service")
    )

    electricity_providers = []
    seen = set()

    for row in rows:
        name = str(row["name"] or "").strip()
        service = str(row["service"] or "").strip()

        if not name and not service:
            continue

        key = service.lower() or name.lower()

        if key in seen:
            continue

        seen.add(key)

        display_name = name or service
        code = service.upper() if service else display_name[:5].upper()

        electricity_providers.append({
            "name": display_name,
            "service": service,
            "code": code[:8],
        })

    context = {
        "electricity_providers": electricity_providers,
        "electricity_provider_count": len(electricity_providers),
    }

    return render(
        request,
        "public_electricity.html",
        context,
    )

def public_cac_registration(request):
    return render(
        request,
        "cac_registration.html",
    )


def user_cac_registration(request):
    table = Config.objects.get(pk=1)

    context = {
        "current_user": request.user,
        "table": table,
        "site_name": site_name,
    }

    return render(
        request,
        "user_cac_registration.html",
        context,
    )


# ============================================================
# MTN PUBLIC DATA PLAN CATEGORY
# ============================================================

def _mtn_plan_category(validity):
    """
    Convert the database validity text into a category
    used by the public MTN Direct Gifting filters.
    """

    value = str(validity or "").strip().lower()

    # Daily
    if (
        "24 hour" in value
        or "24 hours" in value
        or "1 day" in value
        or "1-day" in value
        or "daily" in value
    ):
        return "daily"

    # 2 Days
    if (
        "2 day" in value
        or "2-day" in value
        or "2 days" in value
        or "48 hour" in value
        or "48 hours" in value
    ):
        return "2-day"

    # 2 Weeks / 14 Days
    if (
        "14 day" in value
        or "14 days" in value
        or "2 week" in value
        or "2-week" in value
        or "2 weeks" in value
    ):
        return "2-week"

    # Weekly / 7 Days
    if (
        "7 day" in value
        or "7 days" in value
        or "1 week" in value
        or "1-week" in value
        or "weekly" in value
    ):
        return "weekly"

    # 2 Months / 60 Days
    if (
        "60 day" in value
        or "60 days" in value
        or "2 month" in value
        or "2-month" in value
        or "2 months" in value
    ):
        return "2-month"

    # 3 Months / 90 Days
    if (
        "90 day" in value
        or "90 days" in value
        or "3 month" in value
        or "3-month" in value
        or "3 months" in value
    ):
        return "3-month"

    # Yearly / 365 Days
    if (
        "365 day" in value
        or "365 days" in value
        or "12 month" in value
        or "12 months" in value
        or "1 year" in value
        or "1-year" in value
        or "yearly" in value
        or "annual" in value
    ):
        return "yearly"

    # Monthly / 30 Days
    if (
        "30 day" in value
        or "30 days" in value
        or "1 month" in value
        or "1-month" in value
        or "1 months" in value
        or "monthly" in value
    ):
        return "monthly"

    return "other"


# ============================================================
# GET PUBLIC MTN PLANS
# ============================================================

def _get_public_mtn_plans():
    """
    Return only the two MTN services exposed on the
    public MTN data catalogue:

        1. MTN DataShare
        2. MTN Direct Gifting

    Other MTN services such as SME, Awoof Gifting,
    MTN Gifting and Direct Coupon are deliberately excluded.
    """

    sources = (
        (
            10,
            "MTN DataShare",
            "datashare",
            Mtndatashare,
        ),
        (
            11,
            "MTN Direct Gifting",
            "direct-gifting",
            Mtndirectgifting,
        ),
    )

    # Only include services whose corresponding lock
    # is currently ENABLED.
    lock_ids = [
        lock_id
        for lock_id, _, _, _ in sources
    ]

    enabled_ids = set(
        Lockdata.objects.filter(
            pk__in=lock_ids,
            availability="ENABLE",
        ).values_list(
            "pk",
            flat=True,
        )
    )

    mtn_plans = []

    for (
        lock_id,
        plan_type,
        plan_group,
        model,
    ) in sources:

        if lock_id not in enabled_ids:
            continue

        rows = (
            model.objects
            .values(
                "id",
                "volume",
                "amount",
                "validity",
            )
            .order_by(
                "amount",
                "id",
            )
        )

        for row in rows:

            # Ignore incomplete records.
            if not row["volume"]:
                continue

            if row["amount"] is None:
                continue

            validity = row["validity"] or ""

            mtn_plans.append(
                {
                    "id": row["id"],
                    "volume": row["volume"],
                    "amount": row["amount"],
                    "validity": validity,

                    "plan_type": plan_type,
                    "plan_group": plan_group,

                    # Category is mainly used by
                    # MTN Direct Gifting filters.
                    "category": _mtn_plan_category(
                        validity
                    ),
                }
            )

    # Cheapest first.
    mtn_plans.sort(
        key=lambda item: (
            float(item["amount"] or 0),
            str(item["volume"]),
            str(item["plan_type"]),
        )
    )

    return mtn_plans


# ============================================================
# PUBLIC MTN DATA PAGE
# ============================================================

def public_mtn_data(request):

    mtn_plans = _get_public_mtn_plans()

    datashare_plans = [
        plan
        for plan in mtn_plans
        if plan["plan_group"] == "datashare"
    ]

    direct_gifting_plans = [
        plan
        for plan in mtn_plans
        if plan["plan_group"] == "direct-gifting"
    ]

    lowest_price = min(
        (
            float(plan["amount"])
            for plan in mtn_plans
            if plan["amount"] is not None
        ),
        default=0,
    )

    featured_plan = (
        mtn_plans[0]
        if mtn_plans
        else None
    )

    context = {
        "mtn_plans": mtn_plans,

        "mtn_plan_count": len(mtn_plans),

        "mtn_datashare_count": len(
            datashare_plans
        ),

        "mtn_direct_gifting_count": len(
            direct_gifting_plans
        ),

        "mtn_lowest_price": lowest_price,

        "mtn_featured_plan": featured_plan,
    }

    return render(
        request,
        "public_mtn_data.html",
        context,
    )



def _glo_plan_category(validity):
    """
    Convert GLO validity text into the public-page filter category.
    """

    value = str(validity or "").strip().lower()

    if "24 hour" in value or "1 day" in value:
        return "gifting-daily"

    if "2 day" in value or "48 hour" in value:
        return "gifting-2-day"

    if "14 day" in value or "2 week" in value:
        return "gifting-2-week"

    if "7 day" in value or "1 week" in value or "weekly" in value:
        return "gifting-weekly"

    if "60 day" in value or "2 month" in value:
        return "gifting-2-month"

    if "90 day" in value or "3 month" in value:
        return "gifting-3-month"

    if (
        "365 day" in value
        or "12 month" in value
        or "1 year" in value
        or "yearly" in value
    ):
        return "gifting-yearly"

    if "30 day" in value or "1 month" in value or "monthly" in value:
        return "gifting-monthly"

    return "gifting-other"


def public_glo_data(request):
    """
    Public, SEO-indexable GLO data page.

    This view only reads the existing GLO catalogue.
    It does not call a provider API and does not modify
    transactions, balances or purchase logic.
    """

    sources = (
        (6, "Glo Corporate Gifting", Glocgdata, "cg"),
        (5, "Glo Gifting", Glodata, "gifting"),
    )

    lock_ids = [lock_id for lock_id, _, _, _ in sources]

    enabled_ids = set(
        Lockdata.objects.filter(
            pk__in=lock_ids,
            availability="ENABLE",
        ).values_list(
            "pk",
            flat=True
        )
    )

    glo_plans = []

    for lock_id, plan_type, model, plan_type_code in sources:

        if lock_id not in enabled_ids:
            continue

        rows = (
            model.objects
            .values(
                "id",
                "volume",
                "amount",
                "validity",
            )
            .order_by(
                "amount",
                "id"
            )
        )

        for row in rows:

            if row["amount"] is None:
                continue

            if plan_type_code == "cg":

                category = "cg"

            else:

                category = _glo_plan_category(
                    row["validity"]
                )

            glo_plans.append({
                "id": row["id"],
                "volume": row["volume"],
                "amount": row["amount"],
                "validity": row["validity"],
                "plan_type": plan_type,
                "type": plan_type_code,
                "category": category,
            })

    # Keep CG first, then Gifting.
    # Within each group, show cheaper plans first.
    glo_plans.sort(
        key=lambda item: (
            0 if item["type"] == "cg" else 1,
            float(item["amount"] or 0),
            str(item["volume"] or ""),
        )
    )

    glo_cg_plans = [
        plan
        for plan in glo_plans
        if plan["type"] == "cg"
    ]

    glo_gifting_plans = [
        plan
        for plan in glo_plans
        if plan["type"] == "gifting"
    ]

    featured_plan = (
        glo_cg_plans[0]
        if glo_cg_plans
        else (
            glo_gifting_plans[0]
            if glo_gifting_plans
            else None
        )
    )

    lowest_price = min(
        (
            float(plan["amount"])
            for plan in glo_plans
            if plan["amount"] is not None
        ),
        default=0,
    )

    context = {
        "glo_plans": glo_plans,

        "glo_plan_count": len(glo_plans),

        "glo_cg_plan_count": len(glo_cg_plans),

        "glo_gifting_plan_count": len(glo_gifting_plans),

        "glo_featured_plan": featured_plan,

        "glo_lowest_price": lowest_price,
    }

    return render(
        request,
        "public_glo_data.html",
        context
    )


# ============================================================
# PUBLIC AIRTEL DATA PAGE
# ============================================================

def _airtel_plan_category(validity):
    """Map Airtel validity text to a public-page filter category."""

    value = str(validity or "").strip().lower()

    if "24 hour" in value or "1 day" in value or "daily" in value:
        return "daily"

    if "2 day" in value or "48 hour" in value:
        return "two-day"

    if "7 day" in value or "1 week" in value or "weekly" in value:
        return "weekly"

    if "30 day" in value or "1 month" in value or "monthly" in value:
        return "monthly"

    if any(term in value for term in (
        "60 day",
        "90 day",
        "120 day",
        "180 day",
        "365 day",
        "2 month",
        "3 month",
        "6 month",
        "12 month",
        "1 year",
        "2 year",
        "yearly",
    )):
        return "long-term"

    return "special"


def _get_public_airtel_plans():
    """Read the Airtel catalogue and prepare public-page data."""

    plans = (
        Airteldata.objects
        .values(
            "id",
            "volume",
            "amount",
            "validity",
        )
        .order_by("amount", "id")
    )

    airtel_plans = []

    for plan in plans:

        if not plan["volume"] or plan["amount"] is None:
            continue

        validity = plan["validity"] or ""

        airtel_plans.append({
            "id": plan["id"],
            "volume": plan["volume"],
            "amount": plan["amount"],
            "validity": validity,
            "type": "Airtel Data",
            "category": _airtel_plan_category(validity),
        })

    return airtel_plans


def public_airtel_data(request):
    """
    Public, SEO-indexable Airtel data catalogue page.

    Django renders the plan cards directly in the HTML.
    JavaScript is used only for UI interactions and filtering.
    """

    airtel_plans = _get_public_airtel_plans()

    lowest_price = min(
        (
            float(plan["amount"])
            for plan in airtel_plans
            if plan["amount"] is not None
        ),
        default=0,
    )

    context = {
        "airtel_plans": airtel_plans,
        "airtel_plan_count": len(airtel_plans),
        "airtel_lowest_price": lowest_price,
    }

    return render(
        request,
        "public_airtel_data.html",
        context,
    )



def _9mobile_plan_category(validity):
    """
    Convert the database validity text into a category
    used by the public 9mobile data catalogue.
    """

    value = str(validity or "").strip().lower()

    # Daily
    if (
        "24 hour" in value
        or "1 day" in value
        or "daily" in value
    ):
        return "daily"

    # 2-Day
    if (
        "2 day" in value
        or "48 hour" in value
    ):
        return "two-day"

    # Weekly
    if (
        "7 day" in value
        or "1 week" in value
        or "weekly" in value
    ):
        return "weekly"

    # Monthly
    if (
        "30 day" in value
        or "1 month" in value
        or "monthly" in value
    ):
        return "monthly"

    # Long-term
    if any(
        term in value
        for term in (
            "60 day",
            "90 day",
            "120 day",
            "180 day",
            "365 day",
            "2 month",
            "3 month",
            "6 month",
            "12 month",
            "1 year",
            "2 year",
            "yearly",
        )
    ):
        return "long-term"

    # Anything that doesn't fit the
    # standard validity categories.
    return "special"


def _get_public_9mobile_plans():
    """
    Retrieve the public 9mobile catalogue.

    The database remains the source of truth.
    """

    plans = (
        Mobiledata.objects
        .values(
            "id",
            "volume",
            "amount",
            "validity",
        )
        .order_by(
            "amount",
            "id",
        )
    )

    mobile_plans = []

    for plan in plans:

        if (
            not plan["volume"]
            or plan["amount"] is None
        ):
            continue

        validity = plan["validity"] or ""

        mobile_plans.append({
            "id": plan["id"],
            "volume": plan["volume"],
            "amount": plan["amount"],
            "validity": validity,
            "type": "9mobile Data",
            "category": _9mobile_plan_category(
                validity
            ),
        })

    return mobile_plans


def public_9mobile_data(request):
    """
    Public, SEO-indexable 9mobile data catalogue.

    Plans are rendered by Django so search engines can
    see the actual plan names, prices and validity.
    """

    mobile_plans = _get_public_9mobile_plans()

    lowest_price = min(
        (
            float(plan["amount"])
            for plan in mobile_plans
            if plan["amount"] is not None
        ),
        default=0,
    )

    context = {
        "mobile_plans": mobile_plans,
        "mobile_plan_count": len(mobile_plans),
        "mobile_lowest_price": lowest_price,
    }

    return render(
        request,
        "public_9mobile_data.html",
        context,
    )


def public_airtime(request):
    rows = (
        Airtime.objects
        .values("network", "discount")
        .order_by("network")
    )

    airtime_networks = []
    seen = set()

    for row in rows:
        network = str(row["network"] or "").strip()
        if not network:
            continue

        # Keep one public entry per network.
        network_key = (
            network.lower()
            .replace(" ", "")
            .replace("-", "")
            .replace("_", "")
        )

        if network_key in seen:
            continue

        seen.add(network_key)

        try:
            discount = float(row["discount"] or 0)
        except (TypeError, ValueError):
            discount = 0

        airtime_networks.append({
            "network": network,
            "network_key": network_key,
            "discount": discount,
        })

    context = {
        "airtime_networks": airtime_networks,
        "airtime_network_count": len(airtime_networks),
    }

    return render(
        request,
        "public_airtime.html",
        context,
    )


#  BASIC AUTH CODE


import base64
import binascii

from functools import wraps
from django.contrib.auth import authenticate, login
from django.http import HttpResponse


def view_or_basicauth(view, request, test_func, realm="", *args, **kwargs):
    """
    Require an authenticated Django user or valid HTTP Basic credentials.

    Supports existing Django sessions and programmatic Basic Authentication.
    """

    if test_func(request.user):
        return view(request, *args, **kwargs)

    authorization = request.META.get("HTTP_AUTHORIZATION", "")
    parts = authorization.split(None, 1)

    if len(parts) == 2 and parts[0].lower() == "basic":

        try:
            decoded = base64.b64decode(
                parts[1],
                validate=True
            ).decode("utf-8")

            username, separator, password = decoded.partition(":")

            if not separator or not username:
                raise ValueError("Invalid Basic Authentication credentials.")

            user = authenticate(
                request=request,
                username=username,
                password=password
            )

            if user is not None and user.is_active:
                login(request, user)
                return view(request, *args, **kwargs)

        except (
            ValueError,
            UnicodeDecodeError,
            binascii.Error
        ):
            pass

    response = HttpResponse(
        "Authentication required.",
        status=401
    )

    response["WWW-Authenticate"] = (
        f'Basic realm="{realm}", charset="UTF-8"'
    )

    return response


def logged_in_or_basicauth(realm=""):

    def view_decorator(func):

        @wraps(func)
        def wrapper(request, *args, **kwargs):

            return view_or_basicauth(
                func,
                request,
                lambda user: user.is_authenticated,
                realm,
                *args,
                **kwargs
            )

        return wrapper

    return view_decorator


view_decorator = logged_in_or_basicauth(realm="")




# END OF BASIC AUTH CODE

def request_id_gen():
        # Request ID generator
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        tok = uuid.uuid4()
        token = tok.hex
        req = the_date + token
        request_id = req[0:25]
        return request_id





# PIN CODE STARTS HERE
def set_pin(request):
    if request.method == "POST":
        form = PinForm(request.POST)
        if form.is_valid():
            form.clean()
            user = request.user
            firstPin = form.cleaned_data.get('pin')
            user.transaction_pin = firstPin
            user.save()
            
            data = {'message': 'Pin Set Successfully', 'status': "Successful"}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")

        data = {'message': 'Make sure you have inputed the same pin in both fields and it all digit', 'status': "fail"}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")
    else:
        form = PinForm()
    context = {"form": form}
    return render(request=request, template_name="transPin.html", context=context)

@view_decorator
def set_pin_app(request):
    pin = request.GET.get('pin')
    confirm = request.GET.get('confirm_pin')
    user = request.user
    if confirm == pin:
        if pin.isdigit():
            if len(pin) == 5:
                user.transaction_pin = pin
                user.save()
                data = {'message': 'Pin Set Successfully', 'status': "Successful"}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            else:
                data = {'message': 'Only 5 digit pin allowed', 'status': "Unsuccessful"}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json", status=400)
        else:
            data = {'message': 'Only Numbers Allowed!', 'status': "Unsuccessful"}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json", status=400)
    else:
        data = {'message': 'Pin Does Not Match!', 'status': "Unsuccessful"}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json", status=400)


@view_decorator
def change_pin_app(request):
    user = request.user
    oldpin = request.GET.get('old_pin')
    newpin = request.GET.get('new_pin')
    if user.transaction_pin == oldpin:
        if newpin.isdigit():
            if len(newpin) == 5:
                user.transaction_pin = newpin
                user.save()
                data = {'message': 'Pin Set Successfully', 'status': "Successful"}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            else:
                data = {'message': 'Only 5 digit pin allowed', 'status': "Unsuccessful"}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json", status=400)
        else:
            data = {'message': 'Only Numbers Allowed!', 'status': "Unsuccessful"}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json", status=400)
    else:
        data = {'message': 'Incorrect Old Pin', 'status': "Unsuccessful"}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json", status=400)

              

@view_decorator
def reset_pin_app(request):
    user = request.user
    password = request.GET.get('password')
    newpin = request.GET.get('new_pin')
    check_user = authenticate(username=user.username, password=password)
    if check_user is not None:
        if newpin.isdigit():
            if len(newpin) == 5:
                user.transaction_pin = newpin
                user.save()
                data = {'message': 'Pin Set Successfully', 'status': "Successful"}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            else:
                data = {'message': 'Only 5 digit pin allowed', 'status': "Unsuccessful"}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json", status=400)
        else:
            data = {'message': 'Only Numbers Allowed!', 'status': "Unsuccessful"}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json", status=400)
    else:
        data = {'message': 'Incorrect Password', 'status': "Unsuccessful"}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json", status=400)
                



from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate
from django.http import HttpResponse
from django.shortcuts import render
import json


from django.contrib.auth import authenticate
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render
import json


@login_required
def change_pin(request):

    refree = request.GET.get("demand")

    print(refree)

    # =========================================================
    # CHANGE TRANSACTION PIN
    # =========================================================

    if (
        request.method == "POST"
        and "old_pin" in request.POST
    ):

        form = ChangePinForm(request.POST)

        if form.is_valid():

            user = request.user

            old_pin = form.cleaned_data.get(
                "old_pin"
            )

            new_pin = form.cleaned_data.get(
                "new_pin"
            )

            # -------------------------------------------------
            # CHECK OLD TRANSACTION PIN
            # -------------------------------------------------

            if user.transaction_pin != old_pin:

                data = {
                    "message": (
                        "The old transaction PIN "
                        "you entered is incorrect."
                    ),
                    "status": "Unsuccessful"
                }

                return HttpResponse(
                    json.dumps(data),
                    content_type="application/json"
                )

            # -------------------------------------------------
            # UPDATE TRANSACTION PIN
            # -------------------------------------------------

            user.transaction_pin = new_pin

            user.save(
                update_fields=[
                    "transaction_pin"
                ]
            )

            data = {
                "message": (
                    "Your transaction PIN "
                    "has been changed successfully."
                ),
                "status": "Successful"
            }

            return HttpResponse(
                json.dumps(data),
                content_type="application/json"
            )

        # -----------------------------------------------------
        # FORM VALIDATION ERROR
        # -----------------------------------------------------

        errors = []

        for field_errors in form.errors.values():

            for error in field_errors:

                errors.append(
                    str(error)
                )

        if errors:

            message = " ".join(errors)

        else:

            message = (
                "Please check your PIN details "
                "and try again."
            )

        data = {
            "message": message,
            "status": "Unsuccessful"
        }

        return HttpResponse(
            json.dumps(data),
            content_type="application/json"
        )


    # =========================================================
    # RESET TRANSACTION PIN
    # =========================================================

    elif (
        request.method == "POST"
        and "password" in request.POST
    ):

        form = ResetPinForm(request.POST)

        if form.is_valid():

            user = request.user

            username = user.username

            password = form.cleaned_data.get(
                "password"
            )

            new_pin = form.cleaned_data.get(
                "pin"
            )

            # -------------------------------------------------
            # VERIFY ACCOUNT PASSWORD
            # -------------------------------------------------

            check_user = authenticate(
                username=username,
                password=password
            )

            if check_user is None:

                data = {
                    "message": (
                        "The password you entered "
                        "is incorrect."
                    ),
                    "status": "Unsuccessful"
                }

                return HttpResponse(
                    json.dumps(data),
                    content_type="application/json"
                )

            # -------------------------------------------------
            # RESET TRANSACTION PIN
            # -------------------------------------------------

            user.transaction_pin = new_pin

            user.save(
                update_fields=[
                    "transaction_pin"
                ]
            )

            data = {
                "message": (
                    "Your transaction PIN "
                    "has been reset successfully."
                ),
                "status": "Successful"
            }

            return HttpResponse(
                json.dumps(data),
                content_type="application/json"
            )

        # -----------------------------------------------------
        # FORM VALIDATION ERROR
        # -----------------------------------------------------

        errors = []

        for field_errors in form.errors.values():

            for error in field_errors:

                errors.append(
                    str(error)
                )

        if errors:

            message = " ".join(errors)

        else:

            message = (
                "Please check your PIN details "
                "and try again."
            )

        data = {
            "message": message,
            "status": "Unsuccessful"
        }

        return HttpResponse(
            json.dumps(data),
            content_type="application/json"
        )


    # =========================================================
    # NORMAL PAGE LOAD
    # =========================================================

    else:

        form = ChangePinForm()

        form2 = ResetPinForm()


    context = {
        "form": form,
        "form2": form2
    }

    return render(
        request,
        "changepin.html",
        context
    )


@view_decorator
def checkpin(request):
    pin = request.GET.get('pin')

    if request.user.transaction_pin == pin:
        stat = True
    else:
        stat = False

    data = {
        'status': stat
    }

    datas = json.dumps(data)

    return HttpResponse(
        datas,
        content_type="application/json"
    )

# END OF PIN CODE



def user_details(request):
    load = request.GET.get('username')
    try:
        the_user = AppUser.objects.get(username=load)
        table = Config.objects.get(pk=1)
        ref_list = Bonus.objects.filter(referer=the_user.username).all()
        num_of_ref = len(ref_list)
        user_account = []
        gateway_disable = PaymentGatewayDisable.objects.get(pk=1)
        
        if the_user.securewave_accounts and gateway_disable.securewave == "ENABLE":
            crystal = json.loads(the_user.securewave_accounts)
            crystalpay = {
                "accounts": [
                    {
                    "bankName": crystal['accounts'][0]["account_bank"],
                    "accountName": crystal['accounts'][0]["account_name"],
                    "accountNumber": crystal['accounts'][0]["account_number"],
                    }
                    ]
            }
            if table.securewave_percent:
                charge = f"{table.securewave_percent}%"
            else:
                charge = f"N{table.securewave_charges}"
            crystal_dict = {
                'provider_source': 'Securewave',
                'bank_details': crystalpay['accounts'],
                'charges': charge,
            }
            user_account.append(crystal_dict)
        
        # if the_user.palmpay_account and gateway_disable.palmpay == "ENABLE":
        #     palmpay = json.loads(the_user.palmpay_account)
        #     palmpay_dict = {
        #         'provider_source': 'Palmpay',
        #         'bank_details':palmpay['accounts'],
        #         'charges': "0.9%",
        #     }
        #     user_account.append(palmpay_dict)
        
        if the_user.paymentpoint_accounts and gateway_disable.paymentpoint == "ENABLE":
            paymentpoint = json.loads(the_user.paymentpoint_accounts)
            paymentpoint_dict = {
                'provider_source': 'Paymentpoint',
                'bank_details': paymentpoint['accounts'],
                'charges': "No Charges",
            }
            user_account.append(paymentpoint_dict)
            
        
        if the_user.payvessel_accounts and gateway_disable.payvessel == "ENABLE":
            payvessel = json.loads(the_user.payvessel_accounts)
            payvessel_dict = {
                'provider_source': 'Payvessel',
                'bank_details': payvessel['accounts'],
                'charges': "No Charges",
            }
            user_account.append(payvessel_dict)
        
        
        if the_user.monnify_accounts and gateway_disable.monnify == "ENABLE":
            monnify = json.loads(the_user.monnify_accounts)
            if table.monnify_percent:
                charge = f"{table.monnify_percent}%"
            else:
                charge = f"N{table.monnify_charges}"
            monnify_dict = {
                'provider_source': 'Monnify',
                'bank_details': monnify['accounts'],
                'charges': charge,
            }
            user_account.append(monnify_dict)
            
        data = {'username': the_user.username, 'email_verified': the_user.email_verify, 'balance': the_user.balance, 'user_id': the_user.id, 'first_name': the_user.firstName, 'last_name': the_user.lastName, 'email': the_user.email, 'referer_bonus': the_user.bonus,'number_of_referers': num_of_ref,'referral_link': f'https://exactsub.com/register?referer={the_user.username}',  'status': 'Successful','accounts': user_account, 'notification': table.pop_message,'refer_note': table.refer_note,'bot_link': 'https://wa.me/2349063993606'}
    except:
        data = {'message': "Invalid User", 'status': 'Unsuccessful'}
        
    datas = json.dumps(data)
    return HttpResponse(datas, content_type="application/json")
    
    
    

@view_decorator
def user_transactionapp(request):
    current_user = request.user
    array = Transact.objects.filter(email=current_user.email).all()
    the_list = []

    for n in array:
        if n.user == current_user:

            # CUSTOMER-FACING MOBILE TRANSACTION MESSAGE
            api_response = n.transaction

            if (
                n.value == "DATA"
                and n.status == "Unsuccessful"
            ):
                api_response = (
                    "Transaction failed. If your wallet was debited, "
                    "your refund will be processed automatically."
                )

            load = {
                'username': current_user.username,
                'status': n.status,
                'network': n.d_network,
                'cost': n.cost,
                'previous_balance': n.old_balance,
                'after_balance': n.new_balance,
                'phone_number': n.phone_number,
                'api_response': api_response,
                'date': n.date
            }

            the_list.append(load)

    x = the_list[::-1]

    if x is None or x == []:
        data = {'transactions': 'No transactions found'}

    elif len(x) < 20:
        data = {'transactions': x}

    else:
        data = {'transactions': x[:20]}

    datas = json.dumps(data)

    return HttpResponse(
        datas,
        content_type="application/json"
    )


def register_request(request):
    referer = request.GET.get('referer')
    print(referer)
    if request.method == "POST":
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.clean()
            user = form.save()
            if referer:
                Bonus.objects.create(email=request.POST['email'], referer=referer)
            try:
                send_welcome_email(user)
            except:
                pass

            try:
                current_site = get_current_site(request)
                send_activation_email(user, current_site.domain)
            except:
                pass
            messages.add_message(request, messages.SUCCESS, "Registration Successful. Welcome to ExactSub. A Welcome Email has been sent to your inbox, you can now login and enjoy our services, thanks.")
            return redirect("login")
        messages.add_message(request, messages.ERROR, "Unsuccessful registration. Invalid information.")
    else:
        form = RegistrationForm()
    context = {"form": form}
    return render(request=request, template_name="register.html", context=context)


# APP REGISTER
@csrf_exempt
@require_POST
def register_app(request):
    if request.method == "POST":
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.clean()
            user = form.save()
            
            try:
                send_welcome_email(user)
            except:
                pass
            
            data = {'message': "User Successfully Registered", 'status': 'Successful'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
            
            
        else:
            errors_json = json.loads(form.errors.as_json())
            errorDict = {k: v[0]['message'] for k,v in errors_json.items()}
            errorList = [k + ': ' + v for k,v in errorDict.items()]
            ''.join(errorList)
            data = {'message': errorList, 'status': 'Unsuccessful'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json", status=400)
            



# APP LOGIN

@csrf_exempt
@require_POST
def login_app(request):
    if request.method == "POST":
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                fund_bonus(user)
                
                
                if not user.paymentpoint_accounts and user.bvn:
                    try:
                        paymentpointVirtual(user)
                    except:
                        pass
                
                if not user.securewave_accounts and user.bvn:
                    try:
                        crystalVirtual(user, "1")
                        
                    except:
                        pass
                    
                # if not user.monnify_accounts and user.bvn:
                #     try:
                #         generate_acct(user)
                #     except:
                #         pass
                    
                # if not user.palmpay_account and user.bvn:
                #     try:
                #         getPalmpayAccount(user)
                #     except:
                #         pass
                    
                # if not user.payvessel_accounts and user.bvn:
                    
                #     try:
                #         payvesselVirtual(user)
                #     except:
                #         pass
                    
                
                #remove cur user all sessions
                sessionids = Usersession.objects.filter(user=request.user).first()
                if sessionids != None:
                    sessionidsToDelete = sessionids.stored_key
                    sessions = Session.objects.filter(session_key=sessionidsToDelete)
                    for session in sessions:
                        session.delete()
                        
                    store = Usersession.objects.filter(stored_key=sessionidsToDelete)
                    for session in store:
                        session.delete()
                    request.session.save()
                Usersession.objects.get_or_create(
                    user=user,
                    stored_key=request.session.session_key)
                # End of sessions removal
                try:
                    send_login_notification(user)
                except:
                    pass

                data = {'message': "Login Successful", 'status': 'Successful'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            else:
                data = {'message': "Invalid username or password.", 'status': 'Unsuccessful'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        else:
            data = {'message': "Invalid username or password.", 'status': 'Unsuccessful'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    
    


# FUND REFERRAL BONUS
def fund_bonus(customer):
    table = Config.objects.get(pk=1)
    bonus_list = Bonus.objects.all()
    if bonus_list:
        for item in bonus_list:
            if item.paid is not True:
               if item.referer == customer.username:
                   payer = AppUser.objects.get(email=item.email)
                   bon = table.referral_bonus
                   if bon != None and payer.balance > 0:
                    #   payer.debit(payer.id,20)
                       old_bonus = customer.bonus
                       customer.bonus = old_bonus + bon
                       customer.save()
                    #   customer.fund(customer.id,20)
                       item.paid = True
                       item.save()
                       
                       
                       
# FUND REFERRAL BONUS APP
@view_decorator
def fund_bonus_app(request):
    user = request.user
    user.fund(user.id, user.bonus)
    name = AppUser.objects.get(pk=user.id)
    name.bonus = 0
    name.save()
                       
    data = {'message': "Your Bonus balance has been added to your Wallet Balance", 'status': 'Successful'}                   
    datas = json.dumps(data)
    return HttpResponse(datas, content_type="application/json")
                
                
                      
#  LOGIN

def login_request(request):
    if request.method == "POST":
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                fund_bonus(user)
                
                #remove cur user all sessions
                sessionids = Usersession.objects.filter(user=request.user).first()
                if sessionids != None:
                    sessionidsToDelete = sessionids.stored_key
                    sessions = Session.objects.filter(session_key=sessionidsToDelete)
                    for session in sessions:
                        session.delete()
                        
                    store = Usersession.objects.filter(stored_key=sessionidsToDelete)
                    for session in store:
                        session.delete()
                    request.session.save()
                Usersession.objects.get_or_create(
                    user=user,
                    stored_key=request.session.session_key)
                # End of sessions removal
                try:
                    send_login_notification(user)
                except:
                    pass
                messages.add_message(request, messages.SUCCESS, f"You are now logged in as {username}.")
                return redirect("dashboard")
            else:
                messages.add_message(request, messages.ERROR,"Invalid username or password.")
        else:
            messages.add_message(request, messages.ERROR, "Invalid username or password.")
    else:
        form = AuthenticationForm()
    return render(request=request, template_name="login.html", context={"form": form})



def activate(request, uidb64, token):
    try:
        uid = force_str(urlsafe_base64_decode(uidb64))
        print(uid)
        user = AppUser.objects.get(pk=uid)
    except(TypeError, ValueError, OverflowError, AppUser.DoesNotExist):
        user = None
    if user is not None and account_activation_token.check_token(user, token):
        user.email_verify = True
        user.save()

        messages.success(request, 'Thank you for your email confirmation. Now you can login your account.')

        return redirect('dashboard')

    else:
        return HttpResponse('Activation link is invalid!')


def sendverificationlink(request):
    try:
        user = request.user
        current_site = get_current_site(request)
        send_activation_email(user, current_site.domain)
    except:
        pass

    data = {'message': f"Verification link sent to {request.user.email}", }
    return HttpResponse(data)



def logout_request(request):
    logout(request)
    messages.info(request, "You have successfully logged out.")
    return redirect("login")


# NOTIFICATIONS
def Notify_User(request):
    form = NotifyForm()
    if request.method == "POST":
        form = NotifyForm(request.POST)
        if form.is_valid():
            users = form.cleaned_data.get('users')
            message = form.cleaned_data.get('message')
            try:
                if AppUser.objects.filter(username=users).exists():
                    customer = AppUser.objects.get(username=users)
                    try:
                        send_admin_notification(customer, message)
                    except:
                        pass
                    messages.add_message(request, messages.SUCCESS,
                                         'Message sent successful to {}'.format(users))
                    
                elif (users).lower() == 'all':
                    for name in AppUser.objects.all():
                        customer = AppUser.objects.get(username=name.username)
                        try:
                            send_admin_notification(customer, message)
                        except:
                            pass

                    messages.add_message(request, messages.SUCCESS,
                                         'Message sent successful to {}'.format(users))
                    

                else:
                    fine = users.strip()
                    dlist = fine.split(" ")
                    start = int(dlist[0]) - 1
                    stop = int(dlist[-1])

                    names = AppUser.objects.all()
                    lenght = len(names)
                    if stop <= lenght:
                        selected_users = []
                        for n in range(start, stop):
                            selected_users.append(names[n])
                        for u in selected_users:
                            try:
                                send_admin_notification(u, message)
                            except:
                                pass
                        messages.add_message(request, messages.SUCCESS,
                                         f'SMS Message sent successfully from user {dlist[0]} to user {dlist[-1]}')
                    
                    else:
                        messages.add_message(request, messages.ERROR,
                                         f'Users are not up to {dlist[-1]}')
            except ValueError:
                messages.add_message(request, messages.ERROR,
                                         'Sorry, You entered an invalid input')

        else:
            messages.add_message(request, messages.ERROR,
                                         'Sorry, You entered an invalid input')
    context = {"form": form, "title": "Notify Users (EMAIL)"}
    return render(request=request, template_name="notify.html", context=context)


def Message_User(request):
    form = NotifyForm()
    if request.method == "POST":
        form = NotifyForm(request.POST)
        if form.is_valid():
            users = form.cleaned_data.get('users')
            message = form.cleaned_data.get('message')
            fone_str = ""
            table = Config.objects.get(pk=1)
            key = table.bulksms_api_key
            url = "https://www.bulksmsnigeria.com/api/v2/sms"
            
            headers = {
                "Content-Type": "application/json",
                "Accept": "application/json",
            }
            try:
                if AppUser.objects.filter(username=users).exists():
                    customer = AppUser.objects.get(username=users)
                    fone_str = customer.phoneNumber
                    parameters = {
                         "body": message,
                         "from": f"{site_name}",
                         "to": fone_str,
                         "api_token": key,
                         "gateway": "direct-refund"
                             }
                    try:
                        response = requests.post(url, headers=headers, json=parameters)
                        result = response.json()
                        print(result)
                        status = result['data']['status']
                    except:
                        print("no result")
                        status = "failed"
                    if status == "success":
                        messages.add_message(request, messages.SUCCESS,
                                             'Message sent successful to {}'.format(users))
                    else:
                        messages.add_message(request, messages.ERROR,
                                         'Sorry, SMS Message not sent')

                elif (users).lower() == 'all':
                    names = AppUser.objects.all()
                    namephone = []
                    for name in names:
                        namephone.append(name.phoneNumber)
   
                    for fone in namephone:
                        fone_str = fone_str + fone + ','
                    parameters = {
                         "body": message,
                         "from": f"{site_name}",
                         "to": fone_str,
                         "api_token": key,
                         "gateway": "direct-refund"
                             } 
                    try:
                        response = requests.post(url, headers=headers, json=parameters)
                        result = response.json()
                        status = result['data']['status']
                    except:
                        status = "failed"
                    if status == "success":
                        messages.add_message(request, messages.SUCCESS,
                                             'Message sent successful to {}'.format(users))
                    else:
                        messages.add_message(request, messages.ERROR,
                                         'Sorry, SMS Message not sent')
                else:
                    fine = users.strip()
                    dlist = fine.split(" ")
                    start = int(dlist[0]) - 1
                    stop = int(dlist[-1])

                    names = AppUser.objects.all()
                    namephone = []
                    for name in names:
                        namephone.append(name.phoneNumber)
                    lenght = len(namephone)
                    if stop <= lenght:
                        selected_phone = []
                        for n in range(start, stop):
                            selected_phone.append(namephone[n])
                        for fone in selected_phone:
                            fone_str = fone_str + fone + ','
                        parameters = {
                         "body": message,
                         "from": f"{site_name}",
                         "to": fone_str,
                         "api_token": key,
                         "gateway": "direct-refund"
                             }
                        try:
                            response = requests.post(url, headers=headers, json=parameters)
                            result = response.json()
                            status = result['data']['status']
                        except:
                            status = "failed"
                        if status == "success":
                            messages.add_message(request, messages.SUCCESS,
                                                 'Message sent successful to {}'.format(users))
                        else:
                            messages.add_message(request, messages.ERROR,
                                                 'Sorry, SMS Message not sent')
                    else:
                        messages.add_message(request, messages.ERROR,
                                             f'Users are not up to {dlist[-1]}')
            except ValueError:
                messages.add_message(request, messages.ERROR,
                                     'Sorry, You entered an invalid input')
        else:
            messages.add_message(request, messages.ERROR,
                                 'Sorry, You entered an invalid input')
    context = {"form": form, "title": "Message Users (SMS)"}
    return render(request=request, template_name="notify.html", context=context)



def transfer_bonus(request):
    user = request.user
    user.fund(user.id, user.bonus)
    name = AppUser.objects.get(pk=user.id)
    name.bonus = 0
    name.save()
    messages.add_message(request, messages.SUCCESS, "Your Bonus Balance Has Been Added To Your Wallet Balance.")
    return redirect('dashboard')
    
    
    
def generateCrystalaccess(request):
    if request.method == "POST":
        user = request.user
        crystalVirtual(user, "3")
        data = {'status': 'Successful'}
        datas = json.dumps(data)
        return HttpResponse(datas,content_type="application/json")
    return HttpResponse(status=200)
    
    
def generateCrystalwema(request):
    if request.method == "POST":
        user = request.user
        crystalVirtual(user, "1")
        data = {'status': 'Successful'}
        datas = json.dumps(data)
        return HttpResponse(datas,content_type="application/json")
    return HttpResponse(status=200)
    
    

def generateMonnify(request):
    if request.method == "POST":
        user = request.user
        generate_acct(user)
        data = {'status': 'Successful'}
        datas = json.dumps(data)
        return HttpResponse(datas,content_type="application/json")
    return HttpResponse(status=200)



# user dashboard
def dashboard(request):
    # web total funds
    funds = []
    all_user = AppUser.objects.all()
    every = len(all_user)
    for user in all_user:
        bal = user.balance
        funds.append(bal)
    tb = sum(funds)
    tba = round(tb, 2)
    # End of web total funds
    current_user = request.user
    get_list, list_len = get_trans(request)
    
    details = Config.objects.get(pk=1)
    message = details.scroll_message
    group = details.whatsapp_group
    pop = details.pop_message
    
    table = Config.objects.get(pk=1)
    
    formOptions = {
        f'AFFILIATE ₦{table.affiliate_upgrade_amount}': "AFFILIATE",
        f'AMBASSADOR ₦{table.ambassador_upgrade_amount}': "AMBASSADOR",  
    }
    form = UpgradeFormUser()
    
    # GET CRYSTAL ACCOUNTS
    if not current_user.securewave_accounts and current_user.bvn:
        try:
            crystalVirtual(current_user, "1")
        except:
            pass
    try:
        crystalaccounts = json.loads(current_user.securewave_accounts)
        crystal = crystalaccounts["accounts"]
    except:
        crystal = None
        
    # GET PALMPAY ACCOUNTS
    # if not current_user.palmpay_account:
    #     # getPalmpayAccount(current_user)
    #     try:
    #         getPalmpayAccountTest(current_user)
    #     except:
    #         pass
        
    try:
        palmpayaccounts = json.loads(current_user.palmpay_account)
        palmpay = palmpayaccounts["accounts"]
    except:
        palmpay = None
    
    
    # GET PAYVESSEL ACCOUNTS
    if not current_user.payvessel_accounts and current_user.bvn:
        try:
            payvesselVirtual(current_user)
        except:
            pass
        
    try:
        payvesselaccounts = json.loads(current_user.payvessel_accounts)
        payvessel = payvesselaccounts["accounts"]
    except:
        payvessel = None
        
    
    # GET PAYMENTPOINT ACCOUNTS
    if not current_user.paymentpoint_accounts and current_user.bvn:
       
        try:
            paymentpointVirtual(current_user)
        except:
            pass
        
    try:
        paymentpointaccounts = json.loads(current_user.paymentpoint_accounts)
        paymentpoint = paymentpointaccounts["accounts"]
    except:
        paymentpoint = None
    
    
    
    # GET MONNIFY ACCOUNTS
    if not current_user.monnify_accounts and current_user.bvn:
        # generate_acct(current_user)
        try:
            generate_acct(current_user)
        except:
            pass
    if current_user.monnify_accounts:
        daccounts = json.loads(current_user.monnify_accounts)
        accounts = daccounts["accounts"]
    else:
        accounts = None
        
    # REFERRALS
    ref_list = Bonus.objects.filter(referer=current_user.username).all()
    num_of_ref = len(ref_list)
    # referrals
    
    if table.monnify_percent:
        moncharge = f"{table.monnify_percent}%"
    else:
        moncharge = f"N{table.monnify_charges}"
        
    if table.securewave_percent:
        cryscharge = f"{table.securewave_percent}%"
    else:
        cryscharge = f"N{table.securewave_charges}"
        
    
    gateway_disable = PaymentGatewayDisable.objects.get(pk=1)
    if request.method == "POST":
        level = request.POST['level']
        if level == "AFFILIATE" and current_user.category == "EARNER":
            if current_user.balance >= table.affiliate_upgrade_amount:
                old_bal = current_user.balance
                new_bal = old_bal - float(table.affiliate_upgrade_amount)
                current_user.category = level
                current_user.save()
                current_user.debit(current_user.id,float(table.affiliate_upgrade_amount))
                
                
                
                Wallet_summary.objects.create(user= current_user, product="Account uprade to Affiliate", amount = table.affiliate_upgrade_amount, previous_balance = old_bal, after_balance= new_bal)
                
                Transact.objects.create(
                email=current_user.email,
                user=current_user,
                transaction="Account uprade to Affiliate",
                status="Successful",
                cost=table.affiliate_upgrade_amount,
                old_balance=old_bal,
                new_balance=new_bal,
                phone_number="None",
                d_network="Account Upgrade",
                value = "ACCOUNT UPGRADE"
                )
                messages.add_message(request, messages.SUCCESS,
                                     f'Your Account has been successfully upgraded to {level}')
            else:
                messages.add_message(request, messages.ERROR,
                                     'Your Wallet balance is insufficient for the Account Upgrade')
        
        
        elif level == "AMBASSADOR" and current_user.category != "AMBASSADOR":
            if current_user.balance >= table.ambassador_upgrade_amount:
                old_bal = current_user.balance
                new_bal = old_bal - float(table.ambassador_upgrade_amount)
                current_user.category = level
                current_user.save()
                current_user.debit(current_user.id, float(table.ambassador_upgrade_amount))
                
                
                
                Wallet_summary.objects.create(user= current_user, product="Account uprade to Ambassador", amount = table.ambassador_upgrade_amount, previous_balance = old_bal, after_balance= new_bal)
                
                Transact.objects.create(
                email=current_user.email,
                user=current_user,
                transaction="Account uprade to Ambassador",
                status="Successful",
                cost=table.ambassador_upgrade_amount,
                old_balance=old_bal,
                new_balance=new_bal,
                phone_number="None",
                d_network="Account Upgrade",
                value = "ACCOUNT UPGRADE"
                )
                messages.add_message(request, messages.SUCCESS,
                                     f'Your Account has been successfully upgraded to {level}')
            else:
                messages.add_message(request, messages.ERROR,
                                     'Your Wallet balance is insufficient for the Account Upgrade')
                                     
        else:
            messages.add_message(request, messages.INFO,
                                     'Your are already an AFFILIATE or an AMBASSADOR')
                                     
        return redirect("dashboard")
    context = {'form': form, 'a': formOptions, 'message': message, 'pop': pop, 'list': get_list, 'trans_len': list_len, 'crystal': crystal, 'paymentpoint': paymentpoint, 'accounts': accounts, 'payvessel': payvessel, 'palmpay': palmpay, 'group': group, 'current_user': current_user, "site_funds": tba, "all_users": every,"num_of_ref": num_of_ref,'gateway_disable': gateway_disable, 'moncharge': moncharge, 'cryscharge': cryscharge, 'refbonus': table.refer_note}
    return render(request=request, template_name="dashboard.html", context=context)





# Data
def buydata(request):
    current_user = request.user
    form = DataForm()
    
    # CHECK LOCKS
    mtn = {"---": "---"}
    if Lockdata.objects.get(pk=17).availability == "ENABLE":
        mtn.update({"MTN TALKMORE AIRTIME": "MTN-TALKMORE-AIRTIME"})
    if Lockdata.objects.get(pk=10).availability == "ENABLE":
        mtn.update({"MTN DATASHARE": "MTN-DATASHARE"})
    if Lockdata.objects.get(pk=1).availability == "ENABLE":
        mtn.update({"MTN SME": "MTN-SME"})
    if Lockdata.objects.get(pk=13).availability == "ENABLE":
        mtn.update({"MTN AWOOF GIFTING": "MTN-AWOOF-GIFTING"})
    if Lockdata.objects.get(pk=2).availability == "ENABLE":
        mtn.update({"MTN CG": "MTN-CG"})
    if Lockdata.objects.get(pk=14).availability == "ENABLE":
        mtn.update({"MTN CG LITE": "MTN-CG-LITE"})
    if Lockdata.objects.get(pk=11).availability == "ENABLE":
        mtn.update({"MTN DIRECT GIFTING": "MTN-DG"})
    if Lockdata.objects.get(pk=9).availability == "ENABLE":
        mtn.update({"MTN DIRECT COUPON": "MTNDIRECT-COUPON"})
        
    airtel = {"---": "---"}
    if Lockdata.objects.get(pk=18).availability == "ENABLE":
        airtel.update({"AIRTEL TALKMORE AIRTIME": "AIRTEL-TALKMORE-AIRTIME"})
    if Lockdata.objects.get(pk=4).availability == "ENABLE":
        airtel.update({"AIRTEL CG": "AIRTEL-CG"})
    if Lockdata.objects.get(pk=3).availability == "ENABLE":
        airtel.update({"AIRTEL GIFTING": "AIRTEL"})
    if Lockdata.objects.get(pk=12).availability == "ENABLE":
        airtel.update({"AIRTEL AWOOF": "AIRTEL-AWOOF"})
    
    glo = {"---": "---"}
    if Lockdata.objects.get(pk=19).availability == "ENABLE":
        glo.update({"GLO TALKMORE AIRTIME": "GLO-TALKMORE-AIRTIME"})
    if Lockdata.objects.get(pk=6).availability == "ENABLE":
        glo.update({"GLO CG": "GLO-CG"})
    if Lockdata.objects.get(pk=5).availability == "ENABLE":
        glo.update({"GLO GIFTING": "GLO"})
    if Lockdata.objects.get(pk=15).availability == "ENABLE":
        glo.update({"GLO AWOOF GIFTING": "GLO-AWOOF-GIFTING"})
        
    mobile = {"---": "---"}
    if Lockdata.objects.get(pk=8).availability == "ENABLE":
        mobile.update({"9MOBILE CG": "9MOBILE-CG"})
    if Lockdata.objects.get(pk=7).availability == "ENABLE":
        mobile.update({"9MOBILE GIFTING": "9MOBILE"})
        
    # END CHECK LOCKS
    
    mtn_price = Mtnsmedata.objects.all().order_by('amount')
    mtncg_price = Giftingdata.objects.all().order_by('amount')
    mtncglite_price = Giftinglitedata.objects.all().order_by('amount')
    glo_price = Glodata.objects.all().order_by('amount')
    glocg_price = Glocgdata.objects.all().order_by('amount')
    gloawoof_price = Glospecialdata.objects.all().order_by('amount')
    airtel_price = Airteldata.objects.all().order_by('amount')
    airtelcg_price = Airtelcgdata.objects.all().order_by('amount')
    airtelawoof_price = Airtelawoofgifting.objects.all().order_by('amount')
    mobile_price = Mobiledata.objects.all().order_by('amount')
    mobilesme_price = Mobilesmedata.objects.all().order_by('amount')
    mtncoupon_price = Mtncoupon.objects.all().order_by('amount')
    mtndatashare_price = Mtndatashare.objects.all().order_by('amount')
    mtndirectgifting_price = Mtndirectgifting.objects.all().order_by('amount')
    mtnawoofgifting_price = Mtnawoofgifting.objects.all().order_by('amount')
    mtntalkmore_price = Mtntalkmore.objects.all().order_by('amount')
    glotalkmore_price = Glotalkmore.objects.all().order_by('amount')
    airteltalkmore_price = Airteltalkmore.objects.all().order_by('amount')

    if current_user.category == "EARNER":
        a = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in mtn_price}
        b = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in glo_price}
        c = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in airtel_price}
        d = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in mobile_price}
        e = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in mtncg_price}
        f = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in airtelcg_price}
        g = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in glocg_price}
        h = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in mobilesme_price}
        i = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in mtncoupon_price}
        j = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in mtndatashare_price}
        k = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in mtndirectgifting_price}
        l = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in airtelawoof_price}
        m = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in mtnawoofgifting_price}
        n = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in mtncglite_price}
        o = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in gloawoof_price}
        p = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in glotalkmore_price}
        q = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in mtntalkmore_price}
        r = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in airteltalkmore_price}
    elif current_user.category == "AFFILIATE":
        a = {f"{row.volume}: ₦{row.amount2} {row.validity}": row.volume for row in mtn_price}
        b = {f"{row.volume}: ₦{row.amount2} {row.validity}": row.volume for row in glo_price}
        c = {f"{row.volume}: ₦{row.amount2} {row.validity}": row.volume for row in airtel_price}
        d = {f"{row.volume}: ₦{row.amount2} {row.validity}": row.volume for row in mobile_price}
        e = {f"{row.volume}: ₦{row.amount2} {row.validity}": row.volume for row in mtncg_price}
        f = {f"{row.volume}: ₦{row.amount2} {row.validity}": row.volume for row in airtelcg_price}
        g = {f"{row.volume}: ₦{row.amount2} {row.validity}": row.volume for row in glocg_price}
        h = {f"{row.volume}: ₦{row.amount2} {row.validity}": row.volume for row in mobilesme_price}
        i = {f"{row.volume}: ₦{row.amount2} {row.validity}": row.volume for row in mtncoupon_price}
        j = {f"{row.volume}: ₦{row.amount2} {row.validity}": row.volume for row in mtndatashare_price}
        k = {f"{row.volume}: ₦{row.amount2} {row.validity}": row.volume for row in mtndirectgifting_price}
        l = {f"{row.volume}: ₦{row.amount2} {row.validity}": row.volume for row in airtelawoof_price}
        m = {f"{row.volume}: ₦{row.amount2} {row.validity}": row.volume for row in mtnawoofgifting_price}
        n = {f"{row.volume}: ₦{row.amount2} {row.validity}": row.volume for row in mtncglite_price}
        o = {f"{row.volume}: ₦{row.amount2} {row.validity}": row.volume for row in gloawoof_price}
        p = {f"{row.volume}: ₦{row.amount2} {row.validity}": row.volume for row in glotalkmore_price}
        q = {f"{row.volume}: ₦{row.amount2} {row.validity}": row.volume for row in mtntalkmore_price}
        r = {f"{row.volume}: ₦{row.amount2} {row.validity}": row.volume for row in airteltalkmore_price}
    elif current_user.category == "AMBASSADOR":
        a = {f"{row.volume}: ₦{row.amount3} {row.validity}": row.volume for row in mtn_price}
        b = {f"{row.volume}: ₦{row.amount3} {row.validity}": row.volume for row in glo_price}
        c = {f"{row.volume}: ₦{row.amount3} {row.validity}": row.volume for row in airtel_price}
        d = {f"{row.volume}: ₦{row.amount3} {row.validity}": row.volume for row in mobile_price}
        e = {f"{row.volume}: ₦{row.amount3} {row.validity}": row.volume for row in mtncg_price}
        f = {f"{row.volume}: ₦{row.amount3} {row.validity}": row.volume for row in airtelcg_price}
        g = {f"{row.volume}: ₦{row.amount3} {row.validity}": row.volume for row in glocg_price}
        h = {f"{row.volume}: ₦{row.amount3} {row.validity}": row.volume for row in mobilesme_price}
        i = {f"{row.volume}: ₦{row.amount3} {row.validity}": row.volume for row in mtncoupon_price}
        j = {f"{row.volume}: ₦{row.amount3} {row.validity}": row.volume for row in mtndatashare_price}
        k = {f"{row.volume}: ₦{row.amount3} {row.validity}": row.volume for row in mtndirectgifting_price}
        l = {f"{row.volume}: ₦{row.amount3} {row.validity}": row.volume for row in airtelawoof_price}
        m = {f"{row.volume}: ₦{row.amount3} {row.validity}": row.volume for row in mtnawoofgifting_price}
        n = {f"{row.volume}: ₦{row.amount3} {row.validity}": row.volume for row in mtncglite_price}
        o = {f"{row.volume}: ₦{row.amount3} {row.validity}": row.volume for row in gloawoof_price}
        p = {f"{row.volume}: ₦{row.amount3} {row.validity}": row.volume for row in glotalkmore_price}
        q = {f"{row.volume}: ₦{row.amount3} {row.validity}": row.volume for row in mtntalkmore_price}
        r = {f"{row.volume}: ₦{row.amount3} {row.validity}": row.volume for row in airteltalkmore_price}
    else:
        a = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in mtn_price}
        b = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in glo_price}
        c = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in airtel_price}
        d = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in mobile_price}
        e = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in mtncg_price}
        f = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in airtelcg_price}
        g = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in glocg_price}
        h = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in mobilesme_price}
        i = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in mtncoupon_price}
        j = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in mtndatashare_price}
        k = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in mtndirectgifting_price}
        l = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in airtelawoof_price}
        m = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in mtnawoofgifting_price}
        n = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in mtncglite_price}
        o = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in gloawoof_price}
        p = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in glotalkmore_price}
        q = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in mtntalkmore_price}
        r = {f"{row.volume}: ₦{row.amount} {row.validity}": row.volume for row in airteltalkmore_price}

    context = {"form": form, "current_user": current_user, "a": a, "e": e, "b": b, "g": g, "c": c, "f": f, "d": d,
               "h": h, "i": i, "j": j, "k": k, "l": l, "m": m, "n": n,"o":o,"p":p,"q":q,"r":r,"mtn":mtn, "airtel":airtel, "glo":glo, "mobile":mobile}
    return render(request=request, template_name="buydata.html", context=context)



@csrf_exempt
@view_decorator
@require_POST
def processdata(request):
    data = request.POST
    user = request.user

    network = data['network']
    type = data['type']
    plan = data['plan']

    try:
        phone = normalize_nigerian_phone(data.get('phone', ''))
    except ValidationError as e:
        return JsonResponse({
            'message': e.messages[0],
            'status': 'Unsuccessful'
        }, status=400)

    valid = "valid" in data

    return pro_cess(type, plan, phone, valid, user)



# =========================================================
# BUY AIRTIME
#
# This view prepares the airtime purchase page.
#
# IMPORTANT:
# The actual airtime debit/pricing calculation is NOT
# performed here.
#
# The actual wallet debit is still handled by airtime_debit().
#
# This view only sends the correct discount information
# to the frontend so that the amount displayed to the user
# matches the pricing logic already used by the backend.
#
# API1 / API2 / API3 users -> Airtime.api
# Other users              -> Airtime.discount
# =========================================================

def buyairtime(request):

    # Create the existing AirtimeForm.
    # We are not changing the form itself.
    form = AirtimeForm()

    # Get the currently logged-in user.
    current_user = request.user

    # Get all airtime network pricing records.
    airtime_discount = Airtime.objects.all()

    # Determine whether the current user belongs to
    # one of the API pricing categories.
    is_api_user = current_user.category in (
        'API1',
        'API2',
        'API3'
    )

    # This dictionary will be sent to JavaScript.
    #
    # Example:
    #
    # {
    #     "MTN": 5,
    #     "AIRTEL": 4,
    #     "GLO": 3,
    #     "ETISALAT": 2
    # }
    #
    # JavaScript will use:
    #
    # networkData["MTN"]
    #
    # to determine the correct discount.
    a = {}

    for row in airtime_discount:

        # API users use the "api" discount column.
        if is_api_user:
            disct = row.api

        # Normal users use the normal "discount" column.
        else:
            disct = row.discount

        # Store the discount using the actual network
        # value used by the backend.
        #
        # Example:
        # "MTN": 5
        # "AIRTEL": 4
        a[row.network] = disct

    # Send the existing form, current user and the
    # user-specific discount map to the template.
    context = {
        "form": form,
        "current_user": current_user,
        "a": a
    }

    # Render the existing airtime template.
    return render(
        request=request,
        template_name='airtime.html',
        context=context
    )
    
    


@csrf_exempt
@view_decorator
@require_POST
def processairtime(request):
    data = request.POST
    user = request.user

    network = data.get('network')
    amount = data.get('amount')
    valid = "valid" in data

    try:
        phone = normalize_nigerian_phone(
            data.get('phone', '')
        )
    except ValidationError as exc:
        return JsonResponse({
            'message': str(exc),
            'status': 'Unsuccessful'
        }, status=400)

    if network not in ('MTN', 'AIRTEL', 'GLO', 'ETISALAT'):
        return JsonResponse({
            'message': 'Please select a valid network.',
            'status': 'Unsuccessful'
        }, status=400)

    return pro_cess_airtime(
        network,
        amount,
        phone,
        valid,
        user
    )
        
        
# RECHARE CARD PRINTING

def buycard(request):
    form = RechargeForm()
    current_user = request.user
    airtime_discount = Airtime.objects.all()
    a = {f"{row.network}: {row.recharge_pin_discount}%": row.network for row in airtime_discount}
    context = {"form": form, "current_user": current_user, "a": a}
    return render(request=request, template_name='recharge.html', context=context)
    
    

@csrf_exempt
@view_decorator
@require_POST
def processrecharge(request):
    if request.method == "POST":
        data = request.POST
        user = request.user
        network = data['network']
        amount = data['amount']
        quantity = data['quantity']
        return pro_cess_recharge(network, amount, quantity, user)
        

        



# Cable tv

@csrf_exempt
@view_decorator
def cable(request):

    form = TvForm()

    current_user = request.user

    dstv_price = Dstv.objects.all()
    gotv_price = Gotv.objects.all()
    startimes_price = Startimes.objects.all()

    # ---------------------------------------------------------
    # Package names and package codes.
    #
    # These preserve the existing a, b and c structure.
    # ---------------------------------------------------------

    a = {
        f"{row.package}: ₦{row.amount}": row.package
        for row in dstv_price
    }

    b = {
        f"{row.package}: ₦{row.amount}": row.package
        for row in gotv_price
    }

    c = {
        f"{row.package}: ₦{row.amount}": row.package
        for row in startimes_price
    }


    # ---------------------------------------------------------
    # Pricing data for the frontend.
    #
    # Normal users:
    #     amount + charge
    #
    # API users:
    #     api + api_charge
    #
    # This uses the same pricing structure as tv_debit().
    # ---------------------------------------------------------

    pricing = {
        "dstv": {},
        "gotv": {},
        "startimes": {}
    }


    if (
        current_user.category == 'API1'
        or current_user.category == 'API2'
        or current_user.category == 'API3'
    ):

        # API1/API2/API3 pricing

        for row in dstv_price:

            pricing["dstv"][row.package] = {
                "price": int(row.api),
                "charge": int(row.api_charge),
                "total": int(row.api) + int(row.api_charge)
            }


        for row in gotv_price:

            pricing["gotv"][row.package] = {
                "price": int(row.api),
                "charge": int(row.api_charge),
                "total": int(row.api) + int(row.api_charge)
            }


        for row in startimes_price:

            pricing["startimes"][row.package] = {
                "price": int(row.api),
                "charge": int(row.api_charge),
                "total": int(row.api) + int(row.api_charge)
            }


    else:

        # Normal user pricing

        for row in dstv_price:

            pricing["dstv"][row.package] = {
                "price": int(row.amount),
                "charge": int(row.charge),
                "total": int(row.amount) + int(row.charge)
            }


        for row in gotv_price:

            pricing["gotv"][row.package] = {
                "price": int(row.amount),
                "charge": int(row.charge),
                "total": int(row.amount) + int(row.charge)
            }


        for row in startimes_price:

            pricing["startimes"][row.package] = {
                "price": int(row.amount),
                "charge": int(row.charge),
                "total": int(row.amount) + int(row.charge)
            }


    # ---------------------------------------------------------
    # IUC / Smartcard verification
    # ---------------------------------------------------------

    if request.method == "POST":

        service = request.POST['service']
        iuc_number = request.POST['iuc']

        # KEEP YOUR EXISTING VTPASS URL AND CREDENTIALS.
        urls = "https://api-service.vtpass.com/api/merchant-verify"

        headers = {
            'Content-Type': 'application/json',
            "api-key": "37cbf73ed25cf7eadcc90868ad9ca279",
            "secret-key": "SK_871c545f322d2689c0d02f660e462715ed36771474f",
        }

        parameters = {
            "billersCode": iuc_number,
            "serviceID": service,
        }

        try:

            responses = requests.post(
                urls,
                headers=headers,
                json=parameters,
                timeout=30
            )

            response = responses.json()

            print(response)

            content = response.get("content")

            if isinstance(content, dict):

                customer_name = (
                    content.get("Customer_Name")
                    or content.get("customer_name")
                    or content.get("CustomerName")
                    or ""
                )

                current_bouquet = (
                    content.get("Current_Bouquet")
                    or content.get("current_bouquet")
                    or content.get("Current Bouquet")
                    or content.get("currentBouquet")
                    or ""
                )

                renewal_amount = (
                    content.get("Renewal_Amount")
                    if content.get("Renewal_Amount") is not None
                    else content.get("renewal_amount")
                )

                if renewal_amount is None:
                    renewal_amount = content.get("Renewal Amount")

                if renewal_amount is None:
                    renewal_amount = content.get("renewalAmount")

                data = {
                    # EXISTING RESPONSE CONTRACT - DO NOT REMOVE.
                    "message": customer_name or "CUSTOMER VERIFIED",
                    "status": True,

                    # ADDITIONAL WEB DATA.
                    "customer_name": customer_name,
                    "current_bouquet": current_bouquet,
                    "renewal_amount": renewal_amount,
                }

            else:

                data = {
                    "message": "INVALID IUC NUMBER",
                    "status": False,
                    "customer_name": "",
                    "current_bouquet": "",
                    "renewal_amount": None,
                }

        except Exception as exc:

            print("Cable TV verification error:", exc)

            data = {
                "message": "INVALID IUC NUMBER",
                "status": False,
                "customer_name": "",
                "current_bouquet": "",
                "renewal_amount": None,
            }

        datas = json.dumps(
            data,
            ensure_ascii=False
        )

        return HttpResponse(
            datas,
            content_type="application/json"
        )


    


    # ---------------------------------------------------------
    # Page context
    # ---------------------------------------------------------

    context = {

        "form": form,

        "current_user": current_user,

        "a": a,

        "b": b,

        "c": c,

        "pricing": pricing

    }


    return render(
        request=request,
        template_name='cable.html',
        context=context
    )

@csrf_exempt
@view_decorator
@require_POST
def processtv(request):
    if request.method == "POST":
        data = request.POST
        user = request.user

        service = data['service']
        plan = data['plan']
        iuc = data['iuc']

        return pro_cess_tv(service, plan, iuc, user)

# Buy electricity
@csrf_exempt
@view_decorator
def buyelectricity(request):
    form = ElectricForm()
    current_user = request.user
    electricity_charges = Electricity.objects.all()
    if current_user.category in ('API1', 'API2', 'API3'):
        a = {
            f"{row.name} ({row.service}): ₦{row.api} Charges": row.service
            for row in electricity_charges
        }
    else:
        a = {
            f"{row.name} ({row.service}): ₦{row.discount} Charges": row.service
            for row in electricity_charges
        }
    if request.method == 'POST':
        form = ElectricForm(request.POST)
        meter_num = request.POST['meter_num']
        service = request.POST['service']
        # vtpass_key = table.vtpass_api_key.encode()
        # vtpass_api_key = b64encode(vtpass_key).decode()
        headers = {
          'Content-Type':'application/json',
          "api-key": "37cbf73ed25cf7eadcc90868ad9ca279",
          "secret-key": "SK_871c545f322d2689c0d02f660e462715ed36771474f",
         }
             
        # urls = "https://www.api.ringo.ng/api/agent/p2"
        urls = "https://api-service.vtpass.com/api/merchant-verify"
        parameters = {
            "billersCode": meter_num,
            "serviceID": service,
            "type": "prepaid"
        }
        
        # headers = {
        #      "Content-Type": "application/json",
        #      "email": f'{table.ringo_email}',
        #      "password": f'{table.ringo_password}',
        # }
        
        # disco = Electricity.objects.get(service=service)
        # parameters = {
        #     "serviceCode": "V-ELECT",
        #     "disco": disco.name,
        #     "meterNo": meter_num,
        #     "type": "PREPAID",
        # }
        try:
            responses = requests.post(urls, headers=headers, json=parameters)
            response = responses.json()
            # print(response)
            if 'content' in response:
                res = response["content"]["Customer_Name"]
                details = res
                stat = True
            else:
                details = 'INVALID METER NUMBER'
                stat = False
                
            # if 'customerName' in response:
            #     res = response["customerName"]
            #     details = res
            #     stat = True
            # else:
            #     details = 'INVALID IUC NUMBER'
            #     stat = False
        except:
            details = 'INVALID METER NUMBER'
            stat = False

        data = {'message': details, 'status': stat}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")

    context = {"form": form, "current_user": current_user, "a": a}
    return render(request=request, template_name='elect.html', context=context)



@csrf_exempt
@view_decorator
@require_POST
def processelect(request):
    if request.method == "POST":
        data = request.POST
        user = request.user

        service = data['service']
        amount = data['amount']
        meter = data['meter_num']

        return pro_cess_electricity(service, meter, amount, user)

# Reslut pin
def result_checker(request):

    form = ResultForm()


    result_price = ResultPin.objects.all()

    a = {
        f"{row.exam_type}: ₦{row.price}": row.exam_type
        for row in result_price
    }

    context = {
        "form": form,
        "a": a
    }

    return render(
        request,
        "result.html",
        context
    )

@csrf_exempt
@view_decorator
@require_POST
def processresult(request):
    if request.method == "POST":
        data = request.POST
        user = request.user

        exam_type = data['exam_type']
        quantity = data['quantity']
        phone = data['phone']

        return pro_cess_result(
            exam_type,
            quantity,
            phone,
            user
        )
# Airtime to cash
def airtime_tocash(request):
    global price
    list = Convertocash.objects.all()
    current_user = request.user
    a = {f"{row.network}: {row.charges}%": row.network for row in list}
    form = ConvertAirtimeForm()
    if request.method == 'POST':
        if Lockservice.objects.get(pk=8).availability == "ENABLE":
                form = ConvertAirtimeForm(request.POST)
                network = request.POST["network"]
                phone = request.POST["phone"]
                amount = request.POST["amount"]
                table = Config.objects.get(pk=1)
                for item in list:
                    if item.network == network:
                        charge = item.charges
                        price = int(amount) - (charge / 100) * int(amount)
                context = {"current_user": current_user, "network": network, "phone": phone, "amount": amount, "price": price,
                           "mtn": table.mtn_num, "glo": table.glo_num, "airtel": table.airtel_num, "mobile": table.mobile_num}
                return render(request=request, template_name='cash.html', context=context)
        else:
            messages.add_message(request, messages.INFO, "Sorry, this service is currently unavailable.")
            
    context = {"form": form, "current_user": current_user, "a": a}
    return render(request=request, template_name='airtocash.html', context=context)

def notify_admin(request, network, amount):
    user = request.user
    table = Config.objects.get(pk=1)
    admin = table.admin_mail

    try:
        send_airtime_to_cash_admin_notification(
            admin,
            user,
            amount,
            network
        )
    except:
        pass

    return redirect('dashboard')


# Bulk sms
def bulk_sms(request):
    form = BulkForm()
    current_user = request.user
    context = {"form": form, "current_user": current_user}
    return render(request=request, template_name='bulk.html', context=context)



# USER PROFILE
def my_profile(request):
    current_user = request.user
    context = {"current_user": current_user}
    return render(request=request, template_name='profile.html', context=context)



@csrf_exempt
@view_decorator
@require_POST
def processbulk(request):
    if request.method == "POST":
        if Lockservice.objects.get(pk=9).availability == "ENABLE":
                data = request.POST
                user = request.user
                message = data['message']
                phones = data['phoneNumbers']
                sender = data['sender']
                li = list(phones.split(","))
                num_lenght = len(li)
                price = num_lenght * 3.5
                old_bal = user.balance
                new_bal = old_bal - price
                if old_bal >= price:
                    
                    Wallet_summary.objects.create(user= user, product="Bulk SMS", amount = price, previous_balance = old_bal, after_balance= new_bal)
                    
                    user.debit(user.id, price)
                    table = Config.objects.get(pk=1)
                    key = table.bulksms_api_key
                    url = "https://www.bulksmsnigeria.com/api/v2/sms"
                    parameters = {
                        "body": message,
                        "from": sender,
                        "to": phones,
                        "api_token": key,
                        "gateway": "direct-refund"
                    }
                    headers = {
                        "Content-Type": "application/json",
                        "Accept": "application/json",
                    }
        
                    response = requests.post(url, headers=headers, json=parameters)
                    result = response.json()
                    msg = "Request Unsuccessful"
                    if 'error' in result:
                        msg = result['error']['message']
                        status = "400"
                    else:
                        status = result['data']['status']
                    
                    
                    # def request_id_gen():
                    #     # Request ID generator
                    #     date_time = datetime.now()
                    #     the_date = date_time.strftime("%Y%m%d%H%M")
                    #     tok = uuid.uuid4()
                    #     token = tok.hex
                    #     req = the_date + token
                    #     request_id = req[0:25]
                    #     return request_id
                    # urls = "https://www.api.ringo.ng/api/agent/p2"
                
                    # headers = {
                    #  "Content-Type": "application/json",
                    #  "email": 'saadudeen459@gmail.com',
                    #  "password": 'SuperAdmin??1418.',
                    # }
                
                    # parameters = {
                    # "serviceCode": "SMS",
                    # "sender_id": sender,
                    # "request_id": request_id_gen(),
                    # "mobile": phones,
                    # "msg": message,
                    # }
                    
                    # responses = requests.post(urls, headers=headers, json=parameters)
                    # response = responses.json()
                    # status = response['status']
                    
                    
                    if status == "200":
                        stat = "Successful"
                        data = {'message': "Message sent Successfully", 'status': 'Successful'}
                    else:
                        stat = "Unsuccessful"
                        data = {'message': msg, 'status': 'Unsuccessful'}
                        user.fund(user.id, price)
                        new_bal = old_bal
                    Transact.objects.create(
                        email=user.email,
                        user=user,
                        transaction="Bulk SMS transaction",
                        status=stat,
                        cost=price,
                        old_balance=old_bal,
                        new_balance=new_bal,
                        phone_number="BulkSMS",
                        d_network="BulkSMS",
                        value = "BULK SMS"
                    )
                else:
                    data = {'message': "Insufficient Funds", 'status': 'Unsuccessful'}
        else:
            data = {'message': "Sorry, this service is currently unavailable.", 'status': 'Unsuccessful'}
                    
    datas = json.dumps(data)
    return HttpResponse(datas, content_type="application/json")


# Payment gateways
def monnify_auto(request):
    return autofund(request)

def crystal_auto(request):
    return crystal_autofund(request)

@csrf_exempt
@view_decorator
def dynamic_acct(request):
    return crystalDynamic(request)

def atm_fund(request):
    return atmfund(request)

def manual_funding(request):
    form = ManualFundForm()
    konfig = Config.objects.get(pk=1)

    if request.method == "POST":
        form = ManualFundForm(request.POST)
        data = request.POST
        user = request.user
        amount = data['amount']

        try:
            send_manual_funding_admin_notification(
                konfig.admin_mail,
                user,
                amount
            )
        except:
            pass

        messages.add_message(request, messages.SUCCESS, "Notification Sent.")

    context = {
        "bn": konfig.bank_name,
        "an": konfig.account_name,
        "ab": konfig.account_number,
        "bn2": konfig.bank_name2,
        "an2": konfig.account_name2,
        "ab2": konfig.account_number2,
        "form": form
    }

    return render(
        request=request,
        template_name='manualfund.html',
        context=context
    )


# Sales Analysis
def analize_sales(request):
    return sales_analysis(request)

def analize_sales_users(request):
    return user_sales_analysis(request)


# Transaction history and query

def data_transaction(request):
    current_user = request.user
    array = Transact.objects.filter(user=current_user,value="DATA")
    the_list = []
    for n in array:
        if n.email == current_user.email:
            the_list.append(n)
    x = the_list.reverse()

    page = request.GET.get("page", 1)
    paginator = Paginator(the_list, 15)
    try:
        transactions = paginator.page(page)
    except PageNotAnInteger:
        transactions = paginator.page(1)
    except EmptyPage:
        transactions = paginator.page(paginator.num_pages)
        
    current_page = transactions.number
    total_pages = paginator.num_pages

    # Define how many pages to show before and after current
    page_window = 2

    start_page = max(current_page - page_window, 1)
    end_page = min(current_page + page_window, total_pages)

    custom_page_range = range(start_page, end_page + 1)


    context = {"item": transactions,"custom_page_range": custom_page_range}
    return render(request=request, template_name='transactions_data.html', context=context)


def airtime_transaction(request):
    current_user = request.user
    array = Transact.objects.filter(user=current_user,value="AIRTIME")
    the_list = []
    for n in array:
        if n.email == current_user.email:
            the_list.append(n)
    x = the_list.reverse()

    page = request.GET.get("page", 1)
    paginator = Paginator(the_list, 15)
    try:
        transactions = paginator.page(page)
    except PageNotAnInteger:
        transactions = paginator.page(1)
    except EmptyPage:
        transactions = paginator.page(paginator.num_pages)
        
    current_page = transactions.number
    total_pages = paginator.num_pages

    # Define how many pages to show before and after current
    page_window = 2

    start_page = max(current_page - page_window, 1)
    end_page = min(current_page + page_window, total_pages)

    custom_page_range = range(start_page, end_page + 1)


    context = {"item": transactions,"custom_page_range": custom_page_range}
    return render(request=request, template_name='transactions_airtime.html', context=context)

def funding_transaction(request):
    current_user = request.user
    array = Transact.objects.filter(user=current_user,value__icontains='funding')
    the_list = []
    for n in array:
        if n.email == current_user.email:
            the_list.append(n)
    x = the_list.reverse()

    page = request.GET.get("page", 1)
    paginator = Paginator(the_list, 15)
    try:
        transactions = paginator.page(page)
    except PageNotAnInteger:
        transactions = paginator.page(1)
    except EmptyPage:
        transactions = paginator.page(paginator.num_pages)
        
    current_page = transactions.number
    total_pages = paginator.num_pages

    # Define how many pages to show before and after current
    page_window = 2

    start_page = max(current_page - page_window, 1)
    end_page = min(current_page + page_window, total_pages)

    custom_page_range = range(start_page, end_page + 1)


    context = {"item": transactions,"custom_page_range": custom_page_range}
    return render(request=request, template_name='transactions_funding.html', context=context)




def user_transaction(request):
    current_user = request.user
    array = Transact.objects.filter(user=current_user)
    the_list = []
    for n in array:
        if n.email == current_user.email:
            the_list.append(n)
    x = the_list.reverse()

    page = request.GET.get("page", 1)
    paginator = Paginator(the_list, 15)
    try:
        transactions = paginator.page(page)
    except PageNotAnInteger:
        transactions = paginator.page(1)
    except EmptyPage:
        transactions = paginator.page(paginator.num_pages)
        
    current_page = transactions.number
    total_pages = paginator.num_pages

    # Define how many pages to show before and after current
    page_window = 2

    start_page = max(current_page - page_window, 1)
    end_page = min(current_page + page_window, total_pages)

    custom_page_range = range(start_page, end_page + 1)


    context = {"item": transactions,"custom_page_range": custom_page_range}
    return render(request=request, template_name='transactions.html', context=context)





# def user_transaction(request):
#     current_user = request.user
#     array = Transact.objects.all()
#     the_list = []
#     for n in array:
#         if n.email == current_user.email:
#             the_list.append(n)
#     x = the_list.reverse()
#     context = {"item": the_list}
#     return render(request=request, template_name='transactions.html', context=context)



def user_query(request):
    form = QueryForm()
    # transactions = None
    post = False
    the_list = []
    if request.method == "POST":
        current_user = request.user
        obj = request.POST["query"]
        array = Transact.objects.filter(Q(status=obj) | Q(phone_number=obj), user=current_user)
        the_list = []
        if array:
            for n in array:
                the_list.append(n)
            x = the_list.reverse()
            post = True
            
    page = request.GET.get("page", 1)
    paginator = Paginator(the_list, 30)
    try:
        transactions = paginator.page(page)
    except PageNotAnInteger:
        transactions = paginator.page(1)
    except EmptyPage:
        transactions = paginator.page(paginator.num_pages)
            
    current_page = transactions.number
    total_pages = paginator.num_pages
    
    # Define how many pages to show before and after current
    page_window = 2
    
    start_page = max(current_page - page_window, 1)
    end_page = min(current_page + page_window, total_pages)
    
    custom_page_range = range(start_page, end_page + 1)
    
    
    context = {"item": transactions,"custom_page_range": custom_page_range,"form": form, "is_post": post}
                
        # context = {"item": the_list, "form": form, "is_post": True}
        # return render(request=request, template_name='query.html', context=context)
    # context = {"form": form}
    return render(request=request, template_name='query.html', context=context)



def user_success(request):
    current_user = request.user
    if Transact.objects.filter(user=current_user).exists():
        the_list = Transact.objects.filter(user=current_user,status="Successful").all()
        new_list = []
        for i in the_list:
            new_list.append(i)
        x = new_list.reverse()
    else:
        new_list = []
        
    page = request.GET.get("page", 1)
    paginator = Paginator(new_list, 15)
    try:
        transactions = paginator.page(page)
    except PageNotAnInteger:
        transactions = paginator.page(1)
    except EmptyPage:
        transactions = paginator.page(paginator.num_pages)
        
    current_page = transactions.number
    total_pages = paginator.num_pages

    # Define how many pages to show before and after current
    page_window = 2

    start_page = max(current_page - page_window, 1)
    end_page = min(current_page + page_window, total_pages)

    custom_page_range = range(start_page, end_page + 1)


    context = {"item": transactions,"custom_page_range": custom_page_range}
    return render(request=request, template_name='transactions.html', context=context)




def user_fail(request):
    current_user = request.user
    if Transact.objects.filter(user=current_user).exists():
        the_list = Transact.objects.filter(user=current_user,status="Unsuccessful").all()
        new_list = []
        for i in the_list:
            new_list.append(i)
        x = new_list.reverse()
    else:
        new_list = []
        
    page = request.GET.get("page", 1)
    paginator = Paginator(new_list, 15)
    try:
        transactions = paginator.page(page)
    except PageNotAnInteger:
        transactions = paginator.page(1)
    except EmptyPage:
        transactions = paginator.page(paginator.num_pages)
        
    current_page = transactions.number
    total_pages = paginator.num_pages

    # Define how many pages to show before and after current
    page_window = 2

    start_page = max(current_page - page_window, 1)
    end_page = min(current_page + page_window, total_pages)

    custom_page_range = range(start_page, end_page + 1)


    context = {"item": transactions,"custom_page_range": custom_page_range}
    return render(request=request, template_name='transactions.html', context=context)



def user_pend(request):
    current_user = request.user
    if Transact.objects.filter(user=current_user).exists():
        the_list = Transact.objects.filter(user=current_user,status="Pending").all()
        new_list = []
        for i in the_list:
            new_list.append(i)
        x = new_list.reverse()
    else:
        new_list = []
        
    page = request.GET.get("page", 1)
    paginator = Paginator(new_list, 15)
    try:
        transactions = paginator.page(page)
    except PageNotAnInteger:
        transactions = paginator.page(1)
    except EmptyPage:
        transactions = paginator.page(paginator.num_pages)
        
    current_page = transactions.number
    total_pages = paginator.num_pages

    # Define how many pages to show before and after current
    page_window = 2

    start_page = max(current_page - page_window, 1)
    end_page = min(current_page + page_window, total_pages)

    custom_page_range = range(start_page, end_page + 1)


    context = {"item": transactions,"custom_page_range": custom_page_range}
    return render(request=request, template_name='transactions.html', context=context)

# Transaction history and query for admin


def admin_transaction(request):
    array = Transact.objects.all().order_by('-id')
    context = {"item": array}
    return render(request=request, template_name='transactions.html', context=context)



def admin_query(request):
    form = QueryForm()
    current_user = request.user
    if request.method == "POST":
        obj = request.POST["query"]
        array = Transact.objects.filter(user__username=obj).all()
        array2 = Transact.objects.filter(phone_number=obj).all()
        the_list = []
        for n in array:
            the_list.append(n)
        for n in array2:
            the_list.append(n)
        x = the_list.reverse()
        context = {"item": the_list }
        return render(request=request, template_name='transactions.html', context=context)
    context = {"form": form}
    return render(request=request, template_name='query.html', context=context)



def admin_success(request):
    the_list = Transact.objects.filter(status="Successful").all()
    context = {"item": the_list}
    return render(request=request, template_name='transactions.html', context=context)


def admin_fail(request):
    the_list = Transact.objects.filter(status="Unsuccessful").all()
    context = {"item": the_list}
    return render(request=request, template_name='transactions.html', context=context)


def admin_pend(request):
    the_list = Transact.objects.filter(status="Pending").all()
    context = {"item": the_list}
    return render(request=request, template_name='transactions.html', context=context)



# MONNIFY WEBHOOK

@require_POST
@csrf_exempt
def update_monnify(request):
    byte = request.body
    data = json.loads(byte)
    signature = request.headers.get('monnify-signature')

    pay = monFund(data, byte, signature)

    return HttpResponse(status=200)




# CRYSTAL WEBHOOK


@require_POST
@csrf_exempt
def update_crystal(request):
    data = request.body
    hook = json.loads(data)
    mail = hook['destination']['account_email']
    amount = hook['event_data']['data']['paid']
    tref = hook['transaction_reference']
    try:
        ref = PayRef.objects.get(reference=tref)
    except:
        user = AppUser.objects.get(email=mail)
        PayRef.objects.create(
            user=user,
            reference=tref,
        )

        pay = online_fund(mail, amount, user)

    return HttpResponse(status=200)



# views.py

import logging

from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.views.decorators.http import require_POST

from .forms import KycForm

from .services.kyc import (
    process_kyc_verification,
    check_bvn_verification
)


logger = logging.getLogger(__name__)



def _process_kyc_post(request):
    """
    Shared request handling for website and mobile KYC.
    """

    user = request.user

    if not user.is_authenticated:
        return JsonResponse({
            "status": "Unsuccessful",
            "message": "Authentication required. Please log in again."
        }, status=401)

    if user.verify:
        return JsonResponse({
            "status": "Successful",
            "message": "Your account has already been verified."
        })

    form = KycForm(request.POST)

    if not form.is_valid():

        errors = {
            field: [str(error) for error in field_errors]
            for field, field_errors in form.errors.items()
        }

        return JsonResponse({
            "status": "Unsuccessful",
            "message": "Please correct the highlighted fields.",
            "errors": errors
        }, status=400)

    success, message = process_kyc_verification(
        user,
        form.cleaned_data
    )

    return JsonResponse({
        "status": "Successful" if success else "Unsuccessful",
        "message": message
    })

# ==========================================================
# EXISTING MOBILE ENDPOINT
# URL: /verify/
# ==========================================================

@csrf_exempt
@view_decorator
def kyc(request):
    """
    Existing KYC endpoint.

    Retains the original URL and authentication decorator
    for compatibility with the installed Flutter APK.

    GET: Displays the existing KYC page.
    POST: Processes mobile KYC verification.
    """

    if request.method == "POST":
        return _process_kyc_post(request)

    if request.method == "GET":

        form = KycForm()

        context = {
            "form": form,
            "current_user": request.user
        }

        return render(
            request,
            "kyc.html",
            context
        )

    return JsonResponse({
        "status": "Unsuccessful",
        "message": "Method not allowed."
    }, status=405)


# ==========================================================
# NEW WEBSITE ENDPOINT
# URL: /verify-web/
# ==========================================================

@require_POST
@csrf_protect
def kyc_web_verify(request):
    """
    CSRF-protected website KYC endpoint.

    Requires an authenticated Django session.
    """

    if not request.user.is_authenticated:

        return JsonResponse({
            "status": "Unsuccessful",
            "message": "Your session has expired. Please log in again."
        }, status=401)

    return _process_kyc_post(request)

    

# PRICING
def pricing(request):
    user = request.user
    mtn_price = Mtnsmedata.objects.all()
    mtndirectgifting_price = Mtndirectgifting.objects.all()
    mtnawoofgifting_price = Mtnawoofgifting.objects.all()
    mtnsme1_price = Mtndatashare.objects.all()
    mtncoupon_price = Mtncoupon.objects.all()
    mtncg_price = Giftingdata.objects.all()
    mtncglite_price = Giftinglitedata.objects.all()
    glo_price = Glodata.objects.all()
    glocg_price = Glocgdata.objects.all()
    gloawoof_price = Glospecialdata.objects.all()
    airtel_price = Airteldata.objects.all()
    airtelcg_price = Airtelcgdata.objects.all()
    airtelawoofgifting_price = Airtelawoofgifting.objects.all()
    mobile_price = Mobiledata.objects.all()
    mobilesme_price = Mobilesmedata.objects.all()
    airtime_discount = Airtime.objects.all()
    airtime_charges = Convertocash.objects.all()
    electricity_charges = Electricity.objects.all()
    dstv_price = Dstv.objects.all()
    gotv_price = Gotv.objects.all()
    startimes_price = Startimes.objects.all()
    result_price = ResultPin.objects.all()

    context = {
        "mtn" : mtn_price, "mtncoupon" : mtncoupon_price, "gifting" : mtncg_price, "giftinglite" : mtncglite_price, "mtndirectgifting" : mtndirectgifting_price, "mtnsme1" : mtnsme1_price,"glo" : glo_price, "glocg" : glocg_price,
    "airtel" : airtel_price, "airtelcg" : airtelcg_price, "mobile" : mobile_price, "mobilesme" : mobilesme_price,"gloawoof" : gloawoof_price,
    "airtime" : airtime_discount, "dstv" : dstv_price, "gotv" : gotv_price, "startimes" : startimes_price, "mtnawoof" : mtnawoofgifting_price, "airtelawoof" : airtelawoofgifting_price,
    "elect" : electricity_charges, "result" : result_price, "current_user": user
    }
    return render(request=request, template_name='pricing.html', context=context)






# API views

# DATA
@require_POST
@csrf_exempt
def api_data(request):
    token = request.headers.get('Authorization')
    apy = token.split()
    apikey = apy[1]
    try:
        account = AppUser.objects.get(api_key=apikey)
    except:
        data = {'message': "Invalid Credentials", 'status': 'Unsuccessful', 'api_response': 'Invalid Credentials', 'Status': 'failed'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")

    if account:
        if account.activate:
            bud = request.body
            budy = json.loads(bud)
            planD = budy.get('plan', None)
            phone = budy.get('mobile_number', None)
            try:
                listy = planD.split("_")
                plan = listy[0]
                network = listy[1]
            except:
                if budy.get('type', None) is not None:
                    network = budy.get('type', None)
                    plan = budy.get('plan', None)
                else:
                    data = {'message': "Invalid plan type", 'status': 'Unsuccessful', 'api_response': 'Invalid plan type', 'Status': 'failed'}
                    datas = json.dumps(data)
                    return HttpResponse(datas, content_type="application/json")
            if not account or not network or not phone or not plan:
                data = {'message': "Incomplete parameters", 'status': 'Unsuccessful', 'api_response': 'Incomplete parameters', 'Status': 'failed'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            else:
                return process_data_api(network, plan, phone, account)

        else:
            data = {'message': "Sorry, Your account has not being activated for API services", 'status': 'Unsuccessful', 'api_response': 'Sorry, Your account has not being activated for API services', 'Status': 'failed'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    else:
        data = {'message': "Invalid Credentials", 'status': 'Unsuccessful', 'api_response': 'Invalid Credentials', 'Status': 'failed'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")


# AIRTIME
@require_POST
@csrf_exempt
def api_airtime(request):
    token = request.headers.get('Authorization')
    apy = token.split()
    apikey = apy[1]
    try:
        account = AppUser.objects.get(api_key=apikey)
    except:
        data = {'message': "Invalid Credentials", 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")

    if account:
        if account.activate:
            bud = request.body
            budy = json.loads(bud)
            network = budy.get('network', None)
            phone = budy.get('mobile_number', None)
            amount = budy.get('amount', None)
            if not account or not network or not phone or not amount:
                data = {'message': "Incomplete parameters", 'status': 'Unsuccessful'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            else:
                return process_airtime_api(network, amount, phone, account)

        else:
            data = {'message': "Sorry, Your account has not being activated for API services", 'status': 'Unsuccessful'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    else:
        data = {'message': "Invalid Credentials", 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")



# CABLES
@require_POST
@csrf_exempt
def api_cable(request):
    token = request.headers.get('Authorization')
    apy = token.split()
    apikey = apy[1]
    try:
        account = AppUser.objects.get(api_key=apikey)
    except:
        data = {'message': "Invalid Credentials", 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")

    if account:
        if account.activate:
            bud = request.body
            budy = json.loads(bud)
            cablename = budy.get('cablename', None)
            cableplan = budy.get('cableplan', None)
            iuc = budy.get('iuc_number', None)
            if not account or not cablename or not cableplan or not iuc:
                data = {'message': "Incomplete parameters", 'status': 'Unsuccessful'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            else:
                return process_tv_api(cablename, cableplan, iuc, account)

        else:
            data = {'message': "Sorry, Your account has not being activated for API services", 'status': 'Unsuccessful'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    else:
        data = {'message': "Invalid Credentials", 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")




# ELECTRICITY
@require_POST
@csrf_exempt
def api_electricity(request):
    token = request.headers.get('Authorization')
    apy = token.split()
    apikey = apy[1]
    try:
        account = AppUser.objects.get(api_key=apikey)
    except:
        data = {'message': "Invalid Credentials", 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")

    if account:
        if account.activate:
            bud = request.body
            budy = json.loads(bud)
            disco_name = budy.get('disco_name', None)
            amount = budy.get('amount', None)
            meter_number = budy.get('meter_number', None)
            if not account or not disco_name or not amount or not meter_number:
                data = {'message': "Incomplete parameters", 'status': 'Unsuccessful'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            else:
                return process_electricity_api(disco_name, meter_number, amount, account)

        else:
            data = {'message': "Sorry, Your account has not being activated for API services", 'status': 'Unsuccessful'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    else:
        data = {'message': "Invalid Credentials", 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")



# EXAM PIN
@require_POST
@csrf_exempt
def api_exam(request):
    token = request.headers.get('Authorization')
    apy = token.split()
    apikey = apy[1]
    try:
        account = AppUser.objects.get(api_key=apikey)
    except:
        data = {'message': "Invalid Credentials", 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")

    if account:
        if account.activate:
            bud = request.body
            budy = json.loads(bud)
            exam_type = budy.get('exam_type', None)
            quantity = budy.get('quantity', None)
            phone = budy.get('mobile_number', None)
            if not account or not exam_type or not quantity or not phone:
                data = {'message': "Incomplete parameters", 'status': 'Unsuccessful'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            else:
                return process_result_api(exam_type, quantity, phone, account)

        else:
            data = {'message': "Sorry, Your account has not being activated for API services", 'status': 'Unsuccessful'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    else:
        data = {'message': "Invalid Credentials", 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")


# VALIDATE METER
@require_POST
@csrf_exempt
def validate_meter(request):
    token = request.headers.get('Authorization')
    apy = token.split()
    apikey = apy[1]
    try:
        account = AppUser.objects.get(api_key=apikey)
    except:
        data = {'message': "Invalid Credentials", 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")

    if account:
        if account.activate:
            bud = request.body
            budy = json.loads(bud)
            service = budy.get('disco_name', None)
            meter_num = budy.get('meter_number', None)
            if not account or not service or not meter_num:
                data = {'message': "Incomplete parameters", 'status': 'Unsuccessful'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            else:
                table = Config.objects.get(pk=1)
                vtpass_key = table.vtpass_api_key.encode()
                vtpass_api_key = b64encode(vtpass_key).decode()
                headers = {
                      'Content-Type':'application/json',
                      "api-key": "37cbf73ed25cf7eadcc90868ad9ca279",
                      "secret-key": "SK_871c545f322d2689c0d02f660e462715ed36771474f",
                     }
                url = "https://api-service.vtpass.com/api/merchant-verify"
                parameters = {
                    "billersCode": meter_num,
                    "serviceID": service,
                    "type": "prepaid"
                }
                responses = requests.post(url, headers=headers, json=parameters)
                response = responses.json()

                datas = json.dumps(response)
                return HttpResponse(datas, content_type="application/json")

        else:
            data = {'message': "Sorry, Your account has not being activated for API services", 'status': 'Unsuccessful'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    else:
        data = {'message': "Invalid Credentials", 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")


# VALIDATE IUC
@require_POST
@csrf_exempt
def validate_iuc(request):
    token = request.headers.get('Authorization')
    apy = token.split()
    apikey = apy[1]
    try:
        account = AppUser.objects.get(api_key=apikey)
    except:
        data = {'message': "Invalid Credentials", 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")

    if account:
        if account.activate:
            bud = request.body
            budy = json.loads(bud)
            service = budy.get('cablename', None)
            iuc_number = budy.get('iuc_number', None)
            if not account or not service or not iuc_number:
                data = {'message': "Incomplete parameters", 'status': 'Unsuccessful'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
            else:
                table = Config.objects.get(pk=1)
                vtpass_key = table.vtpass_api_key.encode()
                vtpass_api_key = b64encode(vtpass_key).decode()
                headers = {
                      'Content-Type':'application/json',
                      "api-key": "37cbf73ed25cf7eadcc90868ad9ca279",
                      "secret-key": "SK_871c545f322d2689c0d02f660e462715ed36771474f",
                     }
                url = "https://api-service.vtpass.com/api/merchant-verify"
                parameters = {
                    "billersCode": iuc_number,
                    "serviceID": service,
                }
                responses = requests.post(url, headers=headers, json=parameters)
                response = responses.json()

                datas = json.dumps(response)
                return HttpResponse(datas, content_type="application/json")

        else:
            data = {'message': "Sorry, Your account has not being activated for API services", 'status': 'Unsuccessful'}
            datas = json.dumps(data)
            return HttpResponse(datas, content_type="application/json")
    else:
        data = {'message': "Invalid Credentials", 'status': 'Unsuccessful'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")


# Developer
def developer(request):
    user = request.user
    if request.method == "POST":
        if "gen" in request.POST:
            generator(user)
        messages.add_message(request, messages.SUCCESS, f"Your API Key has been reset successfully.")
        return redirect("developer")
    context = {"current_user": user}
    return render(request=request, template_name='dev.html', context=context)


def record(user, price, old_bal, net):
    Transact.objects.create(
        email=user.email,
        user=user,
        transaction=f"{net} funding",
        status="Successful",
        cost=price,
        old_balance=old_bal,
        new_balance=old_bal-price,
        phone_number=user.phoneNumber,
        d_network=net,
        value = net
    )


# Bucket
def data_bucket(request):
    bucket = Lockbucket.objects.get(pk=1)
    form = BucketForm()
    current_user = request.user
    mtnsme_bucket = Mtnsmebucket.objects.all()
    mtncg_bucket = Mtncgbucket.objects.all()
    airtelcg_bucket = Airtelcgbucket.objects.all()
    glocg_bucket = Glocgbucket.objects.all()
    mobilecg_bucket = Mobilecgbucket.objects.all()
    if bucket.mtn_sme == "ENABLE":
        a = {f"{row.volume} GB: ₦{row.amount}": row.volume for row in mtnsme_bucket}
    else:
        a = {"---":"---"}
    if bucket.mtn_cg == "ENABLE":
        b = {f"{row.volume} GB: ₦{row.amount}": row.volume for row in mtncg_bucket}
    else:
        b = {"---":"---"}
    if bucket.airtel_cg == "ENABLE":
        c = {f"{row.volume} GB: ₦{row.amount}": row.volume for row in airtelcg_bucket}
    else:
        c = {"---":"---"}
    if bucket.glo_cg == "ENABLE":
        d = {f"{row.volume} GB: ₦{row.amount}": row.volume for row in glocg_bucket}
    else:
        d = {"---":"---"}
    if bucket.mobile_cg == 'ENABLE':
        e = {f"{row.volume} GB: ₦{row.amount}": row.volume for row in mobilecg_bucket}
    else:
        e = {"---":"---"}
    if request.method == "POST":
        data = request.POST
        network = data['network']
        plan = data['plan']
        if network == 'mtn_sme':
            try:
                bucket_item = Mtnsmebucket.objects.get(volume=plan)
                if current_user.balance < bucket_item.amount:
                    data = {'message': "Insufficient Balance", 'status': 'Unsuccessful'}
                    datas = json.dumps(data)
                    return HttpResponse(datas, content_type="application/json")
                else:
                    old = current_user.balance
                    
                    Wallet_summary.objects.create(user= user, product="Bucket data purchase", amount = bucket_item.amount, previous_balance = old, after_balance= old - bucket_item.amount)
                    
                    current_user.debit(current_user.id, bucket_item.amount)
                    current_user.fundmtnsme(bucket_item.volume)
                    nett = f"Bucket Data {network}"
                    record(current_user, bucket_item.amount, old, nett)
                    data = {'message': "Bucket Funded Successfully", 'status': 'Successful'}
                    datas = json.dumps(data)
                    return HttpResponse(datas, content_type="application/json")
            except:
                data = {'message': "Invalid plan Type", 'status': 'Unsuccessful'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        elif network == 'mtn_cg':
            try:
                bucket_item = Mtncgbucket.objects.get(volume=plan)
                if current_user.balance < bucket_item.amount:
                    data = {'message': "Insufficient Balance", 'status': 'Unsuccessful'}
                    datas = json.dumps(data)
                    return HttpResponse(datas, content_type="application/json")
                else:
                    old = current_user.balance
                    
                    Wallet_summary.objects.create(user= user, product="Bucket data purchase", amount = bucket_item.amount, previous_balance = old, after_balance= old - bucket_item.amount)
                    
                    current_user.debit(current_user.id, bucket_item.amount)
                    current_user.fundmtncg(bucket_item.volume)
                    nett = f"Bucket Data {network}"
                    record(current_user, bucket_item.amount, old, nett)
                    data = {'message': "Bucket Funded Successfully", 'status': 'Successful'}
                    datas = json.dumps(data)
                    return HttpResponse(datas, content_type="application/json")
            except:
                data = {'message': "Invalid plan Type", 'status': 'Unsuccessful'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        elif network == 'glo_cg':
            try:
                bucket_item = Glocgbucket.objects.get(volume=plan)
                if current_user.balance < bucket_item.amount:
                    data = {'message': "Insufficient Balance", 'status': 'Unsuccessful'}
                    datas = json.dumps(data)
                    return HttpResponse(datas, content_type="application/json")
                else:
                    old = current_user.balance
                    
                    Wallet_summary.objects.create(user= user, product="Bucket data purchase", amount = bucket_item.amount, previous_balance = old, after_balance= old - bucket_item.amount)
                    
                    current_user.debit(current_user.id, bucket_item.amount)
                    current_user.fundglocg(bucket_item.volume)
                    nett = f"Bucket Data {network}"
                    record(current_user, bucket_item.amount, old, nett)
                    data = {'message': "Bucket Funded Successfully", 'status': 'Successful'}
                    datas = json.dumps(data)
                    return HttpResponse(datas, content_type="application/json")
            except:
                data = {'message': "Invalid plan Type", 'status': 'Unsuccessful'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        elif network == 'airtel_cg':
            try:
                bucket_item = Airtelcgbucket.objects.get(volume=plan)
                if current_user.balance < bucket_item.amount:
                    data = {'message': "Insufficient Balance", 'status': 'Unsuccessful'}
                    datas = json.dumps(data)
                    return HttpResponse(datas, content_type="application/json")
                else:
                    old = current_user.balance
                    
                    Wallet_summary.objects.create(user= user, product="Bucket data purchase", amount = bucket_item.amount, previous_balance = old, after_balance= old - bucket_item.amount)
                    
                    current_user.debit(current_user.id, bucket_item.amount)
                    current_user.fundairtelcg(bucket_item.volume)
                    nett = f"Bucket Data {network}"
                    record(current_user, bucket_item.amount, old, nett)
                    data = {'message': "Bucket Funded Successfully", 'status': 'Successful'}
                    datas = json.dumps(data)
                    return HttpResponse(datas, content_type="application/json")
            except:
                data = {'message': "Invalid plan Type", 'status': 'Unsuccessful'}
                datas = json.dumps(data)
                return HttpResponse(datas, content_type="application/json")
        elif network == 'mobile_cg':
            try:
                bucket_item = Mobilecgbucket.objects.get(volume=plan)
                if current_user.balance < bucket_item.amount:
                    data = {'message': "Insufficient Balance", 'status': 'Unsuccessful'}
                    datas = json.dumps(data)
                    return HttpResponse(datas, content_type="application/json")
                else:
                    old = current_user.balance
                    
                    Wallet_summary.objects.create(user= user, product="Bucket data purchase", amount = bucket_item.amount, previous_balance = old, after_balance= old - bucket_item.amount)
                    
                    current_user.debit(current_user.id, bucket_item.amount)
                    current_user.fundmobilecg(bucket_item.volume)
                    nett = f"Bucket Data {network}"
                    record(current_user, bucket_item.amount, old, nett)
                    data = {'message': "Bucket Funded Successfully", 'status': 'Successful'}
                    datas = json.dumps(data)
                    return HttpResponse(datas, content_type="application/json")
            except:
                passdata = {'message': "Invalid plan Type", '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")
    context = {"form": form, "current_user": current_user, "a": a, "b": b, "c": c, "d": d, "e": e}
    return render(request=request, template_name='bucket.html', context=context)

def bucket_query(request):
    form = QueryForm()
    current_user = request.user
    array = BucketTransact.objects.all()
    the_list = []
    for n in array:
        if n.email == current_user.email:
            the_list.append(n)
    x = the_list.reverse()
    if request.method == "POST":
        form = QueryForm(request.POST)
        obj = request.POST["query"]
        array = BucketTransact.objects.filter(status=obj).all()
        array2 = BucketTransact.objects.filter(phone_number=obj).all()
        the_list = []
        for n in array:
            if n.email == current_user.email:
                the_list.append(n)
        for n in array2:
            if n.email == current_user.email:
                the_list.append(n)
        x = the_list.reverse()

    context = {"form": form, "item": the_list}
    return render(request=request, template_name='bucket_transactions.html', context=context)
    

@require_POST
@csrf_exempt
def merrybillsWebhook(request):
    data = json.loads(request.body)
    try:
        ref = data['transaction']['request_id']
        status = data['transaction']['status']
        find = Transact.objects.get(request_id=ref)
        if status == 'completed':
            find.status = "Successful"
        else:
            cost = float(find.cost)
            cus = find.user
            old = cus.balance
            cus.fund(cus.id, cost)
            find.status = "Unsuccessful"
            record(cus, cost, old, "Airtime Successfully Refunded")
        find.save()
        print('merrybills')
        print(status)
    except:
        pass
    return HttpResponse(status=200)


@require_POST
@csrf_exempt
def autopilotWebhook(request):
    try:
        data = json.loads(request.body)
        ref = data['data']['yourReference']
        status = data['status']
        find = Transact.objects.get(request_id=ref)
        if status is True:
            find.status = "Successful"
            find.transaction = data['data']['message']
        else:
            pass
        find.save()
    except:
        pass
    return HttpResponse(status=200)
    
    
def wallet_query(request):
    form = WalletForm()
    current_user = request.user
    if Wallet_summary.objects.filter(user=current_user).exists():
        array = Wallet_summary.objects.filter(user=current_user)
        the_list = []
        for n in array:
            # if n.user == current_user:
            the_list.append(n)
        x = the_list.reverse()
    else:
        the_list = []
    if request.method == "POST":
        form = WalletForm(request.POST)
        obj = request.POST["query"]
        if Wallet_summary.objects.filter(user=current_user).exists():
            array = Wallet_summary.objects.filter(user=current_user,product__icontains=obj).all()
            the_list = []
            for n in array:
                the_list.append(n)
            x = the_list.reverse()
        else:
            the_list = []
        
    page = request.GET.get("page", 1)
    paginator = Paginator(the_list, 15)
    try:
        transactions = paginator.page(page)
    except PageNotAnInteger:
        transactions = paginator.page(1)
    except EmptyPage:
        transactions = paginator.page(paginator.num_pages)
        
    current_page = transactions.number
    total_pages = paginator.num_pages

    # Define how many pages to show before and after current
    page_window = 2

    start_page = max(current_page - page_window, 1)
    end_page = min(current_page + page_window, total_pages)

    custom_page_range = range(start_page, end_page + 1)


    # context = {"item": transactions,"custom_page_range": custom_page_range}

    context = {"form": form, "item": transactions,"custom_page_range": custom_page_range}
    return render(request=request, template_name='wallet.html', context=context)   


# # PROVIDUS WEBHOOK

# @require_POST
# @csrf_exempt
# def providus_webhook(request):
#     data = request.body
#     result = json.loads(data)
#     forwarded_for = u'{}'.format(request.META.get('REMOTE_ADDR'))
#     signature = request.META.get('HTTP_X_AUTH_SIGNATURE')
#     # whitelist = ['154.113.165.53', '197.210.47.23']
#     whitelist = ['154.113.165.53', '197.210.47.23', '154.113.16.42', '212.100.69.82']
    
#     table = Config.objects.get(pk=1)

#     Client_Id = table.providus_client_id
#     ClientSecret = table.providus_client_secret
    
#     a = f"{Client_Id}:{ClientSecret}"
#     c = bytes(a, 'utf-8')
#     hashkey = hashlib.sha512(c).hexdigest().upper()

#     # forwarded_for in whitelist

#     if signature.upper() != hashkey.upper():

#         datas = {
#             "requestSuccessful": True, "sessionId": result['settlementId'], "responseMessage": "rejected",
#             "responseCode": "02"
#         }
#         return HttpResponse(data=json.dumps(datas), status=400)


#     elif not result['settlementId'] or not result['accountNumber']:
#         datas = {
#             "requestSuccessful": True, "sessionId": result['settlementId'], "responseMessage": "rejected",
#             "responseCode": "02"
#         }
#         return HttpResponse(data=json.dumps(datas), status=400)

#     elif not forwarded_for in whitelist:

#         datas = {
#             "requestSuccessful": True, "sessionId": result['settlementId'], "responseMessage": "rejected",
#             "responseCode": "02"
#         }
#         return HttpResponse(data=json.dumps(datas), status=400)


#     else:
#         acct_no = result['accountNumber']

#         try:
#             ref = PayRef.objects.get(reference=result['settlementId'])
#             msg = "Duplicate Transaction"
#             code = "01"

#         except:
#             user = AppUser.objects.get(providus_accounts=acct_no)
#             PayRef.objects.create(
#                 user=user,
#                 reference=result['settlementId'],
#               )
               
#             amount = float(result['transactionAmount'])
            
#             if amount < 9999:
#                     charges = 40
#                     amount -= float(charges)

#             else:
#                     charges = 90
#                     amount -= float(charges)
               
#             msg = "success"
#             code = "00"

#             pay = providus_fund(amount, user)
            
#         datas = {
#                 "requestSuccessful": True, "sessionId": result['settlementId'], "responseMessage": msg,
#                 "responseCode": code
#             }

#         return HttpResponse(json.dumps(datas), status=200)



# PAYVESSEL WEBHOOK

@require_POST
@csrf_exempt
def payvessel_payment_done(request):
    payload = request.body
    table = Config.objects.get(pk=1)
    payvessel_signature = request.META.get('HTTP_PAYVESSEL_HTTP_SIGNATURE')
    ip_address = u'{}'.format(request.META.get('REMOTE_ADDR'))
    secret = bytes(table.payvessel_sk_key, 'utf-8')
    hashkey = hmac.new(secret, request.body, hashlib.sha512).hexdigest()

    if payvessel_signature == hashkey:
        if ip_address == "162.246.254.36" or ip_address == "3.255.23.38":
            data = json.loads(payload)
            email = data["customer"]["email"]
            amount = float(data['order']["amount"])
            # settlementAmount = float(data['order']["settlement_amount"])
            fee = float(data['order']["fee"])
            reference = data['transaction']["reference"]
            description = data['order']["description"]
            
            settlementAmount = amount


            try:
                ref = PayRef.objects.get(reference=reference)
                datas = {"message": "Transaction already exist", }
                return HttpResponse(json.dumps(datas), status=200)

            except PayRef.DoesNotExist:
                user = AppUser.objects.get(email=email)
                PayRef.objects.create(
                user=user,
                reference=reference,
                  )
                pay = payvessel_fund(settlementAmount, user)
            
                datas = {"message": "success", }
                return HttpResponse(json.dumps(datas), status=200)
            
    datas = {"message": "Permission denied, invalid hash or ip address.", }
    return HttpResponse(json.dumps(datas), status=400)



# GET DATA PLANS
def Getdata(request):
    mtn_price = Mtnsmedata.objects.all()
    mtncg_price = Giftingdata.objects.all()
    glo_price = Glodata.objects.all()
    glocg_price = Glocgdata.objects.all()
    gloawoof_price = Glospecialdata.objects.all()
    airtel_price = Airteldata.objects.all()
    airtelcg_price = Airtelcgdata.objects.all()
    airtelawoof_price = Airtelawoofgifting.objects.all()
    mobile_price = Mobiledata.objects.all()
    mobilesme_price = Mobilesmedata.objects.all()
    mtncoupon_price = Mtncoupon.objects.all()
    mtndatashare_price = Mtndatashare.objects.all()
    mtndirectgifting_price = Mtndirectgifting.objects.all()
    mtnawoofgifting_price = Mtnawoofgifting.objects.all()


    
    # CHECK LOCKS
    mtn = []
    if Lockdata.objects.get(pk=10).availability == "ENABLE":
        mtn.append({"type":"MTN-DATASHARE",
                    "plans":[p.volume for p in mtndatashare_price],
                    "price":{p.volume: f"₦{p.amount}  {p.validity}" for p in mtndatashare_price}}
        )
    if Lockdata.objects.get(pk=1).availability == "ENABLE":
        mtn.append({"type":"MTN-SME",
                    "plans":[p.volume for p in mtn_price],
                    "price":{p.volume: f"₦{p.amount}  {p.validity}" for p in mtn_price}})
    if Lockdata.objects.get(pk=13).availability == "ENABLE":
        mtn.append({"type":"MTN-AWOOF-GIFTING",
                    "plans":[p.volume for p in mtnawoofgifting_price],
                    "price":{p.volume: f"₦{p.amount}  {p.validity}" for p in mtnawoofgifting_price}})
    if Lockdata.objects.get(pk=2).availability == "ENABLE":
        mtn.append({"type":"MTN-CG",
                    "plans":[p.volume for p in mtncg_price],
                    "price":{p.volume: f"₦{p.amount}  {p.validity}" for p in mtncg_price}})
    if Lockdata.objects.get(pk=11).availability == "ENABLE":
        mtn.append({"type":"MTN-DG",
                    "plans":[p.volume for p in mtndirectgifting_price],
                    "price":{p.volume: f"₦{p.amount}  {p.validity}" for p in mtndirectgifting_price}})
    if Lockdata.objects.get(pk=9).availability == "ENABLE":
        mtn.append({"type":"MTNDIRECT-COUPON",
                    "plans":[p.volume for p in mtncoupon_price],
                    "price":{p.volume: f"₦{p.amount}  {p.validity}" for p in mtncoupon_price}})
        
    airtel = []
    if Lockdata.objects.get(pk=4).availability == "ENABLE":
        airtel.append({"type":"AIRTEL-CG",
                    "plans":[p.volume for p in airtelcg_price],
                    "price":{p.volume: f"₦{p.amount}  {p.validity}" for p in airtelcg_price}})
    if Lockdata.objects.get(pk=3).availability == "ENABLE":
        airtel.append({"type":"AIRTEL",
                    "plans":[p.volume for p in airtel_price],
                    "price":{p.volume: f"₦{p.amount}  {p.validity}" for p in airtel_price}})
    if Lockdata.objects.get(pk=12).availability == "ENABLE":
        airtel.append({"type":"AIRTEL-AWOOF",
                    "plans":[p.volume for p in airtelawoof_price],
                    "price":{p.volume: f"₦{p.amount}  {p.validity}" for p in airtelawoof_price}})
    
    glo = []
    if Lockdata.objects.get(pk=6).availability == "ENABLE":
        glo.append({"type":"GLO-CG",
                    "plans":[p.volume for p in glocg_price],
                    "price":{p.volume: f"₦{p.amount}  {p.validity}" for p in glocg_price}})
                    
    if Lockdata.objects.get(pk=15).availability == "ENABLE":
        glo.append({"type":"GLO-AWOOF-GIFTING",
                    "plans":[p.volume for p in gloawoof_price],
                    "price":{p.volume: f"₦{p.amount}  {p.validity}" for p in gloawoof_price}})
                    
    if Lockdata.objects.get(pk=5).availability == "ENABLE":
        glo.append({"type":"GLO",
                    "plans":[p.volume for p in glo_price],
                    "price":{p.volume: f"₦{p.amount}  {p.validity}" for p in glo_price}})
        
    mobile = []
    if Lockdata.objects.get(pk=8).availability == "ENABLE":
        mobile.append({"type":"9MOBILE-CG",
                    "plans":[p.volume for p in mobilesme_price],
                    "price":{p.volume: f"₦{p.amount}  {p.validity}" for p in mobilesme_price}})
    if Lockdata.objects.get(pk=7).availability == "ENABLE":
        mobile.append({"type":"9MOBILE",
                    "plans":[p.volume for p in mobile_price],
                    "price":{p.volume: f"₦{p.amount}  {p.validity}" for p in mobile_price}})
        
    # END CHECK LOCKS
    
    
    data = {'network': ["MTN", "AIRTEL", "GLO", "9MOBILE"], 'MTN': mtn, 'GLO': glo, 'AIRTEL': airtel, '9MOBILE': mobile,}
    
    datas = json.dumps(data, ensure_ascii=False)
    return HttpResponse(datas, content_type="application/json")


def data_page(request):
    mtn_plans = []
    airtel_plans = []
    glo_plans = []
    mobile_plans = []

    # MTN
    if Lockdata.objects.get(pk=10).availability == "ENABLE":
        mtn_plans.extend([
            {
                "type": "MTN DataShare",
                "plans": list(
                    Mtndatashare.objects.values("volume", "amount", "validity")
                )
            }
        ])

    if Lockdata.objects.get(pk=1).availability == "ENABLE":
        mtn_plans.extend([
            {
                "type": "MTN SME",
                "plans": list(
                    Mtnsmedata.objects.values("volume", "amount", "validity")
                )
            }
        ])

    if Lockdata.objects.get(pk=13).availability == "ENABLE":
        mtn_plans.extend([
            {
                "type": "MTN Awoof Gifting",
                "plans": list(
                    Mtnawoofgifting.objects.values("volume", "amount", "validity")
                )
            }
        ])

    if Lockdata.objects.get(pk=2).availability == "ENABLE":
        mtn_plans.extend([
            {
                "type": "MTN Gifting",
                "plans": list(
                    Giftingdata.objects.values("volume", "amount", "validity")
                )
            }
        ])

    if Lockdata.objects.get(pk=11).availability == "ENABLE":
        mtn_plans.extend([
            {
                "type": "MTN Direct Gifting",
                "plans": list(
                    Mtndirectgifting.objects.values("volume", "amount", "validity")
                )
            }
        ])

    if Lockdata.objects.get(pk=9).availability == "ENABLE":
        mtn_plans.extend([
            {
                "type": "MTN Direct Coupon",
                "plans": list(
                    Mtncoupon.objects.values("volume", "amount", "validity")
                )
            }
        ])

    # Airtel
    if Lockdata.objects.get(pk=4).availability == "ENABLE":
        airtel_plans.append({
            "type": "Airtel CG",
            "plans": list(
                Airtelcgdata.objects.values("volume", "amount", "validity")
            )
        })

    if Lockdata.objects.get(pk=3).availability == "ENABLE":
        airtel_plans.append({
            "type": "Airtel",
            "plans": list(
                Airteldata.objects.values("volume", "amount", "validity")
            )
        })

    if Lockdata.objects.get(pk=12).availability == "ENABLE":
        airtel_plans.append({
            "type": "Airtel Awoof",
            "plans": list(
                Airtelawoofgifting.objects.values("volume", "amount", "validity")
            )
        })

    # Glo
    if Lockdata.objects.get(pk=6).availability == "ENABLE":
        glo_plans.append({
            "type": "Glo CG",
            "plans": list(
                Glocgdata.objects.values("volume", "amount", "validity")
            )
        })

    if Lockdata.objects.get(pk=15).availability == "ENABLE":
        glo_plans.append({
            "type": "Glo Awoof Gifting",
            "plans": list(
                Glospecialdata.objects.values("volume", "amount", "validity")
            )
        })

    if Lockdata.objects.get(pk=5).availability == "ENABLE":
        glo_plans.append({
            "type": "Glo",
            "plans": list(
                Glodata.objects.values("volume", "amount", "validity")
            )
        })

    # 9mobile
    if Lockdata.objects.get(pk=8).availability == "ENABLE":
        mobile_plans.append({
            "type": "9mobile CG",
            "plans": list(
                Mobilesmedata.objects.values("volume", "amount", "validity")
            )
        })

    if Lockdata.objects.get(pk=7).availability == "ENABLE":
        mobile_plans.append({
            "type": "9mobile",
            "plans": list(
                Mobiledata.objects.values("volume", "amount", "validity")
            )
        })

    context = {
        "mtn_plans": mtn_plans,
        "airtel_plans": airtel_plans,
        "glo_plans": glo_plans,
        "mobile_plans": mobile_plans,

        "data_catalogue": {
            "MTN": mtn_plans,
            "AIRTEL": airtel_plans,
            "GLO": glo_plans,
            "9MOBILE": mobile_plans,
        },
    }

    return render(request, "public_data.html", context)

def robots_txt(request):
    content = """User-agent: *
Allow: /

Sitemap: https://exactsub.com/sitemap.xml
"""
    return HttpResponse(content, content_type="text/plain")

# GET CABLE PLANS
def Getcable(request):
    dstv_price = Dstv.objects.all()
    gotv_price = Gotv.objects.all()
    startimes_price = Startimes.objects.all()
    dstv = []
    gotv = []
    star = []
    dstv.append({"service":"dstv",
                    "plans":[p.package for p in dstv_price],
                    "price":{p.package: f"₦{p.amount}" for p in dstv_price}})
    gotv.append({"service":"gotv",
                    "plans":[p.package for p in gotv_price],
                    "price":{p.package: f"₦{p.amount}" for p in gotv_price}})
    star.append({"service":"startimes",
                    "plans":[p.package for p in startimes_price],
                    "price":{p.package: f"₦{p.amount}" for p in startimes_price}})              
                    
    
    data = {'DSTV': dstv, 'GOTV': gotv, 'STARTIMES': star}
    
    datas = json.dumps(data, ensure_ascii=False)
    return HttpResponse(datas, content_type="application/json")

def Getelectricity(request):
    electricity_charges = Electricity.objects.all()
    a = []
    a.append({"services":[p.service for p in electricity_charges],
                    "charges":{p.name +" : "+ p.service: f"₦{p.discount}" for p in electricity_charges}})              
                    
    
    data = {'Electricity Bills': a}
    
    datas = json.dumps(data, ensure_ascii=False)
    return HttpResponse(datas, content_type="application/json")
    
def Getresult_checker(request):
    result_price = ResultPin.objects.all()
    a = []
    a.append({"exam_type":[p.exam_type for p in result_price],
                    "charges":{p.exam_type: f"₦{p.price}" for p in result_price}})              
                    
    
    data = {'Exam Pin': a}
    
    datas = json.dumps(data, ensure_ascii=False)
    return HttpResponse(datas, content_type="application/json")
    
    
 # GET DATA PLANS
def Getdatatypes(request):
    
    # CHECK LOCKS
    mtn = []
    if Lockdata.objects.get(pk=10).availability == "ENABLE":
        mtn.append("MTN-SPECIAL-DATA")
    if Lockdata.objects.get(pk=1).availability == "ENABLE":
        mtn.append("MTN-SME")
    if Lockdata.objects.get(pk=13).availability == "ENABLE":
        mtn.append("MTN-AWOOF-GIFTING")
    if Lockdata.objects.get(pk=2).availability == "ENABLE":
        mtn.append("MTN-CG")
    if Lockdata.objects.get(pk=11).availability == "ENABLE":
        mtn.append("MTN-DG")
    if Lockdata.objects.get(pk=9).availability == "ENABLE":
        mtn.append("MTNDIRECT-COUPON")
        
    airtel = []
    if Lockdata.objects.get(pk=4).availability == "ENABLE":
        airtel.append("AIRTEL-CG")
    if Lockdata.objects.get(pk=3).availability == "ENABLE":
        airtel.append("AIRTEL")
    if Lockdata.objects.get(pk=12).availability == "ENABLE":
        airtel.append("AIRTEL-AWOOF")
    
    glo = []
    if Lockdata.objects.get(pk=6).availability == "ENABLE":
        glo.append("GLO-CG")
    if Lockdata.objects.get(pk=5).availability == "ENABLE":
        glo.append("GLO")
    if Lockdata.objects.get(pk=15).availability == "ENABLE":
        glo.append("GLO-AWOOF-GIFTING")
        
    mobile = []
    if Lockdata.objects.get(pk=8).availability == "ENABLE":
        mobile.append("9MOBILE-CG")
    if Lockdata.objects.get(pk=7).availability == "ENABLE":
        mobile.append("9MOBILE")
        
    # END CHECK LOCKS
    
    
    data = {'MTN': mtn, 'GLO': glo, 'AIRTEL': airtel, '9MOBILE': mobile,}
    
    datas = json.dumps(data, ensure_ascii=False)
    return HttpResponse(datas, content_type="application/json")  
    


@view_decorator
def set_fcm_token(request):
    token = request.GET.get('fcm_token')
    user = request.user
    user.fcm_token = token
    user.save(update_fields=['fcm_token'])
    subscribe_to_topic(token)
    message = {"status": "Successful","message":"FCM Token Received."}
    datas = json.dumps(message)
    return HttpResponse(datas, content_type="application/json", status=200)





# PAYSCRIBE WEBHOOK
@require_POST
@csrf_exempt
def payscribe_payment_done(request):
    payload = request.body
    table = Config.objects.get(pk=1)
    data = json.loads(payload)
    pay_hash = data['transaction_hash']
    ip_address = u'{}'.format(request.META.get('REMOTE_ADDR'))
    amt = data['amount']
    amnt = f"{amt:.2f}"
    secret = bytes(table.payscribe_sk_key+data['transaction']['sender_account']+data['customer']['number']+data['transaction']['bank_code']+amnt+data['trans_id'], 'utf-8')
    # secretH = bytes(table.payscribe_sk_key, 'utf-8')
    hashkey = hashlib.sha512(secret).hexdigest()
    # hashkey = hmac.new(secret, hashlib.sha512).hexdigest()
    
    # print(pay_hash)
    # print(hashkey)


    if pay_hash == hashkey.upper() and ip_address == "162.254.34.78":
        # data = json.loads(payload)
        cus_id = data["customer"]["id"]
        amount = float(data["amount"])
        fee = float(0.7/100*amount)
        settlementAmount = round(amount-fee, 2)
        reference = data['trans_id']


        try:
            ref = PayRef.objects.get(reference=reference)
            datas = {"message": "Transaction already exist", }
            return HttpResponse(json.dumps(datas), status=200)

        except PayRef.DoesNotExist:
            user = AppUser.objects.get(payscribe_cus_id=cus_id)
            PayRef.objects.create(
                user=user,
                reference=reference,
               )
            pay = payscribe_fund(settlementAmount, user)
            
            datas = {"message": "success", }
            return HttpResponse(json.dumps(datas), status=200)
            
    datas = {"message": "Permission denied, invalid hash or ip address.", }
    return HttpResponse(json.dumps(datas), status=400)



# PAYMENTPOINT WEBHOOK
@require_POST
@csrf_exempt
def paymentpoint_payment_done(request):
    payload = request.body
    table = Config.objects.get(pk=1)
    
    signature = u'{}'.format(request.META.get('HTTP_PAYMENTPOINT_SIGNATURE'))
    secret = bytes(table.paymentpoint_secret_key, 'utf-8')
    pay_hash = hmac.new(secret, payload, hashlib.sha256).hexdigest()
    
    
    if pay_hash == signature:
        data = json.loads(payload)
        cus_id = data["customer"]["email"]
        amt = float(data["amount_paid"])
        # settlementAmount = float(data["settlement_amount"])
        reference = data['transaction_id']
        
        # fee = 0.5/100 * amt
        settlementAmount = amt 


        try:
            ref = PayRef.objects.get(reference=reference)
            datas = {"message": "Transaction already exist", }
            return HttpResponse(json.dumps(datas), status=200)

        except PayRef.DoesNotExist:
            user = AppUser.objects.get(email=cus_id)
            PayRef.objects.create(
                user=user,
                reference=reference,
               )
            pay = paymentpoint_fund(settlementAmount, user)
            
            datas = {"message": "success", }
            return HttpResponse(json.dumps(datas), status=200)
            
    datas = {"message": "Permission denied, invalid hash or ip address.", }
    return HttpResponse(json.dumps(datas), status=400)


# PALMPAY DIRECT WEBHOOK
@require_POST
@csrf_exempt
def pay_palmpay(request):
    payload = request.body
    return palmpay_payment_done(payload)
    

    
    
# PALMPAY DIRECT WEBHOOK FOR DYNAMIC
@require_POST
@csrf_exempt
def pay_palmpay_dynamic(request):
    payload = request.body
    dat = json.loads(payload)
    # print(dat)
    check_sign = palmpay_payment_done_dynamic(payload)
    
    if check_sign is True:
                # print ('palmpay notified')
                if dat["orderStatus"] == 2:
                          ref = dat["orderNo"]
                          account = WhatsAppUser.objects.get(order_id = ref)
                          amount = (dat['amount'])/100 - 10
                          
                           
                        #   ref = dat["orderNo"]
                           
                          if not DynamicPayRef.objects.filter(reference=ref).exists():
                                try:
                                    old_bal = account.balance
    
                                    new_bal = old_bal + amount
                                    account.fund(account.id, amount)
                                    DynamicPayRef.objects.create(
                                        user=account,
                                        reference=ref,)
                                        
                                    Guest_Wallet_summary.objects.create(user= account, product="Direct PalmPay Funding", amount = amount, previous_balance = old_bal, after_balance= new_bal)
                                    
                                    try:
                                        if not account.first_fund:
                                            if account.referer:
                                                mb = account.referer
                                                mboss = WhatsAppUser.objects.get(username = mb)
                                                
                                                table = Config.objects.get(pk=1)
                                                bonus = float(table.referral_bonus)
                                                mboss.fundbonus(mboss.id, bonus)
                                                acc = WhatsAppUser.objects.get(pk= account.id)
                                                acc.first_fund = True
                                                acc.save()
                                            else:
                                                acc = WhatsAppUser.objects.get(pk= account.id)
                                                acc.first_fund = True
                                                acc.save()
                                    except:
                                        pass
                                            
                                            
                                        
                                    
                                    
                                    keys = "EAAcsSgCLQsABPpbbQB1Oddx4MKYTRPbN98YqBmkaqCjI7vPaSxOkJNHZAAmn7hGnpmVmzCoQksbu6vZBAZCJPDjyiZBRuVLALnM6mAOvGqOUXiJ6fzyTIyvW6uU2LnlAXyow6CwL9PAmFqk8OX4BB1cY1r13ckrMbZAQPuAqJ5eoCcwbtq1MGIoZANpZBlLKlkxaAZDZD"
            
            
            
                                    url = "https://graph.facebook.com/v22.0/828938420299590/messages"

                                    headers = {
                                            "Content-Type": "application/json",
                                            "Authorization": f"Bearer {keys}"
                                            }
                                    

                                    try:
                                        
                                        body = {
                                            "messaging_product": "whatsapp",
                                            "recipient_type": "individual",
                                            "to": account.phoneNumber,
                                            "type": "text",
                                            "text": {
                                                "body": f"Your Payment of ₦{amount} Has Been Received, Your Order is Now Being Processed",
                                                "preview_url": True,
                                                }
                                            }
            
                                        response = requests.post(url, headers=headers, json=body)
                                        
                                        return HttpResponse('success',status=200)
                                    finally:
                                        myBot = WhatsApp(account.phoneNumber,"XCONFIRMX",account.username)
                                        botSays = myBot.myFunc()

            
                                        for cargos in botSays:
                                            body = {
                                                "messaging_product": "whatsapp",
                                                "recipient_type": "individual",
                                                "to": account.phoneNumber,
                                                "type": "interactive",
                                                "markdown":True,
                                                "interactive": cargos
                                                }

                                            response = requests.post(url, headers=headers, json=body)
                
                                except:
                                    pass

                          else:
                                 return HttpResponse('success',status=200)


    else:
            return HttpResponse('Permission Denied',status=400)
    
    return HttpResponse('success',status=200)





def ipay(request):
    # table = Config.objects.get(pk=1)
    form = IpayForm()
    user = request.user
    if request.method == "POST":
        form = IpayForm(request.POST)
        sess = request.POST['sessionID']
        amt = request.POST['amount']
        url = "https://ipayng.com/api/live/v1/automanual"
        headers = {
            "Authorization": "Bearer live_9341b204a5b3490d866fb59e2ae505506n40w429",
            "Content-Type": "application/json",

        }
        def request_id_gen():
            # Request ID generator
            date_time = datetime.now()
            the_date = date_time.strftime("%Y%m%d%H%M")
            tok = uuid.uuid4()
            token = tok.hex
            req = the_date + token
            request_id = req[0:21]
            return request_id + "ipay"
        ref = request_id_gen()
        parameters = {
            "accountNo": "8108148459",
            "sessionIdOrReference": sess,
            "amount": amt,
            "reference": ref,
        }
        print(parameters)
        response = requests.post(url, headers=headers, json=parameters)
        res = response.json()
        print(res)
        data = {'message': "Order received and will be processed shortly", 'status': 'Successful'}
        datas = json.dumps(data)
        return HttpResponse(datas, content_type="application/json")
        
    context = {"form": form}
    return render(request=request, template_name="ipay.html", context=context)





@login_required
def receipt(request):

    ident = request.GET.get("ident")

    if not ident:
        return render(
            request,
            "data_reciept.html",
            {
                "item": None,
                "delivery": None,
                "delivery_data": {},
                "exam_pins": [],
                "electricity_token": "",
                "electricity_units": "",
                "service_category": "Transaction",
                "receipt_message": "",
                "receipt_error": (
                    "No transaction reference was provided."
                ),
            }
        )

    # ---------------------------------------------------------
    # GET USER'S TRANSACTION
    # ---------------------------------------------------------

    trans = (
        Transact.objects
        .filter(
            user=request.user,
            request_id=ident
        )
        .order_by("-id")
        .first()
    )

    if trans is None:
        return render(
            request,
            "data_reciept.html",
            {
                "item": None,
                "delivery": None,
                "delivery_data": {},
                "exam_pins": [],
                "electricity_token": "",
                "electricity_units": "",
                "service_category": "Transaction",
                "receipt_message": "",
                "receipt_error": (
                    "Transaction receipt not found."
                ),
            }
        )

    # ---------------------------------------------------------
    # GET STRUCTURED DELIVERY DATA
    # ---------------------------------------------------------

    delivery = (
        TransactionDelivery.objects
        .filter(transaction_id=trans.id)
        .first()
    )

    delivery_data = {}
    exam_pins = []
    electricity_token = ""
    electricity_units = ""

    # ---------------------------------------------------------
    # PARSE DELIVERY JSON
    # ---------------------------------------------------------

    if delivery and delivery.data:

        try:
            parsed_data = json.loads(delivery.data)

            if isinstance(parsed_data, dict):
                delivery_data = parsed_data

        except (TypeError, ValueError):
            delivery_data = {}

    # ---------------------------------------------------------
    # ELECTRICITY DELIVERY
    # ---------------------------------------------------------

    if (
        delivery
        and delivery.delivery_type == "ELECTRICITY"
    ):

        electricity_token = str(
            delivery_data.get("token", "")
        ).strip()

        electricity_units = str(
            delivery_data.get("units", "")
        ).strip()

    # ---------------------------------------------------------
    # EXAM PIN DELIVERY
    # ---------------------------------------------------------

    if (
        delivery
        and delivery.delivery_type == "EXAM_PIN"
    ):

        pins = delivery_data.get("pins", [])

        if isinstance(pins, list):
            exam_pins = pins

    # ---------------------------------------------------------
    # DETERMINE SERVICE CATEGORY
    # ---------------------------------------------------------

    d_network = str(
        getattr(trans, "d_network", "")
        or ""
    ).strip().lower()

    value = str(
        getattr(trans, "value", "")
        or ""
    ).strip().lower()

    plan = str(
        getattr(trans, "plan", "")
        or ""
    ).strip().lower()

    service_category = "Transaction"

    if (
        "electric" in d_network
        or "electric" in value
        or "electric" in plan
        or (
            delivery
            and delivery.delivery_type == "ELECTRICITY"
        )
    ):

        service_category = "Electricity"

    elif (
        "exam" in d_network
        or "exam" in value
        or "exam" in plan
        or (
            delivery
            and delivery.delivery_type == "EXAM_PIN"
        )
    ):

        service_category = "Exam PIN"

    elif (
        "airtime" in d_network
        or "airtime" in value
        or "airtime" in plan
    ):

        service_category = "Airtime"

    elif (
        "data" in d_network
        or "data" in value
        or "data" in plan
    ):

        service_category = "Data"

    elif (
        "cable" in d_network
        or "cable" in value
        or "cable" in plan
        or "tv" in d_network
        or "tv" in value
        or "tv" in plan
    ):

        service_category = "Cable TV"

    elif (
        "wallet" in d_network
        or "wallet" in value
        or "wallet" in plan
        or "funding" in plan
    ):

        service_category = "Wallet Funding"

    # ---------------------------------------------------------
    # CUSTOMER-FACING RECEIPT MESSAGE
    # ---------------------------------------------------------

    receipt_message = trans.transaction or ""

    if (
        service_category == "Data"
        and trans.status == "Unsuccessful"
    ):

        receipt_message = (
            "Transaction failed. If your wallet was debited, "
            "your refund will be processed automatically."
        )

    # ---------------------------------------------------------
    # BALANCES
    # ---------------------------------------------------------

    old_balance = getattr(
        trans,
        "old_balance",
        None
    )

    new_balance = getattr(
        trans,
        "new_balance",
        None
    )

    # ---------------------------------------------------------
    # CONTEXT
    # ---------------------------------------------------------

    context = {
        "item": trans,
        "delivery": delivery,
        "delivery_data": delivery_data,
        "exam_pins": exam_pins,
        "electricity_token": electricity_token,
        "electricity_units": electricity_units,
        "service_category": service_category,
        "receipt_message": receipt_message,
        "old_balance": old_balance,
        "new_balance": new_balance,
        "receipt_error": "",
    }

    return render(
        request,
        "data_reciept.html",
        context
    )

# WHATSAPP WEBHOOK

@csrf_exempt
def whatsapp(request):
    
    if request.method == "POST":
            payload = request.body
            resp = json.loads(payload)
            print(f"this is payload {resp}")
            
            try:
                return HttpResponse(status=200)
            finally:
                
                try:
                    phone = resp['entry'][0]['changes'][0]['value']['contacts'][0]['wa_id']
                    profile_name = resp['entry'][0]['changes'][0]['value']['contacts'][0]['profile']['name']
                    wami = resp['entry'][0]['changes'][0]['value']['messages'][0]['id']
                    
                    if 'interactive' in resp['entry'][0]['changes'][0]['value']['messages'][0]:
                        if 'button_reply' in resp['entry'][0]['changes'][0]['value']['messages'][0]['interactive']:
                            message = resp['entry'][0]['changes'][0]['value']['messages'][0]['interactive']['button_reply']['id']
                        else:
                            message = resp['entry'][0]['changes'][0]['value']['messages'][0]['interactive']['list_reply']['id']
                    else:
                        message = resp['entry'][0]['changes'][0]['value']['messages'][0]['text']['body']
                    
                    realphone = "0" + phone[3:]
                    # print(realphone)
                    # print(message)
                    # if message == "atunzdbaba":
                    #     return HttpResponse(status=200)
                    
                    
                    
                    keys = "EAAcsSgCLQsABPpbbQB1Oddx4MKYTRPbN98YqBmkaqCjI7vPaSxOkJNHZAAmn7hGnpmVmzCoQksbu6vZBAZCJPDjyiZBRuVLALnM6mAOvGqOUXiJ6fzyTIyvW6uU2LnlAXyow6CwL9PAmFqk8OX4BB1cY1r13ckrMbZAQPuAqJ5eoCcwbtq1MGIoZANpZBlLKlkxaAZDZD"
                    
                    # url = "https://graph.facebook.com/v22.0/708564979017777/messages"
                    
                    url = "https://graph.facebook.com/v22.0/828938420299590/messages"
        
                    headers = {
                        "Content-Type": "application/json",
                        "Authorization": f"Bearer {keys}"
                    }
                    
                        
                    typing = {
                        "messaging_product": "whatsapp",
                        "status": "read",
                        "message_id": wami,
                        "typing_indicator": {
                            "type": "text"
                            }
                    }
                    
                    
                    resp = requests.post(url, headers=headers, json=typing)
                    # print(f'TYPING {resp.text}')
                    
                    if message == "atunzdbaba":
                        
                    
                        body = {
                            "messaging_product": "whatsapp",
                            "recipient_type": "individual",
                            "to": phone,
                            "type": "text",
                            "text": {
                                "body": f"Yes *{profile_name}*, you can click on the link to visit our site, or better still reply this message to continue vending from me 😊",
                                "preview_url": True,
                            }
                        }
                        
                        resp = requests.post(url, headers=headers, json=body)
                        
                        return HttpResponse(status=200)
                    
                    myBot = WhatsApp(realphone,message,profile_name)
                    botSays = myBot.myFunc()
                    # print(botSays)
                    
                    for cargos in botSays:
                        body = {
                            "messaging_product": "whatsapp",
                            "recipient_type": "individual",
                            "to": phone,
                            "type": "interactive",
                            "markdown":True,
                            "interactive": cargos
                        }
                        # print(body)
        
                        response = requests.post(url, headers=headers, json=body)
                        # print(response.text)
                    
                    
                except:
                    pass
                
                # return HttpResponse(status=200)
                
    elif request.method == "GET":
                print("YES WHATSAPP CAME THROUGH")
                mode = request.GET.get('hub.mode')
                challenge = request.GET.get('hub.challenge')
                token = request.GET.get('hub.verify_token')
                print(challenge)
                print(token)
            
                if token == "Atunsdev8459" and mode == "subscribe":
                    return HttpResponse(challenge, status=200)
                else:
                    return HttpResponse(status=400)
    else:
                return HttpResponse(status=403)

    
# SECUREWAVE WEBHOOK
@require_POST
@csrf_exempt
def securewave_payment_done(request):
    payload = request.body
    table = Config.objects.get(pk=1)
    
    signature = request.headers.get('X-Signature')
    secret = bytes(table.securewave_secret_key, 'utf-8')
    pay_hash = hmac.new(secret, payload, hashlib.sha256).hexdigest()
    
    
    if pay_hash == signature:
        data = json.loads(payload)
        cus_id = data["customer"]["email"]
        amt = float(data["amount"])
        # settlementAmount = float(data["settlement_amount"])
        reference = data['transaction_id']
        
        # fee = 0.5/100 * amt
        # settlementAmount = amt 


        try:
            ref = PayRef.objects.get(reference=reference)
            datas = {"message": "Transaction already exist", }
            return HttpResponse(json.dumps(datas), status=200)

        except PayRef.DoesNotExist:
            user = AppUser.objects.get(email=cus_id)
            PayRef.objects.create(
                user=user,
                reference=reference,
               )
            pay = online_fund(cus_id, amt, user)
            
            datas = {"message": "success", }
            return HttpResponse(json.dumps(datas), status=200)
            
    datas = {"message": "Permission denied, invalid hash or ip address.", }
    return HttpResponse(json.dumps(datas), status=400)


def email_preview(request):
    return render(
        request,
        "email.html",
        {
            "user_name": "Lukman",
            "subject": "Welcome to ExactSub",
            "message": """
                <p>Welcome to ExactSub. Your account has been successfully created.</p>

                <p>You can now enjoy fast and reliable access to data, airtime,
                cable subscriptions, electricity payments and other services.</p>

                <p>Thank you for choosing ExactSub.</p>
            """,
        },
    )
