import os
from django.views.decorators.cache import cache_page
from django.views.decorators.vary import vary_on_cookie
from django.conf import settings
from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa
from django.contrib.staticfiles import finders
from itertools import chain
import reportlab
import io
from django.conf import settings
from django.shortcuts import redirect
import plotly.express as px
from django.http import FileResponse
from reportlab.pdfgen import canvas
from django.views.decorators.csrf import csrf_exempt
from django.contrib import messages
from datetime import datetime
from django.shortcuts import render
from django.shortcuts import render, redirect
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.authtoken.models import Token
from rest_framework.decorators import api_view, permission_classes
from .serializer import RadcheckSerializer
from .serializer import InvoiceTypeSerializer
from .serializer import RadgroupreplySerializer
from .serializer import  RadacctSerializer
from .serializer import  RadusergroupSerializer
from .serializer import  PaymentSerializer
from .serializer import  BillingPlansSerializer
from .serializer import  UserbillinfoSerializer
from .serializer import OperatorsSerializer
from customer.models import Operators
from customer.models import InvoiceStatus
from customer.models import InvoiceType
from .serializer import  UserSerializer
from .serializer import  BillingHistorySerializer
from .serializer import  NasSerializer
from .serializer import  InvoiceItemsSerializer
from .serializer import  BillingMerchantSerializer
from rest_framework.permissions import AllowAny
from customer.models import Radusergroup
from customer.models import InvoiceItems
from customer.models import AuthUser
from customer.models import BillingPlans
from customer.models import Radgroupreply
from customer.models import Nas
from customer.models import Radacct
from customer.models import Radreply
from customer.models import Registration
from customer.models import Payment
from customer.models import Userbillinfo
from django.contrib import messages
from customer.models import BillingHistory
from customer.models import BillingMerchant
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
import json
import requests
import threading
from .models import Radcheck
import asyncio
import aiohttp
import os
import platform
import urllib.request, json
import datetime
import base64
import asyncio
import aiohttp
from rest_framework.authtoken.models import Token
from rest_framework import permissions
from django.http import JsonResponse
os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"
from django.shortcuts import render
from io import BytesIO
from django.http import HttpResponse
from django.template.loader import get_template
from django.views import View
from xhtml2pdf import pisa
@api_view(['GET'])
def apioverview(request):
    api_urls ={
        "list":'/user-list/',
        "Detail": '/user-detail/<int:id>',
        "Create": '/user-create/',
        "Radusergroup": '/Radusergroup-create/',
        "update": '/user-update/<int:id>',
        "Delete": '/user-delete/<int:id>',
        "Rad_list": '/Radgroupreply/',
        "list-all": '/Radusergroup/',
        "payment": '/payment/',
        "make-payment": '/make-payment/',
        "userbillinfo": '/userbillinfo/',
        "create-userbillinfo": '/create-userbillinfo/',
        "register": '/register/',
        "create_BillingPlans": '/create_BillingPlans/',
    }
    return Response(api_urls)
@api_view(['GET'])
def Operators_all(request):
    id=request.user
    Operators_data = Operators.objects.filter(planid=f"{request.user}")
    serializer=OperatorsSerializer(Operators_data ,many=True)
    return Response(serializer.data)


@api_view(['GET'])
def BillingMerchant_All(request):
    id=request.user
    BillingMerchant_data = BillingMerchant.objects.filter(planid=f"{request.user}")
    serializer=BillingMerchantSerializer(BillingMerchant_data ,many=True)
    return Response(serializer.data)
@api_view(['GET'])
def draft_list(request):
    id=request.user
    InvoiceType_data = InvoiceType.objects.filter(updateby=f"{request.user}")
    serializer=InvoiceTypeSerializer(InvoiceType_data ,many=True)
    return Response(serializer.data)
@login_required(login_url='auth-login')
def BillingMerchant_list(request):
    from rest_framework.authtoken.models import Token
    user = Token.objects.get_or_create(user=request.user)
    for token in user:
        myToken = token
        myUrl = 'https://helios-radius.com/BillingMerchant_All/'
        head = {'Authorization': 'token {}'.format(myToken)}
        response = requests.get(myUrl, headers=head)
        data=response.json()
        context={
            'data': data,
        }
        return JsonResponse(context)
@api_view(['GET'])
def BillingPlans_All(request):
    id=request.user
    BillingPlans_data = BillingPlans.objects.filter(planid=id).using('radius')
    serializer=BillingPlansSerializer(BillingPlans_data ,many=True)
    return Response(serializer.data)
@api_view(['GET'])
def BillingPlans_hotspot(request):
    id=request.user
    BillingPlans_data = BillingPlans.objects.filter(planid=id,plantype="Hotspot").using('radius')
    serializer=BillingPlansSerializer(BillingPlans_data ,many=True)
    return Response(serializer.data)
@api_view(['GET'])
def BillingPlans_pppoe(request):
    id=request.user
    BillingPlans_data = BillingPlans.objects.filter(planid=id,plantype="Fixed-Pppoe").using('radius')
    serializer=BillingPlansSerializer(BillingPlans_data ,many=True)
    return Response(serializer.data)

@api_view(['GET'])
def InvoiceItem_All(request):
    id=request.user
    InvoiceItems_data = InvoiceItems.objects.all()
    serializer=InvoiceItemsSerializer(InvoiceItems_data ,many=True)
    return Response(serializer.data)


def BillingPlanshotspot(request):
    from rest_framework.authtoken.models import Token
    user = Token.objects.get_or_create(user=request.user)
    for token in user:
        myToken = token
        myUrl = 'https://helios-radius.com/BillingPlans_hotspot/'
        head = {'Authorization': 'token {}'.format(myToken)}
        response = requests.get(myUrl, headers=head)
        data=response.json()
        context={
            'data': data,
        }
        return JsonResponse(context)
@login_required(login_url='auth-login')
def BillingPlanspppoe(request):
    from rest_framework.authtoken.models import Token
    user = Token.objects.get_or_create(user=request.user)
    for token in user:
        myToken = token
        myUrl = 'https://helios-radius.com/BillingPlans_pppoe/'
        head = {'Authorization': 'token {}'.format(myToken)}
        response = requests.get(myUrl, headers=head)
        data=response.json()
        context={
            'data': data,
        }
        return JsonResponse(context)        



@login_required(login_url='auth-login')
def BillingPlans_All_list(request):
    from rest_framework.authtoken.models import Token
    user = Token.objects.get_or_create(user=request.user)
    for token in user:
        myToken = token
        myUrl = 'https://helios-radius.com/BillingPlans_All/'
        head = {'Authorization': 'token {}'.format(myToken)}
        response = requests.get(myUrl, headers=head)
        data=response.json()
        count = len(data)
        def human_format(num):
            magnitude = 0
            while abs(num) >= 1000:
                magnitude += 1
                num /= 1000.0
            # add more suffixes if you need them
            return '%.2f%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])
        count_all = human_format(count)
        context={
            'data': data,
            'count_all':count_all
        }
        return JsonResponse(context)
@login_required(login_url='auth-login')
def BillingPlans_chart(request):
    from rest_framework.authtoken.models import Token
    user = Token.objects.get_or_create(user=request.user)
    for token in user:
        myToken = token
        myUrl = 'https://helios-radius.com/BillingPlans_All/'
        head = {'Authorization': 'token {}'.format(myToken)}
        response = requests.get(myUrl, headers=head)
        data=response.json()
        count = len(data)
        def human_format(num):
            magnitude = 0
            while abs(num) >= 1000:
                magnitude += 1
                num /= 1000.0
            # add more suffixes if you need them
            return '%.2f%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])
        count_all = human_format(count)
        context={
            'data': data,
            'count_all':count_all
        }
        return JsonResponse(data, safe=False)

      
@api_view(['POST'])
def create_Operators(request):
    serializer=OperatorsSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
    return Response(serializer.data)


@api_view(['POST'])
def create_BillingPlans(request):
    serializer=BillingPlansSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
    return Response(serializer.data)

@api_view(['GET'])
def Nas_All(request):
    Nas_data = Nas.objects.all().using('radius')
    serializer=NasSerializer(Nas_data,many=True)
    return Response(serializer.data)

@api_view(['GET'])
def Radgroupreply_All(request):
    Radgroupreply_data = Radgroupreply.objects.all()
    serializer=RadgroupreplySerializer(Radgroupreply_data,many=True)
    return Response(serializer.data)
@login_required(login_url='auth-login')
def Radgroupreply_list(request):
    from rest_framework.authtoken.models import Token
    user = Token.objects.get_or_create(user=request.user)
    for token in user:
        myToken = token
        myUrl = 'https://helios-radius.com/Radgroupreply/'
        head = {'Authorization': 'token {}'.format(myToken)}
        response = requests.get(myUrl, headers=head)
        data=response.json()
        context={
            'data': data,
        }
        return JsonResponse(context)
       
@api_view(['POST'])
def create_Radgroupreply(request):
    serializer=RadgroupreplySerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
    return Response(serializer.data)


@login_required(login_url='auth-login')
def plans_list(request):
    try:
        if request.method == "POST":
            id = request.POST['id']
            package_name = request.POST['package_name']
            package_type = request.POST['package_type']
            rate_limit = request.POST['rate_limit']
            unit_time = request.POST['unit_time']
            price= request.POST['price']
            if rate_limit:
                from rest_framework.authtoken.models import Token
                user = Token.objects.get_or_create(user=request.user)
                for token in user:
                    myToken = token
                    head = {'Authorization': 'token {}'.format(myToken)}
                    response = requests.post('https://helios-radius.com/create_Radgroupreply/',headers=head, json={
                        "id": f"{request.user}",
                        "attribute": "Mikrotik-Rate-Limit",
                        "groupname": package_name,
                        "op": ":=",
                        "value": rate_limit
                    })

            if package_name:
                from rest_framework.authtoken.models import Token
                user = Token.objects.get_or_create(user=request.user)
                for token in user:
                    myToken = token
                    head = {'Authorization': 'token {}'.format(myToken)}
                    response = requests.post('https://helios-radius.com/create_BillingPlans/',headers=head, json={
                        "planname": package_name,
                        "planid": id,
                        "plantype": package_type,
                        "plantimetype": unit_time,
                        "plantimerefillCost": price,
                        "plantrafficrefillCost": price,
                        "plantraffictotal": rate_limit,
                        "planrecurring": "Yes",
                        "planrecurringbillingschedule": "Fixed",
                        "plancost": price,
                        "plancurrency": ".Ksh",
                        "planactive": "Yes"
                    })
    except Exception:
        print("something happens")
    return render(request,'plans.html')
   
@api_view(['GET'])
def Userbillinfo_all(request):
    id=request.user
    Userbillinfo_data = Userbillinfo.objects.filter(address=f"{id}")
    serializer=UserbillinfoSerializer(Userbillinfo_data,many=True)
    return Response(serializer.data)
    
@api_view(['GET'])
def hotspot_all(request):
    id=request.user
    hotspot_data = Userbillinfo.objects.filter(company=f"{id}",lead="hotspot")
    serializer=UserbillinfoSerializer(hotspot_data,many=True)
    return Response(serializer.data)

@api_view(['POST'])
def create_userbillinfo(request):
    serializer=UserbillinfoSerializer(data=request.data)
    if serializer.is_valid():
        account=serializer.save()
        phone = account.phone
        if request.method == 'POST':
            Payment.objects.filter(notes=phone).delete()
    return Response(serializer.data)

@api_view(['POST'])
def Register_user(request):
    if request.method == "POST":
        serializer=UserSerializer(data=request.data)
        data = {}
        if serializer.is_valid():
            account=serializer.save()
            data['response']='succesfully registered'
            data['email'] = account.email
            data['username'] = account.username
            token=Token.objects.get(user=account).key
            data['token']=token
        else:
            data=serializer.errors
        return Response(data)


@api_view(['GET'])
def ShowAll(request):
    id=request.user
    if f"{request.user}" == "david":
        radcheck_data = Radcheck.objects.filter(attribute='Expiration').using('radius')
        serializer = RadcheckSerializer(radcheck_data, many=True)
        return Response(serializer.data)
    if f"{request.user}" == "admin":
        radcheck_data = Radcheck.objects.filter(attribute='Expiration').using('radius')
        serializer = RadcheckSerializer(radcheck_data, many=True)
        return Response(serializer.data)
    else:
        radcheck_data = Radcheck.objects.filter(attribute='Expiration', id=f"{id}").using('radius')
        serializer=RadcheckSerializer(radcheck_data,many=True)
        return Response(serializer.data)

@api_view(['GET'])
def Payment_list(request):
    payment_data = Payment.objects.all().using('radius')
    serializer=PaymentSerializer(payment_data,many=True)
    return Response(serializer.data)


@api_view(['POST'])
def create_user(request):
    serializer=RadcheckSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
    return Response(serializer.data)


@api_view(['POST'])
def create_Radusergroup(request):
    serializer=RadusergroupSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
    return Response(serializer.data)
@api_view(['GET'])
def Radacct_All(request):
    Radacct_data =Radacct.objects.filter(acctstoptime__isnull=True,calledstationid=request.user.get_short_name(),framedprotocol="PPP")
    serializer= RadacctSerializer(Radacct_data,many=True)
    return Response(serializer.data)
@api_view(['GET'])
def  Radacct_Hotspot(request):
    Radacct_data =Radacct.objects.filter(acctstoptime__isnull=True, nasportid=request.user.get_short_name(),calledstationid='hotspot')
    serializer= RadacctSerializer(Radacct_data,many=True)
    return Response(serializer.data)

@login_required(login_url='auth-login')
def Register(request):
    if request.method=="POST":
        first_name=request.POST['first_name']
        last_name=request.POST['last_name']
        phone_number=request.POST['phone_number']
        email=request.POST['email']
        password=request.POST['password']
        confirm_password=request.POST['confirm_password']
        Registration(first_name=first_name,last_name=last_name,phone_number=phone_number,email=email,password=password,confirm_password=confirm_password).save(using='radius')
        return redirect('auth-login')
    return render(request, 'auth-register.html')
def Login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        try:
            user = Registration.object.get(username=username)
        except:
            user = authenticate(request, username=username, password=password)
            if user is not None:
                login(request, user)
                return redirect('customer')

            else:
                messages.add_message(request, messages.INFO, 'Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive.')
    return render(request, 'auth-login.html')

@login_required(login_url='auth-login')
def customer(request):
    try:
        context={}
        from django.db.models import Avg, Max, Min, Sum
        from datetime import timedelta
        month = datetime.datetime.now().strftime('%m')
        paid_invoice = BillingMerchant.objects.filter(payment_date__month=month,payment_status='Paid',planid=f"{request.user}")
        unpaid_invoice = BillingMerchant.objects.filter(payment_date__month=month,payment_status='Unpaid',planid=f"{request.user}")
        hotspot = Radacct.objects.filter(acctstoptime__isnull=True, nasportid=request.user.get_short_name(),calledstationid='hotspot')
        paid_invoice2 = BillingMerchant.objects.filter(payment_date__month=month,payment_status='Paid',planid=f"{request.user}").aggregate(Sum('payment_total')).get('payment_total__sum')
        unpaid_invoice2 = BillingMerchant.objects.filter(payment_date__month=month,payment_status='Unpaid',planid=f"{request.user}").aggregate(Sum('payment_total')).get('payment_total__sum')
        import timedelta
        day = datetime.datetime.now().strftime('%d')
        new_users = Userbillinfo.objects.filter(lastbill__day =day, address=f"{request.user}")
        upload = Radacct.objects.filter(acctstoptime__isnull=True,calledstationid=request.user.get_short_name()).aggregate(Sum('acctinputoctets')).get('acctinputoctets__sum')
        download = Radacct.objects.filter(acctstoptime__isnull=True,calledstationid=request.user.get_short_name()).aggregate(Sum('acctoutputoctets')).get( 'acctoutputoctets__sum')
        UNITS_MAPPING = [
            (1 << 50, ' PB'),
            (1 << 40, ' TB'),
            (1 << 30, ' GB'),
            (1 << 20, ' MB'),
            (1 << 10, ' KB'),
            (1, (' byte', ' bytes')),
        ]
        def pretty_size(bytes, units=UNITS_MAPPING):
            for factor, suffix in units:
                if bytes >= factor:
                    break
            amo = int(bytes / factor)
            if isinstance(suffix, tuple):
                singular, multiple = suffix
                if amo == 1:
                    suffix = singular
                else:
                    suffix = multiple
            return str(amo) + suffix


        if download is None:
            download_trafic=0
            packets_up = pretty_size(int(download_trafic))
        else:
            packets_up = pretty_size(int(download))
        if download is None:
            upload_trafic=0
            packets_down = pretty_size(int(upload_trafic))
        else:
            packets_down = pretty_size(int(upload))
        if unpaid_invoice is None:
            unpaid_invoice = 0
            unpaid_invoice2 = 0
            context = {
                'unpaid_invoice': unpaid_invoice,
                'unpaid_invoice2':unpaid_invoice2,
            }
        if paid_invoice is None:
            paid_invoice = 0
            paid_invoice2 = 0
            context = {
                'paid_invoice': paid_invoice,
                'paid_invoice2':paid_invoice2,
                
            }
        else:
            context={
                'packets_up':packets_up,
                'packets_down': packets_down,
                'hotspot': len(hotspot),
                'new_users':len(new_users),
                'unpaid_invoice': len(unpaid_invoice),
                'paid_invoice': len(paid_invoice),
                'paid_invoice2':paid_invoice2,
                'unpaid_invoice2':unpaid_invoice2,
                }
    except Exception:
        print("something happens")
    return render(request, 'index.html',context)
@login_required(login_url='auth-login')
def ecommerce(request):
    from datetime import timedelta
    from django.db.models import Avg, Max, Min, Sum
    day = datetime.datetime.now().strftime('%d')
    today = BillingHistory.objects.filter(creationdate__day=day,planid=f"{request.user}").aggregate(Sum('billamount')).get('billamount__sum')
    month = datetime.datetime.now().strftime('%m')
    sum = BillingHistory.objects.filter(creationdate__month=month,planid=f"{request.user}").aggregate(Sum('billamount')).get('billamount__sum')
    last_7days = BillingHistory.objects.filter(creationdate__gte=datetime.datetime.now() - timedelta(days=7),planid=f"{request.user}").aggregate(Sum('billamount')).get('billamount__sum')
    if sum is None:
        sum = 0
        context = {
            'count_all': sum,
            'today': today,
            'last_7days': last_7days,
        }
    if today is None:
        today = 0
        context = {
            'count_all': sum,
            'today': today,
            'last_7days': last_7days,
        }
    if last_7days is None:
        last_7days = 0
        context = {
            'count_all': sum,
            'today': today,
            'last_7days': last_7days,
        }
    else:
        context = {
            'count_all': sum,
            'today': today,
            'last_7days': last_7days,
        }
    return render(request, 'dashboard-ecommerce.html',context)
@login_required(login_url='auth-login')
def list_users(request):
    from rest_framework.authtoken.models import Token
    user =  Token.objects.get_or_create(user=request.user)
    for token in user:
        myToken = token
        myUrl = 'https://helios-radius.com/hotspot_all/'
        head = {'Authorization': 'token {}'.format(myToken)}
        response = requests.get(myUrl, headers=head)
        data=response.json()
        count = len(data)
        def human_format(num):
            magnitude = 0
            while abs(num) >= 1000:
                magnitude += 1
                num /= 1000.0
            # add more suffixes if you need them
            return '%.2f%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])

        count_all=human_format(count)
        context={
            'data': data,
            'count_all': count_all,
        }
        return JsonResponse(context)
#payments_list
def logoutUser(request):
    logout(request)
    return redirect('auth-login')

@login_required(login_url='auth-login')
def payments_list(request):
    from rest_framework.authtoken.models import Token
    user =  Token.objects.get_or_create(user=request.user)
    for token in user:
        myToken = token
        myUrl = 'https://helios-radius.com/payment/'
        head = {'Authorization': 'token {}'.format(myToken)}
        response = requests.get(myUrl, headers=head)
        data=response.json()
        count=len(data)
        count_all="{:,}".format(count)
        context={
            'data': data,
            'count_all': count_all,
        }
        return JsonResponse(context)
@login_required(login_url='auth-login')
@csrf_exempt
def hotspot_list(request):
    try:
        context={}
        if request.method=="POST":
            id = request.POST['id']
            phone= request.POST['phone']
            username= request.POST['username']
            #password  = request.POST['password']
            nextbill= request.POST['nextbill']
            package = request.POST['package']
            amount = request.POST['amount']
            Expiration=''
            if nextbill == "1hr":
                current_date_and_time = datetime.datetime.now()
                hours = 1
                hours_added = datetime.timedelta(hours=hours)
                future_date_and_time = current_date_and_time + hours_added
                Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
            if nextbill == "2hr":
                current_date_and_time = datetime.datetime.now()
                hours = 4
                hours_added = datetime.timedelta(hours=hours)
                future_date_and_time = current_date_and_time + hours_added
                Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
            if nextbill == "3hr":
                current_date_and_time = datetime.datetime.now()
                hours = 3
                hours_added = datetime.timedelta(hours=hours)
                future_date_and_time = current_date_and_time + hours_added
                Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
            if nextbill == "4hr":
                current_date_and_time = datetime.datetime.now()
                hours = 4
                hours_added = datetime.timedelta(hours=hours)
                future_date_and_time = current_date_and_time + hours_added
                Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
            if nextbill == "6hr":
                current_date_and_time = datetime.datetime.now()
                hours = 6
                hours_added = datetime.timedelta(hours=hours)
                future_date_and_time = current_date_and_time + hours_added
                Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
            if nextbill == "12hr":
                current_date_and_time = datetime.datetime.now()
                hours = 12
                hours_added = datetime.timedelta(hours=hours)
                future_date_and_time = current_date_and_time + hours_added
                Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
            if nextbill == "1":
                current_date_and_time = datetime.datetime.now()
                hours = 24
                hours_added = datetime.timedelta(hours=hours)
                future_date_and_time = current_date_and_time + hours_added
                Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
            if nextbill == "2":
                current_date_and_time = datetime.datetime.now()
                hours = 48
                hours_added = datetime.timedelta(hours=hours)
                future_date_and_time = current_date_and_time + hours_added
                Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
            if nextbill == "7":
                current_date_and_time = datetime.datetime.now()
                hours = 192
                hours_added = datetime.timedelta(hours=hours)
                future_date_and_time = current_date_and_time + hours_added
                Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
            if nextbill == "3":
                current_date_and_time = datetime.datetime.now()
                hours = 72
                hours_added = datetime.timedelta(hours=hours)
                future_date_and_time = current_date_and_time + hours_added
                Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
            
            if nextbill == "30":
                current_date_and_time = datetime.datetime.now()
                hours = 720
                hours_added = datetime.timedelta(hours=hours)
                future_date_and_time = current_date_and_time + hours_added
                Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")

            if username:
                from rest_framework.authtoken.models import Token
                user = Token.objects.get_or_create(user=request.user)
                for token in user:
                    myToken = token
                    head = {'Authorization': 'token {}'.format(myToken)}
                    response = requests.post('https://helios-radius.com/user-create/',headers=head, json={
                        "id": id,
                        "username": username,
                        "attribute": "Cleartext-Password",
                        "op": ":=",
                        "value": f"{request.user}"
                    })

            if Expiration:
                from rest_framework.authtoken.models import Token
                user = Token.objects.get_or_create(user=request.user)
                for token in user:
                    myToken = token
                    head = {'Authorization': 'token {}'.format(myToken)}
                    response = requests.post('https://helios-radius.com/user-create/',headers=head,json={
                        "id": id,
                        "username": username,
                        "attribute": "Expiration",
                        "op": ":=",
                        "value": Expiration
                    })

            if package:
                from rest_framework.authtoken.models import Token
                user = Token.objects.get_or_create(user=request.user)
                for token in user:
                    myToken = token
                    head = {'Authorization': 'token {}'.format(myToken)}
                    response = requests.post('https://helios-radius.com/Radusergroup/',headers=head, json={
                        "username": username,
                        "groupname": package,
                        "priority": '1',
                    })
            if phone:
                sender_details=InvoiceStatus.objects.filter(updateby=request.user)
                for sender in sender_details:
                    msg="Your voucher code is "+username+" valid for  "+minutes+ " minutes."
                    r = requests.post("https://smsportal.hostpinnacle.co.ke/SMSApi/send",
                        data={
                        'userid': sender.value,
                        'password': sender.notes,
                        'mobile': phone,
                        'msgType': 'text',
                        'msg':  msg,
                        'senderid': sender.creationby,
                        'duplicatecheck': 'true',
                        'output' : 'json',
                        'sendMethod':'quick',
                        })
            current_date_and_time = datetime.datetime.now()
            date = current_date_and_time.strftime("%Y-%m-%d")
            Userbillinfo(company=id,username=username,planname=package,lead="hotspot",lastbill=date,nextbill=date,billstatus=nextbill+' '+"(.Days)").save()
            BillingHistory(planid=id,username=username,billamount=amount,billaction="Cash Payments",paymentmethod="Mpesa",creationdate=date,billperformer="helios-radius",billreason="Refill Session Time").save()

    except Exception:
        print("something happens")
    return render(request, 'hotspot.html')
@login_required(login_url='auth-login')    
def voucher_code(request):
    import string, random
    letters = string.digits
    username = ''.join(random.choice(letters) for i in range(8))
    context = {
        "username": username
    }
    return JsonResponse(context)
#nas
@login_required(login_url='auth-login')
def nas_list(request):
    from rest_framework.authtoken.models import Token
    user =  Token.objects.get_or_create(user=request.user)
    for token in user:
        myToken = token
        myUrl = 'https://helios-radius.com/nas_all/'
        head = {'Authorization': 'token {}'.format(myToken)}
        response = requests.get(myUrl, headers=head)
        data=response.json()
        count=len(data)
        count_all="{:,}".format(count)
        context={
            'data': data,
            'count_all': count_all,
        }
        return JsonResponse(context)
@login_required(login_url='auth-login')
def nas(request):
    return render(request,'nas.html')

@login_required(login_url='auth-login')
def pppoe(request):
    if request.method=="POST":
        id = request.POST['idw']
        username= request.POST['usernamew']
        password  = request.POST['passwordw']
        first_name=request.POST['first_namew']
        last_name=request.POST['last_namew']
        phone=request.POST['phonew']
        location=request.POST['locationw']
        package = request.POST['displ']
        payment_method = request.POST['payment_methodw']
        current_date_and_time = datetime.datetime.now()
        hours = 744
        hr='31d'
        hours_added = datetime.timedelta(hours=hours)
        future_date_and_time = current_date_and_time + hours_added
        Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")

        if Expiration:
            Radcheck(username=username,attribute="Cleartext-Password",op=":=",value=password).save()
            Radcheck(username=username,attribute="Expiration",op=":=",value=Expiration).save()
        if package:
            Radusergroup(username=username,groupname=package,priority='1').save()

        date = current_date_and_time.strftime("%Y-%m-%d")
        nextbill=future_date_and_time.strftime("%Y-%m-%d")
        Userbillinfo(address=id,username=username,planname=package,contactperson=first_name +' '+ last_name,phone=phone,paymentmethod=payment_method,hotspotlocation=location,lastbill=date,nextbill=nextbill).save()
        if username:
            sender_details=InvoiceStatus.objects.filter(updateby=request.user)
            for sender in sender_details:
                msg="Dear "+first_name+", Your internet plan of "+package+" has been Created successfully."
                r = requests.post("https://smsportal.hostpinnacle.co.ke/SMSApi/send",
                    data={
                    'userid': sender.value,
                    'password': sender.notes,
                    'mobile': phone,
                    'msgType': 'text',
                    'msg':  msg,
                    'senderid': sender.creationby,
                    'duplicatecheck': 'true',
                    'output' : 'json',
                    'sendMethod':'quick',
                    })
                    
    return render(request,'test.html')

@login_required(login_url='auth-login')
def userbillinfo_list(request):
    from rest_framework.authtoken.models import Token
    user =  Token.objects.get_or_create(user=request.user)
    for token in user:
        myToken = token
        myUrl = 'https://helios-radius.com/userbillinfo'
        head = {'Authorization': 'token {}'.format(myToken)}
        response = requests.get(myUrl, headers=head)
        data=response.json()
        count=len(data)
        count_all="{:,}".format(count)
        context={
            'data': data,
            'count_all': count_all,
        }
        return JsonResponse(context)

def pppoe_payments(request):
    current_date_and_time = datetime.datetime.now()
    hours = 744
    hr='31d'
    hours_added = datetime.timedelta(hours=hours)
    future_date_and_time = current_date_and_time + hours_added
    Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
    date = current_date_and_time.strftime("%Y-%m-%d")
    nextbill = future_date_and_time.strftime("%Y-%m-%d")
    users_payments=payments=Payment.objects.all()
    userplans = BillingPlans.objects.filter(planid=request.user)#todo //remember to filter by user.id
    users = Radcheck.objects.filter(attribute='Expiration') # username
    billinfo=Userbillinfo.objects.filter(address=request.user)
    phone=''
    amount=''
    username=''
    planname=''
    userid=''
    #api V@2
    phone_2=''
    amount2=''
    username2=''
    planname2=''
    userid2=''
    user_planname=""
    #safaricom daraja v1
    for all_payments in users_payments:
        for billinformation in billinfo:
            for userbillingplans in userplans:
                phone_number=all_payments.notes
                paid_amount=all_payments.amount
                if request.user.last_name == "APIV2":
                    phone_num = billinformation.phone
                    re=int(str(phone_num)[: 4])
                    re2=int(str(phone_num)[ -3 :])
                    sum_t=f"{re} ***** {re2}"
                    if sum_t == phone_number and userbillingplans.planname == billinformation.planname:
                        for radgroup in users:
                            if radgroup.username == billinformation.username:
                                if int(float(paid_amount)) == int(userbillingplans.plancost):
                                    amount=int(float(paid_amount))
                                    phone=billinformation.phone
                                    username=billinformation.username
                                    planname=billinformation.planname
                                    user_planname=userbillingplans.planname
                                    userid=billinformation.id
                                    userid2=all_payments.id
                else:
                    if phone_number == billinformation.phone and userbillingplans.planname == billinformation.planname:
                        for radgroup in users:
                            if radgroup.username == billinformation.username:
                                if int(float(paid_amount)) == int(userbillingplans.plancost):
                                    amount=int(float(paid_amount))
                                    phone=billinformation.phone
                                    username=billinformation.username
                                    planname=billinformation.planname
                                    user_planname=userbillingplans.planname
                                    userid=billinformation.id
                                    userid2=all_payments.id
                
    print("phone empty", user_planname)
    #API VERSION 2
    if planname:
        Radcheck.objects.filter(attribute='Expiration',username=username).update(value=Expiration)
        Userbillinfo.objects.filter(pk=userid).update(lastbill=date, nextbill=nextbill)
    if username:
        import subprocess
        Radacct_data =Radacct.objects.filter(username=username,acctstoptime__isnull=True,calledstationid=request.user.get_short_name(),framedprotocol="PPP")
        for active in Radacct_data:
            data=Operators.objects.filter(creationby=f"{request.user}")
            for all_ips in data:
                session = active.acctsessionid
                ip_address=f"{all_ips.phone2}"
                subprocess.run(["echo user-name="+username+",Acct-Session-Id="+session+" | radclient -x -r1 "+ip_address+" disconnect nairobi12"], shell=True)

        print("all is a good idea",planname,username, amount ,phone)
    if amount:
        id = request.user
        date = current_date_and_time.strftime("%Y-%m-%d")
        nextbill = future_date_and_time.strftime("%Y-%m-%d")
        from rest_framework.authtoken.models import Token
        user = Token.objects.get_or_create(user=request.user)
        for token in user:
            myToken = token
            head = {'Authorization': 'token {}'.format(myToken)}
            response = requests.post('https://helios-radius.com/BillingHistory/', headers=head, json={
                "username": username,
                "planid": f"{id}",
                "billamount": int(amount),
                "billaction": "Refill Session Time",
                "billperformer": phone,
                "billreason": "Refill Session Time",
                "paymentmethod": "Mpesa",
                "creationdate":date,

            })
    if phone:
        Payment.objects.filter(pk=userid2).delete()
        sender_details=InvoiceStatus.objects.filter(updateby=request.user)
        for sender in sender_details:
            msg="Dear customer, Your internet plan of "+planname+" has been renewed successfully and valid till "+Expiration+"."
            r = requests.post("https://smsportal.hostpinnacle.co.ke/SMSApi/send",
                data={
                'userid': sender.value,
                'password': sender.notes,
                'mobile': phone,
                'msgType': 'text',
                'msg':  msg,
                'senderid': sender.creationby,
                'duplicatecheck': 'true',
                'output' : 'json',
                'sendMethod':'quick',
                })

            print(r.json(), r.reason) 
    else:
        print("all this was a stupid idea")
    return render(request,'test.html')

@api_view(['POST'])
def Make_payment(request):
    serializer=PaymentSerializer(data=request.data)
    if serializer.is_valid():
        account=serializer.save()
    if request.method == 'POST':
        pppoe_payments(request) 
    return Response(serializer.data)

@api_view(['POST'])
def BillingHistory_create(request):
    serializer=BillingHistorySerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
    return Response(serializer.data)

@api_view(['GET'])
def BillingHistory_All(request):
    BillingHistory_data = BillingHistory.objects.filter(planid=f"{request.user}")
    serializer=BillingHistorySerializer(BillingHistory_data,many=True)
    return Response(serializer.data)
@login_required(login_url='auth-login')
def sum_list(request):
    from django.db.models import Avg, Max, Min, Sum
    sum=BillingHistory.objects.filter(planid=f"{request.user}").aggregate(Sum('billamount')).get('billamount__sum')
    if sum:
        count_all="{:,}".format(int(sum))
        context={
            'count_all': "Ksh." + ' ' + count_all ,
        }
    else:
        sum = 0
        count_all = "{:,}".format(int(sum))
        context = {
            'count_all': count_all + ' ' + "Ksh.",
        }
    return JsonResponse(context)
@login_required(login_url='auth-login')   
def today_list(request):
    from django.db.models import Avg, Max, Min, Sum
    import datetime
    today_min = datetime.datetime.combine(datetime.date.today(), datetime.time.min)
    today_max = datetime.datetime.combine(datetime.date.today(), datetime.time.max)
    day = datetime.datetime.now().strftime('%d')
    sum=BillingHistory.objects.filter(creationdate__range=(today_min, today_max),planid=f"{request.user}").aggregate(Sum('billamount')).get('billamount__sum')

    if sum:
        count_all = "{:,}".format(int(sum))
        data = "Ksh." + ' ' +  count_all 
        context={
            'count_all': data,
        }
    else:
        sum = 0
        count_all = "{:,}".format(int(sum))
        data= "Ksh." +' '+count_all
        context = {
            'count_all': data,
        }
    return JsonResponse(context)
@login_required(login_url='auth-login')    
def month_list(request):
    from django.db.models import Avg, Max, Min, Sum
    month = datetime.datetime.now().strftime('%m')
    sum=BillingHistory.objects.filter(creationdate__month=month,planid=f"{request.user}").aggregate(Sum('billamount')).get('billamount__sum')
    count_all=sum
    context={}
    if sum:
        count_all = "{:,}".format(int(sum))
        data ="Ksh." + ' ' + count_all 
        context={
            'count_all': data,
        }
    else:
        sum = 0
        count_all = "{:,}".format(int(sum))
        data="Ksh."+' '+count_all 
        context = {
            'count_all': data,
        }
    return JsonResponse(context)
@login_required(login_url='auth-login')    
def sales_list(request):
    from django.db.models import Avg, Max, Min, Sum
    day = datetime.datetime.now().strftime('%d')
    today = BillingHistory.objects.filter(creationdate__day=day,planid=f"{request.user}").aggregate(Sum('billamount')).get('billamount__sum')
    month = datetime.datetime.now().strftime('%m')
    sum=BillingHistory.objects.filter(creationdate__month=month,planid=f"{request.user}").aggregate(Sum('billamount')).get('billamount__sum')
    count_all=sum
    context={}
    if sum is None:
        sum = 0
        count_all = "{:,}".format(int(sum))
        data = count_all + ' ' + "Ksh."
        context={
            'y': data,
            'x': today,
        }
    else:
        count_all = "{:,}".format(int(sum))
        data=count_all +' '+"Ksh."
        context = {
            'count_all': data,
        }
    return JsonResponse(context)
@login_required(login_url='auth-login')
def commission(request):
    from django.db.models import Avg, Max, Min, Sum
    sum=BillingHistory.objects.filter(planid=f"{request.user}").aggregate(Sum('billamount')).get('billamount__sum')
    context={}
    if sum is None:
        sum = 0
        commission=sum * 20 /100
        count_all="{:,}".format(int(commission))
        context={
            'count_all': count_all + ' ' + "Ksh.",
        }
    else:
        commission = sum * 20 / 100
        count_all = "{:,}".format(int(commission))
        context = {
            'count_all': count_all + ' ' + "Ksh.",
        }
    return JsonResponse(context)
@login_required(login_url='auth-login')
def last_days(request):
    from datetime import timedelta
    from django.db.models import Avg, Max, Min, Sum
    last_7days = BillingHistory.objects.filter(creationdate__gte=datetime.datetime.now() - timedelta(days=7),planid=f"{request.user}").aggregate(Sum('billamount')).get('billamount__sum')
    context={}
    if last_7days is None:
        last_7days =0
        count_all="{:,}".format(int(last_7days))
        context={
            'last_7days':"Ksh." + ' '+ count_all,
        }
    else:
        count_all = "{:,}".format(int(last_7days))
        context = {
            'last_7days':"Ksh." + ' '+ count_all,
        }
    return JsonResponse(context)
@login_required(login_url='auth-login')    
def profit(request):
    from django.db.models import Avg, Max, Min, Sum
    sum=BillingHistory.objects.filter(planid=f"{request.user}").aggregate(Sum('billamount')).get('billamount__sum')
    if sum is None:
        sum=0
        commission=sum * 20 /100
        profit=sum - commission
        count_all="{:,}".format(int(profit))
        context={
            'count_all': count_all + ' ' + "Ksh.",
        }
    else:
        commission = sum * 20 / 100
        profit = sum - commission
        count_all = "{:,}".format(int(profit))
        context = {
            'count_all': count_all + ' ' + "Ksh.",
        }
    return JsonResponse(context)

@login_required(login_url='auth-login')
def json_list(request):
    try:
        from rest_framework.authtoken.models import Token
        user = Token.objects.get_or_create(user=request.user)
        for token in user:
            myToken = token
            myUrl = 'https://helios-radius.com/Radacct'
            head = {'Authorization': 'token {}'.format(myToken)}
            response = requests.get(myUrl, headers=head)
            data = response.json()
            count = len(data)
            count_all = "{:,}".format(count)
            context = {
                'data': data,
                'count_all': count_all,
            }
            return JsonResponse(context)
    except Exception:
        print("something happened")

@login_required(login_url='auth-login')        
def hotspot_active(request):
    from rest_framework.authtoken.models import Token
    user = Token.objects.get_or_create(user=request.user)
    for token in user:
        myToken = token
        myUrl = 'https://helios-radius.com/Radacct_Hotspot/'
        head = {'Authorization': 'token {}'.format(myToken)}
        response = requests.get(myUrl, headers=head)
        data = response.json()
        count = len(data)
        count_all = "{:,}".format(count)
        context = {
            'data': data,
            'count_all': count_all,
        }
        return JsonResponse(context)
@login_required(login_url='auth-login')        
def billing_list(request):
    from rest_framework.authtoken.models import Token
    user = Token.objects.get_or_create(user=request.user)
    for token in user:
        myToken = token
        myUrl = 'https://helios-radius.com/BillingHistory_All'
        head = {'Authorization': 'token {}'.format(myToken)}
        response = requests.get(myUrl, headers=head)
        data = response.json()
        count = len(data)
        count_all = "{:,}".format(count)
        context = {
            'data': data,
            'count_all': count_all,
        }
        return JsonResponse(context)
@login_required(login_url='auth-login')
def online_users(request):
    return render(request,'online_users.html')
@login_required(login_url='auth-login')    
@csrf_exempt
def delete(request):
    username=request.GET.get('id', '')
    Userbillinfo.objects.filter(username=username).delete()
    Radcheck.objects.filter(username=username).delete()
    Radusergroup.objects.filter(username=username).delete()
    return render(request,'test.html')
@login_required(login_url='auth-login')
@csrf_exempt
def delete_billing(request):
    username=request.GET.get('id', '')
    BillingHistory.objects.filter(id=username).delete()
    return render(request,'test.html')
@login_required(login_url='auth-login')    
@csrf_exempt
def delete_package(request):
    username=request.GET.get('id', '')
    BillingPlans.objects.filter(id=username).delete()
    return render(request,'test.html')
@login_required(login_url='auth-login')    
@csrf_exempt
def delete_voucher(request):
    username=request.GET.get('id', '')
    Userbillinfo.objects.filter(username=username).delete()
    Radcheck.objects.filter(username=username).delete()
    Radusergroup.objects.filter(username=username).delete()
    Radreply.objects.filter(username=username).delete()
    return render(request,'test.html')
@login_required(login_url='auth-login')    
def billing_history(request):
    return render(request,'billing.html')
@login_required(login_url='auth-login')
def active_records(request):
    import datetime
    from django.db.models import Sum
    upload = Radacct.objects.filter(acctstoptime__isnull=True).aggregate(Sum('acctinputoctets')).get('acctinputoctets__sum')
    return render(request,'delete.html')
@login_required(login_url='auth-login')
def InvoiceItems_data(request):
    from rest_framework.authtoken.models import Token
    user =  Token.objects.get_or_create(user=request.user)
    for token in user:
        myToken = token
        myUrl = 'https://helios-radius.com/InvoiceItem/'
        head = {'Authorization': 'token {}'.format(myToken)}
        response = requests.get(myUrl, headers=head)
        data=response.json()
        count=len(data)
        count_all="{:,}".format(count)
        context={
            'data': data,
            'count_all': count_all,
        }
        return JsonResponse(context)

@login_required(login_url='auth-login')
def invoice(request):
    return render(request,'page-invoices.html')
@login_required(login_url='auth-login')
@csrf_exempt
def update_pppoe_user(request):
    if request.method == "POST":
        myinput2= request.POST['myinput2']
        username = request.POST['username']
        password = request.POST['password']
        contactperson = request.POST['contact']
        phone = request.POST['phone']
        location = request.POST['location']
        package = request.POST['myinput']
        nextbill = request.POST['nextbill']
        Expiration=''
        hours = ''
        user_id=''
        new_package=''
        user_update=Userbillinfo.objects.filter(username=username)
        for all_s in user_update:
            user_id=all_s.id
            if package:
                new_package=package
            else:
                new_package=myinput2
        if nextbill == "Now":
            current_date_and_time = datetime.datetime.now()
            hours = 00
            hours_added = datetime.timedelta(seconds=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "Tommorrow":
            current_date_and_time = datetime.datetime.now()
            hours = 24
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "2":
            current_date_and_time = datetime.datetime.now()
            hours = 48
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "3":
            current_date_and_time = datetime.datetime.now()
            hours = 72
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "4":
            current_date_and_time = datetime.datetime.now()
            hours = 96
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "5":
            current_date_and_time = datetime.datetime.now()
            hours = 120
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "6":
            current_date_and_time = datetime.datetime.now()
            hours = 144
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "7":
            current_date_and_time = datetime.datetime.now()
            hours = 168
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "8":
            current_date_and_time = datetime.datetime.now()
            hours = 192
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "9":
            current_date_and_time = datetime.datetime.now()
            hours = 216
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "10":
            current_date_and_time = datetime.datetime.now()
            hours = 240
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "11":
            current_date_and_time = datetime.datetime.now()
            hours = 264
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "12":
            current_date_and_time = datetime.datetime.now()
            hours = 288
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")

        if nextbill == "13":
            current_date_and_time = datetime.datetime.now()
            hours = 312
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "14":
            current_date_and_time = datetime.datetime.now()
            hours = 336
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")

        if nextbill == "15":
            current_date_and_time = datetime.datetime.now()
            hours = 360
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")

        if nextbill == "16":
            current_date_and_time = datetime.datetime.now()
            hours = 384
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "17":
            current_date_and_time = datetime.datetime.now()
            hours = 408
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "18":
            current_date_and_time = datetime.datetime.now()
            hours = 432
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "19":
            current_date_and_time = datetime.datetime.now()
            hours = 456
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")

        if nextbill == "20":
            current_date_and_time = datetime.datetime.now()
            hours = 480
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "21":
            current_date_and_time = datetime.datetime.now()
            hours = 504
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "22":
            current_date_and_time = datetime.datetime.now()
            hours = 528
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %B %Y %H:%M:%S")
        if nextbill == "22":
            current_date_and_time = datetime.datetime.now()
            hours = 552
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "23":
            current_date_and_time = datetime.datetime.now()
            hours = 576
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "24":
            current_date_and_time = datetime.datetime.now()
            hours = 600
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "25":
            current_date_and_time = datetime.datetime.now()
            hours = 624
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "26":
            current_date_and_time = datetime.datetime.now()
            hours = 648
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "27":
            current_date_and_time = datetime.datetime.now()
            hours = 672
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "28":
            current_date_and_time = datetime.datetime.now()
            hours = 480
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "29":
            current_date_and_time = datetime.datetime.now()
            hours = 696
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "30":
            current_date_and_time = datetime.datetime.now()
            hours = 720
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "31":
            current_date_and_time = datetime.datetime.now()
            hours = 744
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")

        rad_ids=""
        rad_userid=Radcheck.objects.filter(username=username,attribute="Cleartext-Password")
        for all_ids in rad_userid:
            rad_ids=all_ids.id
        radds=""
        radserid=Radcheck.objects.filter(username=username,attribute="Expiration")
        for all_is in radserid:
            radds=all_is.id   
        if username:
            Radcheck.objects.filter(pk=rad_ids,attribute="Cleartext-Password").update(username=username,value=password)
        if Expiration:
            Radcheck.objects.filter(pk=radds,attribute="Expiration").update(value=Expiration)
        if package:
            Radusergroup.objects.filter(username=username).delete()
            Radusergroup(username=username, groupname=new_package,priority="1").save()
        if contactperson:
            if nextbill == "Select":
                Userbillinfo.objects.filter(pk=user_id).update(username=username, planname=new_package,contactperson=contactperson, phone=phone,hotspotlocation=location)
            else:
                current_date_and_time = datetime.datetime.now()
                hours_added = datetime.timedelta(hours=hours)
                future_date_and_time = current_date_and_time + hours_added
                nextbill = future_date_and_time.strftime("%Y-%m-%d")
                Userbillinfo.objects.filter(pk=user_id).update(username=username, planname=new_package,contactperson=contactperson,phone=phone,hotspotlocation=location,nextbill=nextbill)
        if username:
            import subprocess
            Radacct_data =Radacct.objects.filter(username=username,acctstoptime__isnull=True,calledstationid=request.user.get_short_name(),framedprotocol="PPP")
            for active in Radacct_data:
                data=Operators.objects.filter(creationby=f"{request.user}")
                for all_ips in data:
                    session = active.acctsessionid
                    ip_address=f"{all_ips.phone2}"
                    subprocess.run(["echo user-name="+username+",Acct-Session-Id="+session+" | radclient -x -r1 "+ip_address+" disconnect nairobi12"], shell=True)
    return render(request,'test.html')

@login_required(login_url='auth-login')
@csrf_exempt
def update_pppoe(request):
    if request.method == "POST":
        user_id= request.POST['id']
        username = request.POST['username']
        password = request.POST['password']
        contactperson = request.POST['contact']
        phone = request.POST['phone']
        location = request.POST['location']
        package = request.POST['myinput']
        nextbill = request.POST['nextbill']
        Expiration=''
        hours = ''
        if nextbill == "Now":
            current_date_and_time = datetime.datetime.now()
            hours = 00
            hours_added = datetime.timedelta(seconds=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "Tommorrow":
            current_date_and_time = datetime.datetime.now()
            hours = 24
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "2":
            current_date_and_time = datetime.datetime.now()
            hours = 48
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "3":
            current_date_and_time = datetime.datetime.now()
            hours = 72
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "4":
            current_date_and_time = datetime.datetime.now()
            hours = 96
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "5":
            current_date_and_time = datetime.datetime.now()
            hours = 120
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "6":
            current_date_and_time = datetime.datetime.now()
            hours = 144
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "7":
            current_date_and_time = datetime.datetime.now()
            hours = 168
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "8":
            current_date_and_time = datetime.datetime.now()
            hours = 192
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "9":
            current_date_and_time = datetime.datetime.now()
            hours = 216
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "10":
            current_date_and_time = datetime.datetime.now()
            hours = 240
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "11":
            current_date_and_time = datetime.datetime.now()
            hours = 264
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "12":
            current_date_and_time = datetime.datetime.now()
            hours = 288
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")

        if nextbill == "13":
            current_date_and_time = datetime.datetime.now()
            hours = 312
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "14":
            current_date_and_time = datetime.datetime.now()
            hours = 336
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")

        if nextbill == "15":
            current_date_and_time = datetime.datetime.now()
            hours = 360
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")

        if nextbill == "16":
            current_date_and_time = datetime.datetime.now()
            hours = 384
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "17":
            current_date_and_time = datetime.datetime.now()
            hours = 408
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "18":
            current_date_and_time = datetime.datetime.now()
            hours = 432
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "19":
            current_date_and_time = datetime.datetime.now()
            hours = 456
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")

        if nextbill == "20":
            current_date_and_time = datetime.datetime.now()
            hours = 480
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "21":
            current_date_and_time = datetime.datetime.now()
            hours = 504
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "22":
            current_date_and_time = datetime.datetime.now()
            hours = 528
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %B %Y %H:%M:%S")
        if nextbill == "22":
            current_date_and_time = datetime.datetime.now()
            hours = 552
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "23":
            current_date_and_time = datetime.datetime.now()
            hours = 576
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "24":
            current_date_and_time = datetime.datetime.now()
            hours = 600
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "25":
            current_date_and_time = datetime.datetime.now()
            hours = 624
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "26":
            current_date_and_time = datetime.datetime.now()
            hours = 648
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "27":
            current_date_and_time = datetime.datetime.now()
            hours = 672
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "28":
            current_date_and_time = datetime.datetime.now()
            hours = 480
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "29":
            current_date_and_time = datetime.datetime.now()
            hours = 696
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "30":
            current_date_and_time = datetime.datetime.now()
            hours = 720
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "31":
            current_date_and_time = datetime.datetime.now()
            hours = 744
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")

        if username:
            Radcheck.objects.filter(username=username).update(username=username)

        if Expiration:
            Radcheck.objects.filter(username=username,attribute="Expiration").update(value=Expiration)

        if package:
            Radusergroup.objects.filter(username=username).update(username=username, groupname=package)
        if contactperson:
            if nextbill == "Select":
                Userbillinfo.objects.filter(pk=user_id).update(username=username, planname=package,contactperson=contactperson, phone=phone,hotspotlocation=location)
            else:
                current_date_and_time = datetime.datetime.now()
                hours_added = datetime.timedelta(hours=hours)
                future_date_and_time = current_date_and_time + hours_added
                nextbill = future_date_and_time.strftime("%Y-%m-%d")
                Userbillinfo.objects.filter(pk=user_id).update(username=username, planname=package,contactperson=contactperson,phone=phone,hotspotlocation=location,nextbill=nextbill)
        if username:
            import subprocess
            Radacct_data =Radacct.objects.filter(username=username,acctstoptime__isnull=True,calledstationid=request.user.get_short_name(),framedprotocol="PPP")
            for active in Radacct_data:
                data=Operators.objects.filter(creationby=f"{request.user}")
                for all_ips in data:
                    session = active.acctsessionid
                    ip_address=f"{all_ips.phone2}"
                    subprocess.run(["echo user-name="+username+",Acct-Session-Id="+session+" | radclient -x -r1 "+ip_address+" disconnect nairobi12"], shell=True)
    return render(request,'test.html')
@login_required(login_url='auth-login')    
def wifi_online(request):
    return render(request,'wifi_online.html')
@login_required(login_url='auth-login')
@csrf_exempt
def create_invoice(request):
    if request.method == "POST":
        username = request.POST['status']
        status = request.POST['status']
        type = request.POST['type']
        plans = request.POST['plans']
        amount = request.POST['amount']
        customer = request.POST['customer']
        notes = request.POST['notes']
        taxamount = request.POST['taxamount']
        date = datetime.datetime.now()

        BillingMerchant(planid=f"{request.user}",username=username,planname=plans,quantity='0',payment_tax=taxamount, payment_cost=amount,payment_total=amount,first_name=customer,payment_date=date,payment_status=status,pending_reason='none').save()

    return render(request,'delete.html')
@login_required(login_url='auth-login')
def payments_pay(request):
    date = datetime.datetime.now()
    Payment(invoice_id='33', amount='344', type_id="3344",notes="0708562799", creationby='hh',date=date).save()
    return render(request,'payments.html')
@login_required(login_url='auth-login')
def deduct(request):
    
    return render(request,'invoice-pdf.html')


def render_to_pdf(template_src, context_dict={}):
    template = get_template(template_src)
    html = template.render(context_dict)
    result = BytesIO()
    pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), content_type='application/pdf')
    return None


data = {
    "company": "Dennnis Ivanov Company",
    "address": "123 Street name",
    "city": "Vancouver",
    "state": "WA",
    "zipcode": "98663",
    "phone": "555-555-2345",
    "email": "youremail@dennisivy.com",
    "website": "dennisivy.com",
}


# Opens up page as PDF
class ViewPDF(View):
    def get(self, request, *args, **kwargs):
        pdf = render_to_pdf('invoice-pdf.html', data)
        return HttpResponse(pdf, content_type='application/pdf')


# Automaticly downloads to PDF file
class DownloadPDF(View):
    def get(self, request, *args, **kwargs):
        pdf = render_to_pdf('invoice-pdf.html', data)

        response = HttpResponse(pdf, content_type='application/pdf')
        filename = "Invoice_%s.pdf" % ("12341231")
        content = "attachment; filename=%s" % (filename)
        response['Content-Disposition'] = content
        return response

@login_required(login_url='auth-login')
def index(request):
    context = {}
    return render(request, 'invoice-pdf.html', context)

@login_required(login_url='auth-login')
@csrf_exempt
def sessiontimeout(request):
    if request.method == "POST":
        username = request.POST['user']
        user_data=Radcheck.objects.filter(username=username, attribute='Expiration')
        for i in user_data:
            import datetime
            date_format = "%d %B %Y %H:%M:%S"
            next = datetime.datetime.strptime(i.value, date_format)
            now = datetime.datetime.now()
            current = now.strftime("%d %B %Y %H:%M:%S")
            delta = next - now
            ans=delta.days * 24 * 60 * 60
            if Radreply.objects.filter(username=username).exists():
                Radreply.objects.filter(username=username).update(username=username,attribute="Session-Timeout",op=":=",value=ans)
            else:
                Radreply(username=username,attribute="Session-Timeout",op=":=",value=ans).save()
            return redirect('pppoe_list')
    return render(request, 'test.html')
@login_required(login_url='auth-login')
def chart(request):
    co2 = BillingHistory.objects.filter(planid=f"{request.user}")
    fig = px.line(x=[c.billamount for c in co2], y=[c.creationdate  for c in co2],color=[c.billamount for c in co2],
        title="User Data Analytics",
        labels={'x': 'Amount', 'y': 'Date'}
    )
    fig.update_layout(
        title={
            'font_size': 24,
            'xanchor': 'center',
            'x': 0.5
    })
    chart = fig.to_html()
    context = {'chart': chart}
    return render(request, 'table.html', context)
@login_required(login_url='auth-login')    
def users(request):
    return render(request,'page-profile.html')
@login_required(login_url='auth-login')    
def sales_analytics(request):
    return render(request,'index4.html')
@login_required(login_url='auth-login')
def customer_info(request):
    try:
        data={}
        from django.db.models import Sum
        username=request.GET.get('user', '')
        Userbillinfo_data = Userbillinfo.objects.filter(address=request.user,username=username)
        Radcheck_User = Radcheck.objects.filter(attribute="Expiration",username=username)
        password = Radcheck.objects.filter(attribute="Cleartext-Password",username=username)
        upload = Radacct.objects.filter(username=username,acctstoptime__isnull=True,calledstationid=request.user.get_short_name()).aggregate(Sum('acctinputoctets')).get('acctinputoctets__sum')
        download = Radacct.objects.filter(username=username,acctstoptime__isnull=True,calledstationid=request.user.get_short_name()).aggregate(Sum('acctoutputoctets')).get( 'acctoutputoctets__sum')
        conn_details = Radacct.objects.filter(username=username,acctstoptime__isnull=True,calledstationid=request.user.get_short_name())
        BillingHistory_data = BillingHistory.objects.filter(username=username,planid=f"{request.user}")
        UNITS_MAPPING = [
            (1 << 50, ' PB'),
            (1 << 40, ' TB'),
            (1 << 30, ' GB'),
            (1 << 20, ' MB'),
            (1 << 10, ' KB'),
            (1, (' byte', ' bytes')),
        ]
        def pretty_size(bytes, units=UNITS_MAPPING):
            for factor, suffix in units:
                if bytes >= factor:
                    break
            amo = int(bytes / factor)
            if isinstance(suffix, tuple):
                singular, multiple = suffix
                if amo == 1:
                    suffix = singular
                else:
                    suffix = multiple
            return str(amo) + suffix


        if download is None:
            download_trafic=0
            packets_up = pretty_size(int(download_trafic))
        else:
            packets_up = pretty_size(int(download))
        if download is None:
            upload_trafic=0
            packets_down = pretty_size(int(upload_trafic))
        else:
            packets_down = pretty_size(int(upload))
        
        if conn_details:
         for user_conn in conn_details:
            for all in Radcheck_User:
                for users_info in Userbillinfo_data:
                    for passwords in password:
                        import datetime
                        sec = user_conn.acctsessiontime
                        convert = str(datetime.timedelta(seconds = sec))
                        data={
                            'nasportid':user_conn.nasportid,
                            'framedipaddress':user_conn.framedipaddress,
                            'nasipaddress':user_conn.nasipaddress,
                            'callingstationid':user_conn.callingstationid,
                            'packets_up':packets_up,
                            'packets_down': packets_down,
                            'uptime':convert,
                            'BillingHistory_data':BillingHistory_data,
                            'contactperson':users_info.contactperson,
                            'username':username,
                            'paymentmethod':users_info.paymentmethod,
                            'location':users_info.hotspotlocation,
                            'id':users_info.cash,
                            'phone2':users_info.phone,
                            'planname':users_info.planname,
                            'passwords':passwords.value,
                            'due':all.value,
                        }
        else:
            for all in Radcheck_User:
                for users_info in Userbillinfo_data:
			                    for passwords in password:
                        data={
                        'BillingHistory_data':BillingHistory_data,
                        'contactperson':users_info.contactperson,
                        'username':username,
                        'paymentmethod':users_info.paymentmethod,
                        'location':users_info.hotspotlocation,
                        'id':users_info.id,
                        'phone2':users_info.phone,
                        'planname':users_info.planname,
                        'due':all.value,
                        'passwords':passwords.value,
                        }
    except Exception:
        print("something happens")
    return render(request,'customer_details.html',data)
@login_required(login_url='auth-login')    
@csrf_exempt
def operaters_user(request):
    try:
        op=Operators.objects.filter(creationby=f"{request.user}")
        if op:
            print("data")
        else:
            if request.method == "POST":
                    firstname = request.POST['firstname']
                    lastname = request.POST['lastname']
                    department= request.POST['department']
                    company= request.POST['company']
                    phone1= request.POST['phone']
                    email= request.POST['email']
                    ip= request.POST['ip']
                    current_date_and_time = datetime.datetime.now()
                    date = current_date_and_time.strftime("%Y-%m-%d")
                    Operators(firstname=firstname,email1=email,phone2=ip,password="password",lastname=lastname,department=department,creationby= f"{request.user}",company= company,phone1= phone1,creationdate= date,updatedate=date,lastlogin=date).save()
                    return redirect('user_profile')
        context={}
        for Operator in op:
            if request.method == "POST":
                firstname = request.POST['firstname']
                lastname = request.POST['lastname']
                department= request.POST['department']
                company= request.POST['company']
                phone1= request.POST['phone']
                email= request.POST['email']
                ip= request.POST['ip']
                current_date_and_time = datetime.datetime.now()
                date = current_date_and_time.strftime("%Y-%m-%d")
                if Operators.objects.filter(firstname=Operator.firstname).exists():
                    Operators.objects.filter(firstname=Operator.firstname).update(firstname=firstname,email1=email,phone2=ip,password="password",lastname=lastname,department=department,creationby= f"{request.user}",company= company,phone1= phone1,creationdate= date,updatedate=date,lastlogin=date)
                
            firstname =Operator.firstname + ' '+ Operator.lastname
            email =Operator.email1
            company= Operator.company
            department= Operator.department
            phone=Operator.phone1
            address= Operator.phone2
            return firstname,email,company,department,phone,address

    except Exception:
        print("something happened")
        
@login_required(login_url='auth-login')    
@csrf_exempt
def update_plan(request):
    if request.method == "POST":
        user_id= request.POST['user_id']
        planname = request.POST['planname']
        new_planname = request.POST['new_planname']
        plantype = request.POST['plantype']
        plantimetype = request.POST['plantraffictotal']
        planrecurring = request.POST['planrecurring']
        plancost = request.POST['plancost']
        plantraffictotal = request.POST['plantraffictotal']
        plantimetype = request.POST['plantimetype']
        Radgroup=Radgroupreply.objects.filter(groupname=planname)
        rad=""
        for Radgroups in Radgroup:
            rad=Radgroups.id
        if planname:
            Radgroupreply.objects.filter(pk=rad).update(groupname=new_planname,attribute="Mikrotik-Rate-Limit",op=":=",value=plantraffictotal)    
        BillingPlans.objects.filter(pk=user_id).update(planname=new_planname,plantype=plantype,plantimetype=plantimetype,planrecurring=planrecurring,plancost=plancost,plantraffictotal=plantraffictotal)
    return render(request,'test.html')
@login_required(login_url='auth-login')
def edit_user(request):
    try:
        context={}
        op=Operators.objects.filter(creationby=f"{request.user}")
        if op:
            print("data")
        else:
            if request.method == "POST":
                    firstname = request.POST['firstname']
                    lastname = request.POST['lastname']
                    department= request.POST['department']
                    company= request.POST['company']
                    phone1= request.POST['phone']
                    email= request.POST['email']
                    ip= request.POST['ip']
                    current_date_and_time = datetime.datetime.now()
                    date = current_date_and_time.strftime("%Y-%m-%d")
                    Operators(firstname=firstname,email1=email,phone2=ip,password="password",lastname=lastname,department=department,creationby= f"{request.user}",company= company,phone1= phone1,creationdate= date,updatedate=date,lastlogin=date).save()
        for Operator in op:
            if request.method == "POST":
                firstname = request.POST['firstname']
                lastname = request.POST['lastname']
                department= request.POST['department']
                company= request.POST['company']
                phone1= request.POST['phone']
                email= request.POST['email']
                ip= request.POST['ip']
                current_date_and_time = datetime.datetime.now()
                date = current_date_and_time.strftime("%Y-%m-%d")
                if Operators.objects.filter(firstname=Operator.firstname).exists():
                    Operators.objects.filter(firstname=Operator.firstname).update(firstname=firstname,email1=email,phone2=ip,password="password",lastname=lastname,department=department,creationby= f"{request.user}",company= company,phone1= phone1,creationdate= date,updatedate=date,lastlogin=date)
        for Operator in op:
            context={
                "firstname": Operator.firstname + ' '+Operator.lastname,
                "firstname2":Operator.firstname,
                "lastname": Operator.lastname,
                "email": Operator.email1,
                "company": Operator.company,
                "department": Operator.department,
                "phone": Operator.phone1,
                "address": Operator.phone2,

                }
    except Exception:
        print("something happens")
    return render(request,'page-empty.html',context)

def search_user(request):
    username=request.GET.get('address')
    results=[]
    if username:
        users=Userbillinfo.objects.filter(address=request.user,username__icontains=username)
        for user in users:
            results.append(user.username)
    return JsonResponse({'status':200,'data':results})

@login_required(login_url='auth-login')
def last_month(request):
    try:
        from datetime import timedelta
        from django.db.models import Avg, Max, Min, Sum
        lastmonth = BillingHistory.objects.filter(creationdate__gte=datetime.datetime.now() - timedelta(days=30),planid=f"{request.user}").aggregate(Sum('billamount')).get('billamount__sum')
        def human_format(num):
                magnitude = 0
                while abs(num) >= 1000:
                    magnitude += 1
                    num /= 1000
                # add more suffixes if you need them
                return '%.1f%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])
           

        context={}
        if lastmonth is None:
            lastmonth =0
            count_all='Ksh. '+ "{:,}".format(int(lastmonth))
            context={
                'lastmonth':'Ksh. '+ "{:,}".format(int(lastmonth)),
            }
        else:
            count_all ='Ksh. '+ "{:,}".format(int(lastmonth))
            context = {
                'lastmonth':'Ksh. '+"{:,}".format(int(lastmonth)),
            }
        return JsonResponse(context)
    except Exception:
        print("something happened")

@login_required(login_url='auth-login')
def draft_all(request):
    from rest_framework.authtoken.models import Token
    user = Token.objects.get_or_create(user=request.user)
    for token in user:
        myToken = token
        myUrl = 'https://helios-radius.com/draft_list/'
        head = {'Authorization': 'token {}'.format(myToken)}
        response = requests.get(myUrl, headers=head)
        data=response.json()
        context={
            'data': data,
        }
        return JsonResponse(context)
@login_required(login_url='auth-login')        
def draft(request):
    if request.method == "POST":
        title = request.POST['title']
        message= request.POST['msg']
        user_id= request.user
        if message:
            InvoiceType(value=title,notes=message,creationby=user_id,updateby=user_id).save()
    return render(request, 'test.html')
@login_required(login_url='auth-login')
def bulksms(request):
    try:
        context={}
        sender_details=InvoiceStatus.objects.filter(updateby=request.user)
        if sender_details:
            print("")
        else:
            if request.method == "POST":
                username = request.POST['username']
                password = request.POST['password']
                senderid = request.POST['senderid']
                user_id= request.user
                InvoiceStatus(value=username,notes=password,creationby=senderid,updateby=user_id).save()
        for sender in sender_details:
            if request.method == "POST":
                username = request.POST['username']
                password = request.POST['password']
                senderid = request.POST['senderid']
                user_id= request.user
                if InvoiceStatus.objects.filter(value=sender.value).exists():
                    InvoiceStatus.objects.filter(pk=sender.id).update(value=username,notes=password,creationby=senderid)
            context={
            'username':sender.value,
            'password':sender.notes,
            'senderid':sender.creationby,
            }
    except Exception:
        print("something happens")
    return render(request,'app-email.html',context)
    
@login_required(login_url='auth-login')
def send_sms(request):
    if request.method == "POST":
        phone = request.POST['phone']
        msg = request.POST['message']
        myselect = request.POST['myinput']
        user_id= request.user
    draft=InvoiceType.objects.filter(updateby=request.user)
    sms=""
    for drafts in draft:
        if myselect == drafts.value:
            sender_details=InvoiceStatus.objects.filter(updateby=request.user)
            for sender in sender_details:
                r = requests.post("https://smsportal.hostpinnacle.co.ke/SMSApi/send",
                data={
                'userid': sender.value,
                'password': sender.notes,
                'mobile': phone,
                'msgType': 'text',
                'msg': drafts.notes,
                'senderid': sender.creationby,
                'duplicatecheck': 'true',
                'output' : 'json',
                'sendMethod':'quick',
                })
        else:
            sender_details=InvoiceStatus.objects.filter(updateby=request.user)
            for sender in sender_details:
                r = requests.post("https://smsportal.hostpinnacle.co.ke/SMSApi/send",
                data={
                'userid': sender.value,
                'password': sender.notes,
                'mobile': phone,
                'msgType': 'text',
                'msg': msg,
                'senderid': sender.creationby,
                'duplicatecheck': 'true',
                'output' : 'json',
                'sendMethod':'quick',
                })
    return render(request,'test.html')
@login_required(login_url='auth-login')
@csrf_exempt    
def changeusername(request):
    if request.method == "POST":
        user_id= request.POST['user_name']
        username = request.POST['id']
        new_package=""
        planid=""
        Userbill=Userbillinfo.objects.filter(address=f"{request.user}",username=username)
        for userinfo in Userbill:
            new_package=userinfo.planname
            planid=userinfo.id
        rad_ids=""
        rad_userid=Radcheck.objects.filter(username=username,attribute="Cleartext-Password")
        for all_ids in rad_userid:
            rad_ids=all_ids.id
        radds=""
        radserid=Radcheck.objects.filter(username=username,attribute="Expiration")
        for all_is in radserid:
            radds=all_is.id   
        if username:
            Radcheck.objects.filter(pk=rad_ids,attribute="Cleartext-Password").update(username=user_id)
            Radcheck.objects.filter(pk=radds,attribute="Expiration").update(username=user_id)
        if new_package:
            Radusergroup.objects.filter(username=user_id).delete()
            Radusergroup(username=user_id,groupname=new_package,priority='1').save()
            
            Userbillinfo.objects.filter(pk=planid,address=f"{request.user}").update(username=user_id)
        print(new_package)
        return redirect('https://helios-radius.com/user_info/?user='+user_id+'')
    return render(request,'test.html')
@csrf_exempt
def login_userportal(request):
    if request.method=='POST':
        username= request.POST.get('username')
        password = request.POST.get('password')
        try:
            user = AuthUser.empAuth_object.get(username=username,password=password)
        except:
            messages.add_message(request, messages.INFO, 'username or password does not exist.')

            user = authenticate(request,username=username,password=password)
            if user is not None:
                login(request, user)
                return redirect('client-portal')

            else:
                messages.add_message(request, messages.INFO,'')
    return render(request, 'login.html')    

@login_required(login_url='user-portal')
def client_portal(request):
    return render(request,'userportal.html')
@login_required(login_url='auth-login')
@csrf_exempt
def update_voucher(request):
    if request.method == "POST":
        nextbill= request.POST['refill']
        username = request.POST['username']
        Expiration=''
        hours = ''
        if nextbill == "1hr":
            current_date_and_time = datetime.datetime.now()
            hours = 1
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "2hr":
            current_date_and_time = datetime.datetime.now()
            hours = 4
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "3hr":
            current_date_and_time = datetime.datetime.now()
            hours = 3
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "4hr":
            current_date_and_time = datetime.datetime.now()
            hours = 4
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "6hr":
            current_date_and_time = datetime.datetime.now()
            hours = 6
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "12hr":
            current_date_and_time = datetime.datetime.now()
            hours = 12
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "1":
            current_date_and_time = datetime.datetime.now()
            hours = 24
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "2":
            current_date_and_time = datetime.datetime.now()
            hours = 48
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "8":
            current_date_and_time = datetime.datetime.now()
            hours = 192
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        if nextbill == "3":
            current_date_and_time = datetime.datetime.now()
            hours = 72
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        
        if nextbill == "30":
            current_date_and_time = datetime.datetime.now()
            hours = 720
            hours_added = datetime.timedelta(hours=hours)
            future_date_and_time = current_date_and_time + hours_added
            Expiration = future_date_and_time.strftime("%d %b %Y %H:%M:%S")
        
        if Expiration:
            current_date_and_time = datetime.datetime.now()
            date = current_date_and_time.strftime("%Y-%m-%d")
            nextbill = current_date_and_time.strftime("%Y-%m-%d") 
            Radcheck.objects.filter(username=username,attribute="Expiration").update(value=Expiration)
            test=Radcheck.objects.filter(username=username,attribute="Access-Period")
            userids=''
            for tests in test:
                userids=tests.id
            if userids:
                Radcheck.objects.filter(pk=userids).update(attribute="Expiration",value=Expiration)
            Userbillinfo.objects.filter(username=username).update(lastbill=date, nextbill=Expiration)
            from rest_framework.authtoken.models import Token
            user = Token.objects.get_or_create(user=request.user)
            for token in user:
                myToken = token
                head = {'Authorization': 'token {}'.format(myToken)}
                response = requests.post('https://helios-radius.com/BillingHistory/',headers=head,json={
                    "username": username,
                     "planid" :f"{request.user}",
                     "billamount" :amount,
                     "billaction" :"Refill Session Time",
                     "billperformer" : "Helios Radius",
                     "billreason" : "Refill Session Time",
                     "paymentmethod" : "Mpesa",
                     "creationdate" : date,
                }) 

    return render(request,'test.html')

def delete_all(request):
    Userbillinfo.objects.filter(company='28351281',lead="hotspot",).delete()
    return render(request,'test.html')
