from django.db import models
from django.db.models import F
from django.contrib.auth.models import AbstractUser, UserManager
from django.conf import settings
from django.contrib.auth import get_user_model
import time
from django.utils import timezone
import requests
from .atuns import zone
from datetime import datetime
from django.urls import reverse
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
import uuid
from django.core.validators import MaxValueValidator, MinValueValidator
from django.utils.text import slugify
from django.db.models import Sum
from django.db import transaction
from django.utils import dateparse
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from django.utils.html import strip_tags
import json
import openpyxl
import uuid
from django.utils import timezone
from base64 import b64encode
from .atuns import zone

from django.dispatch import receiver
from django.db.models.signals import post_save
from . firebase_utils import send_notification_to_all_customers_firebase, send_firebase_notification


#  n = Note.objects.all()
#  n = Note.objects.all().order_by('-id')
#  n = Note.objects.get(pk=note_id)
# n = Note.objects.filter(title='test')
# n.save()
# n.delete()
# request.POST.get('title')
# {% csrf_token %}

# ============================================================
# MAILER
# ============================================================



site_name = "Exactsub.com"

SITE_URL = "https://exactsub.com"

LOGO_URL = (
    "https://exactsub.com/"
    "static/images/atuns.png"
)


def mailer(
    email,
    subject,
    message,
    user_name="",
    button_text="",
    button_url="",
    preheader=""
):
    """
    Send a branded ExactSub HTML email.

    Existing calls remain compatible because the additional
    arguments are optional.

    Parameters
    ----------
    email:
        Recipient email address.

    subject:
        Email subject and main heading.

    message:
        Trusted HTML email body.

    user_name:
        Customer display name.

    button_text:
        Optional CTA button text.

    button_url:
        Optional CTA button URL.

    preheader:
        Optional preview text shown by supported email clients.
    """

    html_template = get_template("email.html")

    context = {
        "subject": subject,
        "message": message,
        "site_name": site_name,
        "user_name": user_name or "there",
        "site_url": SITE_URL,
        "logo_url": LOGO_URL,
        "button_text": button_text,
        "button_url": button_url,
        "preheader": preheader,
    }

    html_message = html_template.render(context)

    # Convert the HTML message into a plain-text fallback.
    plain_message = strip_tags(message)

    plain_message = " ".join(
        plain_message.split()
    )

    msg = EmailMultiAlternatives(
        subject,
        plain_message,
        "ExactSub <info@exactsub.com>",
        [email]
    )

    msg.attach_alternative(
        html_message,
        "text/html"
    )

    msg.send()
    
def send_notification_to_all_customers(users,body):
    keys = "EAAcsSgCLQsABPpbbQB1Oddx4MKYTRPbN98YqBmkaqCjI7vPaSxOkJNHZAAmn7hGnpmVmzCoQksbu6vZBAZCJPDjyiZBRuVLALnM6mAOvGqOUXiJ6fzyTIyvW6uU2LnlAXyow6CwL9PAmFqk8OX4BB1cY1r13ckrMbZAQPuAqJ5eoCcwbtq1MGIoZANpZBlLKlkxaAZDZD"
    url = "https://graph.facebook.com/v22.0/828938420299590/messages"

    headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {keys}"
            }
                                    
    for cus in users:
                print(cus.username)
                try:
                                        
                    pbody = {
                            "messaging_product": "whatsapp",
                            "recipient_type": "individual",
                            "to": cus.phoneNumber,
                            "type": "text",
                            "text": {
                                    "body": body,
                                    "preview_url": True,
                                     }
                                 }
                    response = requests.post(url, headers=headers, json=pbody)
                    time.sleep(2) 
                    print(response.text)
                except:
                    pass
    
    

def request_id_gen():
        # Request ID generator
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M%S")
        tok = uuid.uuid4()
        token = tok.hex
        req = the_date + token
        request_id = req[0:30]
        return request_id
        
def getdate():
    date_time = datetime.now()
    the_date = date_time.strftime("%d/%m/%Y, %I:%M:%S %p")
    return the_date


# Create your models here.
class AppUserManager(UserManager):
    def get_by_natural_key(self, username):
        case_insensitive_username_field = '{}__iexact'.format(
            self.model.USERNAME_FIELD)
        return self.get(**{case_insensitive_username_field: username})


class AppUser(AbstractUser):
    object = AppUserManager()
    firstName = models.CharField(max_length=500, null=False)
    lastName = models.CharField(max_length=500, null=False)
    phoneNumber = models.CharField(max_length=500, null=False)
    email = models.EmailField(null=False)
    password = models.CharField(max_length=500, null=True)
    category = models.CharField(max_length=500, choices=(('EARNER', 'EARNER'), ('AFFILIATE', 'AFFILIATE'), ('AMBASSADOR', 'AMBASSADOR'), ('API1', 'API1'), ('API2', 'AP12'), ('API3', 'API3')), null=True, default='EARNER')
    balance = models.FloatField(max_length=500, default=0.0, validators=[MinValueValidator(0.0)],)
    bonus = models.FloatField(max_length=500, default=0.0, validators=[MinValueValidator(0.0)],)
    acctref = models.CharField(max_length=500, null=True, blank=True)
    transaction_pin = models.CharField(max_length=5, null=True, blank=True)
    refnum = models.CharField(max_length=500, null=True, blank=True)
    activate = models.BooleanField(default=False, help_text="Activate user for API access.")
    verify = models.BooleanField(default=False)
    email_verify = models.BooleanField(default=True)
    bvn = models.CharField(max_length=500, null=True, blank=True)
    payscribe_cus_id = models.CharField(max_length=500, null=True, blank=True)
    dob = models.DateField(null=True, blank=True, )
    monnify_accounts = models.TextField(blank=True, null=True)
    crystal_accounts = models.TextField(blank=True, null=True)
    payscribe_accounts = models.TextField(blank=True, null=True)
    payvessel_accounts = models.TextField(blank=True, null=True)
    paymentpoint_accounts = models.TextField(blank=True, null=True)
    securewave_accounts = models.TextField(blank=True, null=True)
    palmpay_account = models.TextField(blank=True, null=True)
    palmpay_ref = models.CharField(max_length=500, null=True, blank=True)
    fcm_token = models.CharField(max_length=500, null=True, blank=True)
    api_key = models.CharField(max_length=500, null=True, blank=True)
    mtn_sme = models.FloatField(max_length=500, default=0.0, validators=[MinValueValidator(0.0)],)
    mtn_cg = models.FloatField(max_length=500, default=0.0, validators=[MinValueValidator(0.0)],)
    glo_cg = models.FloatField(max_length=500, default=0.0, validators=[MinValueValidator(0.0)],)
    airtel_cg = models.FloatField(max_length=500, default=0.0, validators=[MinValueValidator(0.0)],)
    mobile_cg = models.FloatField(max_length=500, default=0.0, validators=[MinValueValidator(0.0)],)


    @classmethod
    def debit(cls, id, amount):
        with transaction.atomic():
            account = (cls.objects.select_for_update().get(id=id))
            
            # balance_before = account.balance
            if account.balance < amount or amount < 0:
                return False
            account.balance -= amount
            account.balance = round(account.balance, 2)
            account.save()

            return True
        
            
            
    @classmethod
    def fund(cls, id, amount):
        with transaction.atomic():
            account = (cls.objects.select_for_update().get(id=id))
            account.balance += amount
            account.balance = round(account.balance, 2)
            account.save()
            
    @classmethod
    def fundmtnsme(cls, id, amount):
        with transaction.atomic():
            account = (cls.objects.select_for_update().get(id=id))
            account.mtn_sme += amount
            account.save()
    
    @classmethod
    def debitmtnsme(cls, id, amount):
        with transaction.atomic():
            account = (cls.objects.select_for_update().get(id=id))
            account.mtn_sme -= amount
            account.save()

    
    @classmethod
    def fundmtncg(cls, id, amount):
        with transaction.atomic():
            account = (cls.objects.select_for_update().get(id=id))
            account.mtn_cg += amount
            account.save()
    
    @classmethod
    def debitmtncg(cls, id, amount):
        with transaction.atomic():
            account = (cls.objects.select_for_update().get(id=id))
            account.mtn_cg -= amount
            account.save()
    
    @classmethod
    def fundglocg(cls, id, amount):
        with transaction.atomic():
            account = (cls.objects.select_for_update().get(id=id))
            account.glo_cg += amount
            account.save()
    
    @classmethod
    def debitglocg(cls, id, amount):
        with transaction.atomic():
            account = (cls.objects.select_for_update().get(id=id))
            account.glo_cg -= amount
            account.save()

    @classmethod
    def fundairtelcg(cls, id, amount):
        with transaction.atomic():
            account = (cls.objects.select_for_update().get(id=id))
            account.airtel_cg += amount
            account.save()
    
    @classmethod
    def debitairtelcg(cls, id, amount):
        with transaction.atomic():
            account = (cls.objects.select_for_update().get(id=id))
            account.airtel_cg -= amount
            account.save()

    @classmethod
    def fundmobilecg(cls, id, amount):
        with transaction.atomic():
            account = (cls.objects.select_for_update().get(id=id))
            account.mobile_cg += amount
            account.save()
    
    @classmethod
    def debitmobilecg(cls, id, amount):
        with transaction.atomic():
            account = (cls.objects.select_for_update().get(id=id))
            account.mobile_cg -= amount
            account.save()


    def __str__(self):
        return self.username

    class Meta:
        verbose_name_plural = 'USER MANAGEMENT'


class Usersession(models.Model):
    user = models.ForeignKey(AppUser, on_delete=models.CASCADE, editable=False, blank=False, null=True)
    stored_key = models.CharField(max_length=500, null=True)
    
    def __str__(self):
        return self.user.username

    class Meta:
        verbose_name_plural = 'USER SESSIONS'



class KycVerificationAttempt(models.Model):
    # Store the existing AppUser primary key as an integer.
    # This intentionally avoids creating a database foreign key.
    user_id = models.IntegerField()

    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_at"]
        indexes = [
            models.Index(
                fields=["user_id", "created_at"],
                name="kyc_user_created_idx"
            )
        ]

    def __str__(self):
        return f"KYC attempt - User {self.user_id}"


class Transact(models.Model):
    user = models.ForeignKey(AppUser, on_delete=models.CASCADE, editable=False, blank=False, null=True)
    transaction = models.TextField(null=True)
    email = models.CharField(max_length=500, null=True)
    status = models.CharField(max_length=500, null=True)
    cost = models.CharField(max_length=500, null=True)
    date = models.CharField(max_length=500, null=True, default=getdate)
    old_balance = models.FloatField(max_length=500, null=True)
    new_balance = models.FloatField(max_length=500, null=True)
    phone_number = models.CharField(max_length=500, null=True)
    d_network = models.CharField(max_length=500, null=True)
    request_id = models.CharField(max_length=500, null=True, default=request_id_gen)
    value = models.CharField(max_length=500, null=True, blank=True)
    volume = models.CharField(max_length=500, null=True, blank=True)
    provider_source = models.CharField(max_length=500, null=True, blank=True)

    def __str__(self):
        return self.status

    class Meta:
        verbose_name_plural = 'TRANSACTIONS'

class TransactionDelivery(models.Model):
    transaction_id = models.IntegerField(
        unique=True,
        db_index=True
    )

    delivery_type = models.CharField(
        max_length=50,
        choices=(
            ("ELECTRICITY", "Electricity"),
            ("EXAM_PIN", "Exam PIN"),
        )
    )

    data = models.TextField(
        blank=True,
        null=True
    )

    created_at = models.DateTimeField(
        auto_now_add=True
    )

    def __str__(self):
        return "{} - {}".format(
            self.delivery_type,
            self.transaction_id
        )

    class Meta:
        verbose_name = "TRANSACTION DELIVERY"
        verbose_name_plural = "TRANSACTION DELIVERIES"


class Config(models.Model):
    Atuns_web_url = models.CharField(max_length=500, null=True, blank=True)
    Atuns_web_api_key = models.CharField(max_length=500, null=True, blank=True)
    ms_url = models.CharField(max_length=500, null=True, blank=True)
    ms_api_key = models.CharField(max_length=500, null=True, blank=True)
    ms_url_2 = models.CharField(max_length=500, null=True, blank=True)
    ms_api_key_2 = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_url = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_key = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_url_2 = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_key_2 = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_url_3 = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_key_3 = models.CharField(max_length=500, null=True, blank=True)
    monnify_apikey = models.CharField(max_length=500, null=True, blank=True)
    monnify_secretkey = models.CharField(max_length=500, null=True, blank=True)
    ringo_email = models.CharField(max_length=500, null=True, blank=True)
    ringo_password = models.CharField(max_length=500, null=True, blank=True)
    autopilot_key = models.CharField(max_length=500, null=True, blank=True)
    gongoz_api_key = models.CharField(max_length=500, null=True, blank=True)
    topupaccess_api_key = models.CharField(
        max_length=500,
        null=True,
        blank=True
    )
    topupaccess_pin = models.CharField(
        max_length=500,
        null=True,
        blank=True
    )
    # autopilot_key_2 = models.CharField(max_length=500, null=True, blank=True)
    # abumpay_key = models.CharField(max_length=500, null=True, blank=True)
    buypower_key = models.CharField(max_length=500, null=True, blank=True)
    ogdams_key = models.CharField(max_length=500, null=True, blank=True)
    # imansub_key = models.CharField(max_length=500, null=True, blank=True)
    cloudsimhost_key = models.CharField(max_length=500, null=True, blank=True)
    simserver_key = models.CharField(max_length=500, null=True, blank=True)
    apisubportal_key = models.CharField(max_length=500, null=True, blank=True)
    # apisubportal_key_2 = models.CharField(max_length=500, null=True, blank=True)
    contract_code = models.CharField(max_length=500, null=True, blank=True)
    vtpass_api_key = models.CharField(max_length=500, null=True, blank=True)
    account_number = models.CharField(max_length=500, null=True, blank=True)
    account_name = models.CharField(max_length=500, null=True, blank=True)
    bank_name = models.CharField(max_length=500, null=True, blank=True)
    pop_message = models.CharField(max_length=500, null=True, blank=True)
    scroll_message = models.CharField(max_length=500, null=True, blank=True)
    merrybills_api_key = models.TextField(null=True, blank=True)
    bulksms_api_key = models.CharField(max_length=500, null=True, blank=True)
    crystal_pay_key = models.CharField(max_length=500, null=True, blank=True)
    # providus_client_secret = models.CharField(max_length=500, null=True, blank=True)
    # providus_client_id = models.CharField(max_length=500, null=True, blank=True)
    palmpay_private_key = models.TextField(null=True, blank=True)
    palmpay_public_key = models.TextField(null=True, blank=True)
    palmpay_app_id = models.TextField(null=True, blank=True)
    payvessel_sk_key = models.CharField(max_length=500, null=True, blank=True)
    payvessel_bizID = models.CharField(max_length=500, null=True, blank=True)
    payvessel_api_key = models.CharField(max_length=500, null=True, blank=True)
    smeplug_api_key = models.CharField(max_length=500, null=True, blank=True)
    # payscribe_sk_key = models.CharField(max_length=500, null=True, blank=True)
    paymentpoint_api_key = models.CharField(max_length=500, null=True, blank=True)
    paymentpoint_secret_key = models.CharField(max_length=500, null=True, blank=True)
    paymentpoint_app_id = models.CharField(max_length=500, null=True, blank=True)
    bank_name2 = models.CharField(max_length=500, null=True, blank=True)
    account_name2 = models.CharField(max_length=500, null=True, blank=True)
    account_number2 = models.CharField(max_length=500, null=True, blank=True)
    mtn_num = models.CharField(max_length=500, null=True, blank=True)
    glo_num = models.CharField(max_length=500, null=True, blank=True)
    airtel_num = models.CharField(max_length=500, null=True, blank=True)
    mobile_num = models.CharField(max_length=500, null=True, blank=True)
    whatsapp_num = models.CharField(max_length=500, null=True, blank=True)
    whatsapp_group = models.CharField(max_length=500, null=True, blank=True)
    admin_mail = models.CharField(max_length=500, null=True, blank=True)
    monnify_charges = models.IntegerField(null=True, blank=True, help_text="Set charges e.g 50. Note, your are to set either charges or percent not the two.")
    monnify_percent = models.FloatField(max_length=500, null=True, blank=True, help_text="Set percent e.g 0.98 to fund users 98%. Note, your are to set either charges or percent not the two.")
    securewave_charges = models.IntegerField(null=True, blank=True, help_text="Set charges e.g 50. Note, your are to set either charges or percent not the two.")
    securewave_percent = models.FloatField(max_length=500, null=True, blank=True, help_text="Set percent e.g 0.98 to fund users 98%. Note, your are to set either charges or percent not the two.")
    affiliate_upgrade_amount = models.FloatField(max_length=500, null=True, blank=True, help_text="Set price for Affiliate upgrade")
    ambassador_upgrade_amount = models.FloatField(max_length=500, null=True, blank=True, help_text="Set price for Ambassador upgrade")
    earner_transaction_limit = models.FloatField(max_length=500, null=True, blank=True, help_text="Set price for Earner Transaction Limit")
    affiliate_transaction_limit = models.FloatField(max_length=500, null=True, blank=True, help_text="Set price for Affiliate Transaction Limit")
    ambassador_transaction_limit = models.FloatField(max_length=500, null=True, blank=True, help_text="Set price for Ambassador Transaction Limit")
    set_transaction_limit = models.BooleanField(default=True)
    referral_bonus = models.IntegerField(null=True, blank=True, help_text="Set  Referral Bonus, e.g 50")
    refer_note = models.TextField(null=True, blank=True)
    pluginng_email = models.CharField(max_length=500, null=True, blank=True)
    pluginng_password = models.CharField(max_length=500, null=True, blank=True)
    imansub_api_key = models.CharField(max_length=500, null=True, blank=True)
    securewave_secret_key = models.CharField(max_length=500, null=True, blank=True)
    securewave_public_key = models.CharField(max_length=500, null=True, blank=True)
    securewave_business_id = models.CharField(max_length=500, null=True, blank=True)




    def __str__(self):
        return 'Website Configuration'

    class Meta:
        verbose_name_plural = 'WEBSITE CONFIGURATION'



class Sale(models.Model):
    user = models.ForeignKey(AppUser, on_delete=models.CASCADE, editable=False, blank=False, null=True,
                             related_name='sale')
    network = models.CharField(max_length=500, null=True)
    plan = models.CharField(max_length=500, null=True)
    status = models.CharField(max_length=500, null=True)
    cost = models.CharField(max_length=500, null=True)
    date = models.CharField(max_length=500, null=True)
    request_id = models.CharField(max_length=500, null=True, default=request_id_gen)

    def __str__(self):
        return self.status

    class Meta:
        verbose_name_plural = 'SALES'



class Mtnsmedata(models.Model):
    vending_medium = models.CharField(max_length=500, choices=(('manual_mtn', 'Manual'), ('atuns_mtn', 'ATUNS WEB'), ('simserverslot_mtn', 'Simserver Web Slot'), ('autopilot_mtn', 'Autopilot'), ('simserver_mtn', 'Simservers'), ('ms_mtn', 'MS WEB'), ('ms2_mtn', 'MS WEB2'), ('simserverslot2_mtn', 'Simserver Web Slot2'),  ('simserverslot3_mtn', 'Simserver Web Slot3'),('cloudsim_mtn', 'Cloud Sim Hosting'),('smeplug_mtn', 'Smeplug')), null=True)
    volume = models.CharField(max_length=500, null=True)
    amount = models.IntegerField(null=True)
    amount2 = models.IntegerField(null=True)
    amount3 = models.IntegerField(null=True)
    api1 = models.FloatField(null=True)
    api2 = models.FloatField(null=True)
    api3 = models.FloatField(null=True)
    plan_id = models.CharField(max_length=500, null=True, blank=True,help_text="leave blank sytem sets this automatically")
    Atuns_web_id = models.CharField(max_length=500, null=True, blank=True)
    ms_id = models.CharField(max_length=500, null=True, blank=True)
    autopilot_id = models.CharField(max_length=500, null=True, blank=True)
    # abumpay_plan_id = models.CharField(max_length=500, null=True, blank=True)
    cloudsim_plan_id = models.CharField(max_length=500, null=True, blank=True)
    simserver_plan_id = models.CharField(max_length=500, null=True, blank=True)
    smeplug_id = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id_2 = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id_3 = models.CharField(max_length=500, null=True, blank=True)
    ms_id_2 = models.CharField(max_length=500, null=True, blank=True)
    validity = models.CharField(max_length=500, null=True, blank=True)
    


    def __str__(self):
        return self.volume
        
    def save(self, *args, **kwargs):
        self.plan_id = self.volume + '_MTN-SME'
        
        super(Mtnsmedata, self).save(*args, **kwargs)

    class Meta:
        verbose_name_plural = 'MTN SME'
        
class Mtndirectgifting(models.Model):
    vending_medium = models.CharField(max_length=500, choices=(('manual_directgifting', 'Manual'),('atuns_directgifting', 'ATUNS WEB'),('vtpass_directgifting', 'VTPASS'), ('imansub_directgifting', 'IMANSUB'), ('autopilot_directgifting', 'Autopilot'), ('ms_directgifting', 'MS WEB'), ('ms2_directgifting', 'MS WEB2'), ('simserverslot2_directgifting', 'Simserver Web Slot2'),  ('simserverslot3_directgifting', 'Simserver Web Slot3')), null=True)
    volume = models.CharField(max_length=500, null=True)
    amount = models.IntegerField(null=True)
    amount2 = models.IntegerField(null=True)
    amount3 = models.IntegerField(null=True)
    api1 = models.FloatField(null=True)
    api2 = models.FloatField(null=True)
    api3 = models.FloatField(null=True)
    plan_id = models.CharField(max_length=500, null=True, blank=True,help_text="leave blank sytem sets this automatically")
    Atuns_web_id = models.CharField(max_length=500, null=True, blank=True)
    ms_id = models.CharField(max_length=500, null=True, blank=True)
    autopilot_id = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id_2 = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id_3 = models.CharField(max_length=500, null=True, blank=True)
    ms_id_2 = models.CharField(max_length=500, null=True, blank=True)
    vtpass_variation_code = models.CharField(max_length=500, null=True, blank=True)
    imansub_plan_id = models.CharField(max_length=500, null=True, blank=True)
    validity = models.CharField(max_length=500, null=True, blank=True)


    def __str__(self):
        return self.volume
        
    def save(self, *args, **kwargs):
        self.plan_id = self.volume + '_MTN-DG'

        super(Mtndirectgifting, self).save(*args, **kwargs)

    class Meta:
        verbose_name_plural = 'MTN DIRECT GIFTING'


class Mtndatashare(models.Model):
    vending_medium = models.CharField(max_length=500, choices=(('autopilot_sme1', 'Autopilot'),('topupaccess_sme1', 'Topupaccess'),('smeplug_sme1', 'Smeplug'), ('imansub_sme1', 'IMANSUB'), ('atuns_sme1', 'ATUNS WEB'),  ('simserverslot_sme1', 'Simserver Web Slot'), ('ms_sme1', 'MS WEB'), ('ms2_sme1', 'MS WEB2'), ('simserverslot2_sme1', 'Simserver Web Slot2'), ('simserverslot3_sme1', 'Simserver Web Slot3'), ('gongoz_sme1', 'Gongoz'), ('manual_sme1', 'Manual')), null=True)
    volume = models.CharField(max_length=500, null=True)
    amount = models.IntegerField(null=True)
    amount2 = models.IntegerField(null=True)
    amount3 = models.IntegerField(null=True)
    api1 = models.FloatField(null=True)
    api2 = models.FloatField(null=True)
    api3 = models.FloatField(null=True)
    plan_id = models.CharField(max_length=500, null=True, blank=True,help_text="leave blank sytem sets this automatically")
    Atuns_web_id = models.CharField(max_length=500, null=True, blank=True)
    ms_id = models.CharField(max_length=500, null=True, blank=True)
    autopilot_id = models.CharField(max_length=500, null=True, blank=True)
    # autopilot_id_2 = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id_2 = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id_3 = models.CharField(max_length=500, null=True, blank=True)
    # smeplug_id = models.CharField(max_length=500, null=True, blank=True)
    ms_id_2 = models.CharField(max_length=500, null=True, blank=True)
    # mvtelecoms_plan_id = models.CharField(max_length=500, null=True, blank=True)
    gongoz_plan_id = models.CharField(max_length=500, null=True, blank=True)
    # unaysenet_plan_id = models.CharField(max_length=500, null=True, blank=True)
    topupaccess_plan_id = models.CharField(max_length=500, null=True, blank=True)
    # alkam_plan_id = models.CharField(max_length=500, null=True, blank=True)
    imansub_plan_id = models.CharField(max_length=500, null=True, blank=True)
    validity = models.CharField(max_length=500, null=True, blank=True)

    def __str__(self):
        return self.volume
        
    def save(self, *args, **kwargs):
        self.plan_id = self.volume + '_MTN-DATASHARE'
        
        super(Mtndatashare, self).save(*args, **kwargs)


    class Meta:
        verbose_name_plural = 'MTN DATASHARE'


class Mtnawoofgifting(models.Model):
    vending_medium = models.CharField(max_length=500, choices=(('manual_awoofgifting', 'Manual'), ('atuns_awoofgifting', 'ATUNS WEB'), ('autopilot_awoofgifting', 'Autopilot'), ('ms_awoofgifting', 'MS WEB'), ('ms2_awoofgifting', 'MS WEB2')), null=True)
    volume = models.CharField(max_length=500, null=True)
    amount = models.IntegerField(null=True)
    amount2 = models.IntegerField(null=True)
    amount3 = models.IntegerField(null=True)
    api1 = models.FloatField(null=True)
    api2 = models.FloatField(null=True)
    api3 = models.FloatField(null=True)
    plan_id = models.CharField(max_length=500, null=True, blank=True,help_text="leave blank sytem sets this automatically")
    Atuns_web_id = models.CharField(max_length=500, null=True, blank=True)
    ms_id = models.CharField(max_length=500, null=True, blank=True)
    autopilot_id = models.CharField(max_length=500, null=True, blank=True)
    # simserver_web_id_2 = models.CharField(max_length=500, null=True, blank=True)
    # simserver_web_id_3 = models.CharField(max_length=500, null=True, blank=True)
    ms_id_2 = models.CharField(max_length=500, null=True, blank=True)
    validity = models.CharField(max_length=500, null=True, blank=True)

    def __str__(self):
        return self.volume
        
    def save(self, *args, **kwargs):
        self.plan_id = self.volume + '_MTN-AWOOF-GIFTING'
        
        super(Mtnawoofgifting, self).save(*args, **kwargs)


    class Meta:
        verbose_name_plural = 'MTN AWOOF GIFTING'        




class Mtncoupon(models.Model):
    vending_medium = models.CharField(max_length=500, choices=(('manual_directcoupon', 'Manual'),  ('atuns_directcoupon', 'ATUNS WEB'), ('ms_directcoupon', 'MS WEB'),('ms2_directcoupon', 'MS WEB2')), null=True)
    volume = models.CharField(max_length=500, null=True)
    amount = models.IntegerField(null=True)
    amount2 = models.IntegerField(null=True)
    amount3 = models.IntegerField(null=True)
    api1 = models.FloatField(null=True)
    api2 = models.FloatField(null=True)
    api3 = models.FloatField(null=True)
    plan_id = models.CharField(max_length=500, null=True, blank=True,help_text="leave blank sytem sets this automatically")
    Atuns_web_id = models.CharField(max_length=500, null=True, blank=True)
    ms_id = models.CharField(max_length=500, null=True, blank=True)
    autopilot_id = models.CharField(max_length=500, null=True, blank=True)
    # simserver_web_id_2 = models.CharField(max_length=500, null=True, blank=True)
    # simserver_web_id_3 = models.CharField(max_length=500, null=True, blank=True)
    ms_id_2 = models.CharField(max_length=500, null=True, blank=True)
    validity = models.CharField(max_length=500, null=True, blank=True)

    def __str__(self):
        return self.volume
        
    def save(self, *args, **kwargs):
        self.plan_id = self.volume + '_MTNDIRECT-COUPON'
        
        super(Mtncoupon, self).save(*args, **kwargs)


    class Meta:
        verbose_name_plural = 'MTN DIRECT COUPON'


class Airteldata(models.Model):
    vending_medium = models.CharField(max_length=500, choices=(('manual_airtel', 'Manual'),  ('atuns_airtel', 'ATUNS WEB'),('vtpass_airtel', 'VTPASS'), ('imansub_airtel', 'IMANSUB'), ('autopilot_airtel', 'Autopilot'), ('ms_airtel', 'MS WEB'),('ms2_airtel', 'MS WEB2'), ('simserverslot2_airtel', 'Simserver Web Slot2'), ('simserverslot3_airtel', 'Simserver Web Slot3')), null=True)
    volume = models.CharField(max_length=500, null=True)
    amount = models.IntegerField(null=True)
    amount2 = models.IntegerField(null=True)
    amount3 = models.IntegerField(null=True)
    api1 = models.FloatField(null=True)
    api2 = models.FloatField(null=True)
    api3 = models.FloatField(null=True)
    plan_id = models.CharField(max_length=500, null=True, blank=True,help_text="leave blank sytem sets this automatically")
    Atuns_web_id = models.CharField(max_length=500, null=True, blank=True)
    ms_id = models.CharField(max_length=500, null=True, blank=True)
    autopilot_id = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id_2 = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id_3 = models.CharField(max_length=500, null=True, blank=True)
    ms_id_2 = models.CharField(max_length=500, null=True, blank=True)
    vtpass_variation_code = models.CharField(max_length=500, null=True, blank=True)
    imansub_plan_id = models.CharField(max_length=500, null=True, blank=True)
    validity = models.CharField(max_length=500, null=True, blank=True)
    def __str__(self):
        return self.volume
        
    def save(self, *args, **kwargs):
        self.plan_id = self.volume + '_AIRTEL'
        
        super(Airteldata, self).save(*args, **kwargs)


    class Meta:
        verbose_name_plural = 'AIRTEL'

class Airtelcgdata(models.Model):
    vending_medium = models.CharField(max_length=500, choices=(('manual_airtelcg', 'Manual'), ('atuns_airtelcg', 'ATUNS WEB'), ('simserverslot_airtelcg', 'Simserver Web Slot'), ('autopilot_airtelcg', 'Autopilot'), ('ms_airtelcg', 'MS WEB'), ('simserver_airtelcg', 'Simservers'),('ms2_airtelcg', 'MS WEB2'), ('simserverslot2_airtelcg', 'Simserver Web Slot2'), ('simserverslot3_airtelcg', 'Simserver Web Slot3')), null=True)
    volume = models.CharField(max_length=500, null=True)
    amount = models.IntegerField(null=True)
    amount2 = models.IntegerField(null=True)
    amount3 = models.IntegerField(null=True)
    api1 = models.FloatField(null=True)
    api2 = models.FloatField(null=True)
    api3 = models.FloatField(null=True)
    plan_id = models.CharField(max_length=500, null=True, blank=True,help_text="leave blank sytem sets this automatically")
    Atuns_web_id = models.CharField(max_length=500, null=True, blank=True)
    ms_id = models.CharField(max_length=500, null=True, blank=True)
    autopilot_id = models.CharField(max_length=500, null=True, blank=True)
    simserver_plan_id = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id_2 = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id_3 = models.CharField(max_length=500, null=True, blank=True)
    ms_id_2 = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id = models.CharField(max_length=500, null=True, blank=True)
    validity = models.CharField(max_length=500, null=True, blank=True)

    def __str__(self):
        return self.volume
        
    def save(self, *args, **kwargs):
        self.plan_id = self.volume + '_AIRTEL-CG'
        
        super(Airtelcgdata, self).save(*args, **kwargs)


    class Meta:
        verbose_name_plural = 'AIRTEL CG'
        
        
class Airtelawoofgifting(models.Model):
    vending_medium = models.CharField(max_length=500, choices=(('manual_airtelawoof', 'Manual'),  ('atuns_airtelawoof', 'ATUNS WEB'), ('autopilot_airtelawoof', 'Autopilot'), ('ms_airtelawoof', 'MS WEB'),('ms2_airtelawoof', 'MS WEB2')), null=True)
    volume = models.CharField(max_length=500, null=True)
    amount = models.IntegerField(null=True)
    amount2 = models.IntegerField(null=True)
    amount3 = models.IntegerField(null=True)
    api1 = models.FloatField(null=True)
    api2 = models.FloatField(null=True)
    api3 = models.FloatField(null=True)
    plan_id = models.CharField(max_length=500, null=True, blank=True,help_text="leave blank sytem sets this automatically")
    Atuns_web_id = models.CharField(max_length=500, null=True, blank=True)
    ms_id = models.CharField(max_length=500, null=True, blank=True)
    autopilot_id = models.CharField(max_length=500, null=True, blank=True)
    # simserver_web_id_2 = models.CharField(max_length=500, null=True, blank=True)
    # simserver_web_id_3 = models.CharField(max_length=500, null=True, blank=True)
    ms_id_2 = models.CharField(max_length=500, null=True, blank=True)
    validity = models.CharField(max_length=500, null=True, blank=True)

    def __str__(self):
        return self.volume
        
    def save(self, *args, **kwargs):
        self.plan_id = self.volume + '_AIRTEL-AWOOF'
        
        super(Airtelawoofgifting, self).save(*args, **kwargs)


    class Meta:
        verbose_name_plural = 'AIRTEL AWOOF GIFTING'        

class Glodata(models.Model):
    vending_medium = models.CharField(max_length=500, choices=(('manual_glo', 'Manual'),  ('atuns_glo', 'ATUNS WEB'), ('vtpass_glo', 'VTPASS'), ('imansub_glo', 'IMANSUB'),('autopilot_glo', 'Autopilot'), ('ms_glo', 'MS WEB'),('ms2_glo', 'MS WEB2'), ('simserverslot2_glo', 'Simserver Web Slot2'), ('simserverslot3_glo', 'Simserver Web Slot3')), null=True)
    volume = models.CharField(max_length=500, null=True)
    amount = models.IntegerField(null=True)
    amount2 = models.IntegerField(null=True)
    amount3 = models.IntegerField(null=True)
    api1 = models.FloatField(null=True)
    api2 = models.FloatField(null=True)
    api3 = models.FloatField(null=True)
    plan_id = models.CharField(max_length=500, null=True, blank=True,help_text="leave blank sytem sets this automatically")
    Atuns_web_id = models.CharField(max_length=500, null=True, blank=True)
    ms_id = models.CharField(max_length=500, null=True, blank=True)
    autopilot_id = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id_2 = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id_3 = models.CharField(max_length=500, null=True, blank=True)
    ms_id_2 = models.CharField(max_length=500, null=True, blank=True)
    vtpass_variation_code = models.CharField(max_length=500, null=True, blank=True)
    imansub_plan_id = models.CharField(max_length=500, null=True, blank=True)
    validity = models.CharField(max_length=500, null=True, blank=True)


    def __str__(self):
        return self.volume
        
    def save(self, *args, **kwargs):
        self.plan_id = self.volume + '_GLO'
        
        super(Glodata, self).save(*args, **kwargs)


    class Meta:
        verbose_name_plural = 'GLO'


class Glocgdata(models.Model):
    vending_medium = models.CharField(max_length=500, choices=(('manual_glocg', 'Manual'), ('topupaccess_glocg', 'Topupaccess'), ('imansub_glocg', 'IMANSUB'), ('atuns_glocg', 'ATUNS WEB'), ('simserverslot_glocg', 'Simserver Web Slot'), ('autopilot_glocg', 'Autopilot'), ('ms_glocg', 'MS WEB'),('ms2_glocg', 'MS WEB2'), ('simserverslot2_glocg', 'Simserver Web Slot2'),('simserverslot3_glocg', 'Simserver Web Slot3')), null=True)
    volume = models.CharField(max_length=500, null=True)
    amount = models.IntegerField(null=True)
    amount2 = models.IntegerField(null=True)
    amount3 = models.IntegerField(null=True)
    api1 = models.FloatField(null=True)
    api2 = models.FloatField(null=True)
    api3 = models.FloatField(null=True)
    plan_id = models.CharField(max_length=500, null=True, blank=True,help_text="leave blank sytem sets this automatically")
    Atuns_web_id = models.CharField(max_length=500, null=True, blank=True)
    ms_id = models.CharField(max_length=500, null=True, blank=True)
    autopilot_id = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id_2 = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id_3 = models.CharField(max_length=500, null=True, blank=True)
    ms_id_2 = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id = models.CharField(max_length=500, null=True, blank=True)
    apisubportal_plan_id = models.CharField(max_length=500, null=True, blank=True)
    topupaccess_plan_id = models.CharField(max_length=500, null=True, blank=True)
    imansub_plan_id = models.CharField(max_length=500, null=True, blank=True)
    validity = models.CharField(max_length=500, null=True, blank=True)

    def __str__(self):
        return self.volume
        
    def save(self, *args, **kwargs):
        self.plan_id = self.volume + '_GLO-CG'
        
        super(Glocgdata, self).save(*args, **kwargs)


    class Meta:
        verbose_name_plural = 'GLO CG'
        
class Glospecialdata(models.Model):
    vending_medium = models.CharField(max_length=500, choices=(('manual_gloawoof', 'Manual'),  ('atuns_gloawoof', 'ATUNS WEB'),('simserverslot_gloawoof', 'Simserver Web Slot'), ('autopilot_gloawoof', 'Autopilot'), ('ms_gloawoof', 'MS WEB'),('ms2_gloawoof', 'MS WEB2'), ('simserverslot2_gloawoof', 'Simserver Web Slot2'), ('simserverslot3_gloawoof', 'Simserver Web Slot3')), null=True)
    volume = models.CharField(max_length=500, null=True)
    amount = models.IntegerField(null=True)
    amount2 = models.IntegerField(null=True)
    amount3 = models.IntegerField(null=True)
    api1 = models.FloatField(null=True)
    api2 = models.FloatField(null=True)
    api3 = models.FloatField(null=True)
    plan_id = models.CharField(max_length=500, null=True, blank=True,help_text="leave blank sytem sets this automatically")
    Atuns_web_id = models.CharField(max_length=500, null=True, blank=True)
    ms_id = models.CharField(max_length=500, null=True, blank=True)
    autopilot_id = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id_2 = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id_3 = models.CharField(max_length=500, null=True, blank=True)
    ms_id_2 = models.CharField(max_length=500, null=True, blank=True)
    validity = models.CharField(max_length=500, null=True, blank=True)

    def __str__(self):
        return self.volume
    
    def save(self, *args, **kwargs):
        self.plan_id = self.volume + '_GLO-AWOOF-GIFTING'
        
        super(Glospecialdata, self).save(*args, **kwargs)


    class Meta:
        verbose_name_plural = 'GLO AWOOF GIFTING'



class Mobiledata(models.Model):
    vending_medium = models.CharField(max_length=500, choices=(('manual_mobile', 'Manual'),  ('atuns_mobile', 'ATUNS WEB'), ('vtpass_mobile', 'VTPASS'),('autopilot_mobile', 'Autopilot'), ('ms_mobile', 'MS WEB'),('ms2_mobile', 'MS WEB2')), null=True)
    volume = models.CharField(max_length=500, null=True)
    amount = models.IntegerField(null=True)
    amount2 = models.IntegerField(null=True)
    amount3 = models.IntegerField(null=True)
    api1 = models.FloatField(null=True)
    api2 = models.FloatField(null=True)
    api3 = models.FloatField(null=True)
    plan_id = models.CharField(max_length=500, null=True, blank=True,help_text="leave blank sytem sets this automatically")
    Atuns_web_id = models.CharField(max_length=500, null=True, blank=True)
    ms_id = models.CharField(max_length=500, null=True, blank=True)
    autopilot_id = models.CharField(max_length=500, null=True, blank=True)
    # simserver_web_id_2 = models.CharField(max_length=500, null=True, blank=True)
    # simserver_web_id_3 = models.CharField(max_length=500, null=True, blank=True)
    ms_id_2 = models.CharField(max_length=500, null=True, blank=True)
    vtpass_variation_code = models.CharField(max_length=500, null=True, blank=True)
    validity = models.CharField(max_length=500, null=True, blank=True)

    def __str__(self):
        return self.volume
        
    def save(self, *args, **kwargs):
        self.plan_id = self.volume + '_9MOBILE'
        
        super(Mobiledata, self).save(*args, **kwargs)



    class Meta:
        verbose_name_plural = '9MOBILE'


class Mobilesmedata(models.Model):
    vending_medium = models.CharField(max_length=500, choices=(('manual_mobilesme', 'Manual'), ('atuns_mobilesme', 'ATUNS WEB'),  ('simserverslot_mobilesme', 'Simserver Web Slot'),('autopilot_mobilesme', 'Autopilot'), ('ms_mobilesme', 'MS WEB'), ('ms2_mobilesme', 'MS WEB2'), ('simserverslot2_mobilesme', 'Simserver Web Slot2'), ('simserverslot3_mobilesme', 'Simserver Web Slot3')), null=True)
    volume = models.CharField(max_length=500, null=True)
    amount = models.IntegerField(null=True)
    amount2 = models.IntegerField(null=True)
    amount3 = models.IntegerField(null=True)
    api1 = models.FloatField(null=True)
    api2 = models.FloatField(null=True)
    api3 = models.FloatField(null=True)
    plan_id = models.CharField(max_length=500, null=True, blank=True,help_text="leave blank sytem sets this automatically")
    Atuns_web_id = models.CharField(max_length=500, null=True, blank=True)
    ms_id = models.CharField(max_length=500, null=True, blank=True)
    autopilot_id = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id_2 = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id_3 = models.CharField(max_length=500, null=True, blank=True)
    ms_id_2 = models.CharField(max_length=500, null=True, blank=True)
    validity = models.CharField(max_length=500, null=True, blank=True)

    def __str__(self):
        return self.volume
        
    def save(self, *args, **kwargs):
        self.plan_id = self.volume + '_9MOBILE-SME'
        
        super(Mobilesmedata, self).save(*args, **kwargs)

    class Meta:
        verbose_name_plural = '9MOBILE SME'



class Giftingdata(models.Model):
    vending_medium = models.CharField(max_length=500, choices=(('manual_gifting', 'Manual'), ('atuns_gifting', 'ATUNS WEB'), ('simserverslot_gifting', 'Simserver Web Slot'), ('autopilot_gifting', 'Autopilot'), ('ms_gifting', 'MS WEB'), ('ms2_gifting', 'MS WEB2'), ('simserverslot2_gifting', 'Simserver Web Slot2'), ('simserverslot3_gifting', 'Simserver Web Slot3'),('cloudsim_gifting', 'Cloud Sim Hosting')), null=True)
    volume = models.CharField(max_length=500, null=True)
    amount = models.IntegerField(null=True)
    amount2 = models.IntegerField(null=True)
    amount3 = models.IntegerField(null=True)
    api1 = models.FloatField(null=True)
    api2 = models.FloatField(null=True)
    api3 = models.FloatField(null=True)
    plan_id = models.CharField(max_length=500, null=True, blank=True,help_text="leave blank sytem sets this automatically")
    Atuns_web_id = models.CharField(max_length=500, null=True, blank=True)
    ms_id = models.CharField(max_length=500, null=True, blank=True)
    autopilot_id = models.CharField(max_length=500, null=True, blank=True)
    cloudsim_plan_id = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id_2 = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id_3 = models.CharField(max_length=500, null=True, blank=True)
    ms_id_2 = models.CharField(max_length=500, null=True, blank=True)
    validity = models.CharField(max_length=500, null=True, blank=True)

    def __str__(self):
        return self.volume
        
    def save(self, *args, **kwargs):
        self.plan_id = self.volume + '_MTN-CG'
        
        super(Giftingdata, self).save(*args, **kwargs)



    class Meta:
        verbose_name_plural = 'MTN CG'


class Giftinglitedata(models.Model):
    vending_medium = models.CharField(max_length=500, choices=(('manual_giftinglite', 'Manual'), ('atuns_giftinglite', 'ATUNS WEB'),('autopilot_giftinglite', 'Autopilot'), ('simserverslot_giftinglite', 'Simserver Web Slot'), ('ms_giftinglite', 'MS WEB'),('ms2_giftinglite', 'MS WEB2'), ('simserverslot2_giftinglite', 'Simserver Web Slot2'), ('simserverslot3_giftinglite', 'Simserver Web Slot3'), ('cloudsim_giftinglite', 'Cloud Sim Hosting')), null=True)
    volume = models.CharField(max_length=500, null=True)
    amount = models.IntegerField(null=True)
    amount2 = models.IntegerField(null=True)
    amount3 = models.IntegerField(null=True)
    api1 = models.FloatField(null=True)
    api2 = models.FloatField(null=True)
    api3 = models.FloatField(null=True)
    plan_id = models.CharField(max_length=500, null=True, blank=True,help_text="leave blank sytem sets this automatically")
    Atuns_web_id = models.CharField(max_length=500, null=True, blank=True)
    ms_id = models.CharField(max_length=500, null=True, blank=True)
    autopilot_id = models.CharField(max_length=500, null=True, blank=True)
    # alc_plan_id = models.CharField(max_length=500, null=True, blank=True)
    cloudsim_plan_id = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id_2 = models.CharField(max_length=500, null=True, blank=True)
    simserver_web_id_3 = models.CharField(max_length=500, null=True, blank=True)
    ms_id_2 = models.CharField(max_length=500, null=True, blank=True)
    validity = models.CharField(max_length=500, null=True, blank=True)

    def __str__(self):
        return self.volume
        
    def save(self, *args, **kwargs):
        self.plan_id = self.volume + '_MTN-CG-LITE'
        
        super(Giftinglitedata, self).save(*args, **kwargs)


    class Meta:
        verbose_name_plural = 'MTN CG LITE'



class Airtime(models.Model):
    network = models.CharField(max_length=500, null=True)
    discount = models.IntegerField(null=True)
    api = models.IntegerField(null=True)
    recharge_pin_discount = models.IntegerField(null=True)

    def __str__(self):
        return self.network

    class Meta:
        verbose_name_plural = 'AIRTIME'


class Electricity(models.Model):
    name = models.CharField(max_length=500, null=True)
    service = models.CharField(max_length=500, null=True)
    merrybills_code = models.CharField(max_length=500, null=True, blank=True)
    buypower_id = models.CharField(max_length=500, null=True, blank=True)
    discount = models.IntegerField(verbose_name=u"Charges", null=True)
    api = models.IntegerField(null=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = 'ELECTRICITY BILL'


class Convertocash(models.Model):
    network = models.CharField(max_length=500, null=True)
    charges = models.IntegerField(null=True)

    def __str__(self):
        return self.network

    class Meta:
        verbose_name_plural = 'AIRTIME TO CASH'


class Dstv(models.Model):
    package = models.CharField(max_length=500, null=True)
    amount = models.IntegerField(null=True)
    api = models.IntegerField(null=True)
    charge = models.IntegerField(default=0)
    api_charge = models.IntegerField(default=0)
    site_id = models.CharField(max_length=500, null=True, blank=True)
    vtpass_code = models.CharField(max_length=500, null=True, blank=True)
    merrybills_code = models.CharField(max_length=500, null=True, blank=True)
    apisub_code = models.CharField(max_length=500, null=True, blank=True)
    autopilot_code = models.CharField(max_length=500, null=True, blank=True)
    ringo_name = models.CharField(max_length=500, null=True, blank=True)
    ringo_code = models.CharField(max_length=500, null=True, blank=True)
    plan = models.IntegerField(null=True, blank=True)

    def __str__(self):
        return self.package

    class Meta:
        verbose_name_plural = 'DSTV'


class Gotv(models.Model):
    package = models.CharField(max_length=500, null=True)
    amount = models.IntegerField(null=True)
    api = models.IntegerField(null=True)
    charge = models.IntegerField(default=0)
    api_charge = models.IntegerField(default=0)
    site_id = models.CharField(max_length=500, null=True, blank=True)
    vtpass_code = models.CharField(max_length=500, null=True, blank=True)
    merrybills_code = models.CharField(max_length=500, null=True, blank=True)
    apisub_code = models.CharField(max_length=500, null=True, blank=True)
    autopilot_code = models.CharField(max_length=500, null=True, blank=True)
    ringo_name = models.CharField(max_length=500, null=True, blank=True)
    ringo_code = models.CharField(max_length=500, null=True, blank=True)
    plan = models.IntegerField(null=True, blank=True)

    def __str__(self):
        return self.package

    class Meta:
        verbose_name_plural = ' GOTV'


class Startimes(models.Model):
    package = models.CharField(max_length=500, null=True)
    amount = models.IntegerField(null=True)
    api = models.IntegerField(null=True)
    charge = models.IntegerField(default=0)
    api_charge = models.IntegerField(default=0)
    site_id = models.CharField(max_length=500, null=True, blank=True)
    vtpass_code = models.CharField(max_length=500, null=True, blank=True)
    merrybills_code = models.CharField(max_length=500, null=True, blank=True)
    apisub_code = models.CharField(max_length=500, null=True, blank=True)
    ringo_name = models.CharField(max_length=500, null=True, blank=True)
    ringo_code = models.CharField(max_length=500, null=True, blank=True)
    plan = models.IntegerField(null=True, blank=True)

    def __str__(self):
        return self.package

    class Meta:
        verbose_name_plural = 'STARTIMES'



class Lockdata(models.Model):
    service = models.CharField(max_length=500, null=True)
    availability = models.CharField(max_length=500, choices=(('ENABLE', 'ENABLE'), ('DISABLE', 'DISABLE')), null=True)


    def __str__(self):
        return self.service

    class Meta:
        verbose_name_plural = 'DATA LOCK'


class Lockservice(models.Model):
    service = models.CharField(max_length=500, null=True)
    availability = models.CharField(max_length=500, choices=(('ENABLE', 'ENABLE'), ('DISABLE', 'DISABLE')), null=True)

    def __str__(self):
        return self.service

    class Meta:
        verbose_name_plural = 'SERVICE LOCK'


class Airtime_Switch(models.Model):
    mtn = models.CharField(max_length=500, choices=(('airtime_autopilot', 'Autopilot'),  ('airtime_ringo', 'Ringo'), ('airtime_atuns', 'ATUNS WEB'), ('airtime_vtpass', 'VTpass'), ('airtime_merrybills', 'Merrybills'), ('airtime_ogdams', 'Ogdams')), null=True)
    airtel = models.CharField(max_length=500, choices=(('airtime_autopilot', 'Autopilot'),  ('airtime_ringo', 'Ringo'), ('airtime_atuns', 'ATUNS WEB'), ('airtime_vtpass', 'VTpass'), ('airtime_merrybills', 'Merrybills'), ('airtime_ogdams', 'Ogdams')), null=True)
    glo = models.CharField(max_length=500, choices=(('airtime_autopilot', 'Autopilot'),  ('airtime_ringo', 'Ringo'), ('airtime_atuns', 'ATUNS WEB'), ('airtime_vtpass', 'VTpass'), ('airtime_merrybills', 'Merrybills'), ('airtime_ogdams', 'Ogdams')), null=True)
    etisalat = models.CharField(max_length=500, choices=(('airtime_autopilot', 'Autopilot'),  ('airtime_ringo', 'Ringo'), ('airtime_atuns', 'ATUNS WEB'), ('airtime_vtpass', 'VTpass'), ('airtime_merrybills', 'Merrybills'), ('airtime_ogdams', 'Ogdams')), null=True)
    
    def __str__(self):
        return 'Airtime switch'

    class Meta:
        verbose_name_plural = 'AIRTIME SWITCH'



class Switch(models.Model):
    mtn_sme = models.CharField(max_length=500, choices=(('manual_mtn', 'Manual'), ('plan_code', 'Plan Vending Medium'), ('atuns_mtn', 'ATUNS WEB'), ('simserverslot_mtn', 'Simserver Web Slot'), ('autopilot_mtn', 'Autopilot'), ('simserver_mtn', 'Simservers'), ('ms_mtn', 'MS WEB'), ('cloudsim_mtn', 'Cloud Sim Hosting'), ('ms2_mtn', 'MS WEB2'), ('simserverslot2_mtn', 'Simserver Web Slot2'),  ('simserverslot3_mtn', 'Simserver Web Slot3'),('smeplug_mtn', 'Smeplug')), null=True)
    mtn_coupon = models.CharField(max_length=500, choices=(('manual_directcoupon', 'Manual'), ('plan_code', 'Plan Vending Medium'),  ('atuns_directcoupon', 'ATUNS WEB'), ('ms_directcoupon', 'MS WEB'),('ms2_directcoupon', 'MS WEB2')), null=True)
    mtn_gifting = models.CharField(max_length=500, choices=(('manual_gifting', 'Manual'), ('plan_code', 'Plan Vending Medium'), ('atuns_gifting', 'ATUNS WEB'), ('simserverslot_gifting', 'Simserver Web Slot'), ('autopilot_gifting', 'Autopilot'), ('ms_gifting', 'MS WEB'), ('cloudsim_gifting', 'Cloud Sim Hosting') ,('ms2_gifting', 'MS WEB2'), ('simserverslot2_gifting', 'Simserver Web Slot2'), ('simserverslot3_gifting', 'Simserver Web Slot3')), null=True)
    mtn_cg_lite = models.CharField(max_length=500, choices=(('manual_giftinglite', 'Manual'), ('plan_code', 'Plan Vending Medium'), ('atuns_giftinglite', 'ATUNS WEB'),('autopilot_giftinglite', 'Autopilot'), ('simserverslot_giftinglite', 'Simserver Web Slot'), ('ms_giftinglite', 'MS WEB'), ('ms2_giftinglite', 'MS WEB2'), ('simserverslot2_giftinglite', 'Simserver Web Slot2'), ('simserverslot3_giftinglite', 'Simserver Web Slot3'),('cloudsim_giftinglite', 'Cloud Sim Hosting')), null=True)
    glo = models.CharField(max_length=500, choices=(('manual_glo', 'Manual'), ('vtpass_glo', 'VTPASS'),  ('imansub_glo', 'IMANSUB'),('atuns_glo', 'ATUNS WEB'), ('plan_code', 'Plan Vending Medium'), ('autopilot_glo', 'Autopilot'), ('ms_glo', 'MS WEB'),('ms2_glo', 'MS WEB2'), ('simserverslot2_glo', 'Simserver Web Slot2'), ('simserverslot3_glo', 'Simserver Web Slot3')), null=True)
    glo_cg = models.CharField(max_length=500, choices=(('manual_glocg', 'Manual'), ('topupaccess_glocg', 'Topupaccess'), ('imansub_glocg', 'IMANSUB'),('plan_code', 'Plan Vending Medium'),  ('atuns_glocg', 'ATUNS WEB'), ('simserverslot_glocg', 'Simserver Web Slot'),('autopilot_glocg', 'Autopilot'), ('ms_glocg', 'MS WEB'),('ms2_glocg', 'MS WEB2'), ('simserverslot2_glocg', 'Simserver Web Slot2'), ('simserverslot3_glocg', 'Simserver Web Slot3')), null=True)
    glo_awoof_gifting = models.CharField(max_length=500, choices=(('manual_gloawoof', 'Manual'),  ('plan_code', 'Plan Vending Medium'), ('atuns_gloawoof', 'ATUNS WEB'),('simserverslot_gloawoof', 'Simserver Web Slot'), ('autopilot_gloawoof', 'Autopilot'), ('ms_gloawoof', 'MS WEB'),('ms2_gloawoof', 'MS WEB2'), ('simserverslot2_gloawoof', 'Simserver Web Slot2'), ('simserverslot3_gloawoof', 'Simserver Web Slot3')), null=True)
    airtel = models.CharField(max_length=500, choices=(('manual_airtel', 'Manual'),('vtpass_airtel', 'VTPASS'),  ('imansub_airtel', 'IMANSUB'),('plan_code', 'Plan Vending Medium'),  ('atuns_airtel', 'ATUNS WEB'), ('autopilot_airtel', 'Autopilot'), ('ms_airtel', 'MS WEB'),('ms2_airtel', 'MS WEB2'), ('simserverslot2_airtel', 'Simserver Web Slot2'), ('simserverslot3_airtel', 'Simserver Web Slot3')), null=True)
    airtel_cg = models.CharField(max_length=500, choices=(('manual_airtelcg', 'Manual'), ('plan_code', 'Plan Vending Medium'),  ('atuns_airtelcg', 'ATUNS WEB'), ('simserverslot_airtelcg', 'Simserver Web Slot'), ('autopilot_airtelcg', 'Autopilot'), ('ms_airtelcg', 'MS WEB'), ('simserver_airtelcg', 'Simservers'),('ms2_airtelcg', 'MS WEB2'), ('simserverslot2_airtelcg', 'Simserver Web Slot2'), ('simserverslot3_airtelcg', 'Simserver Web Slot3')), null=True)
    airtel_awoof = models.CharField(max_length=500, choices=(('manual_airtelawoof', 'Manual'),  ('plan_code', 'Plan Vending Medium'), ('atuns_airtelawoof', 'ATUNS WEB'), ('autopilot_airtelawoof', 'Autopilot'), ('ms_airtelawoof', 'MS WEB'),('ms2_airtelawoof', 'MS WEB2')), null=True)
    mobile = models.CharField(max_length=500, choices=(('manual_mobile', 'Manual'), ('vtpass_mobile', 'VTPASS'),('plan_code', 'Plan Vending Medium'),  ('atuns_mobile', 'ATUNS WEB'), ('autopilot_mobile', 'Autopilot'), ('ms_mobile', 'MS WEB'),('ms2_mobile', 'MS WEB2')), null=True)
    mobile_sme = models.CharField(max_length=500, choices=(('manual_mobilesme', 'Manual'), ('plan_code', 'Plan Vending Medium'), ('atuns_mobilesme', 'ATUNS WEB'),('apisub_mobilesme', 'Apisubportal'),  ('simserverslot_mobilesme', 'Simserver Web Slot'),('autopilot_mobilesme', 'Autopilot'), ('ms_mobilesme', 'MS WEB'),('ms2_mobilesme', 'MS WEB2'), ('simserverslot2_mobilesme', 'Simserver Web Slot2'), ('simserverslot3_mobilesme', 'Simserver Web Slot3')), null=True)
    airtime = models.CharField(max_length=500, choices=(('airtime_autopilot', 'Autopilot'),  ('airtime_atuns', 'ATUNS WEB'), ('airtime_vtpass', 'VTpass'), ('airtime_merrybills', 'Merrybills'), ('airtime_ogdams', 'Ogdams')), null=True)
    dstv = models.CharField(max_length=500, choices=( ('dstv_ringo', 'Ringo'), ('dstv_vtpass', 'VTpass'), ('dstv_autopilot', 'Autopilot'), ('dstv_merrybills', 'Merrybills')), null=True)
    gotv = models.CharField(max_length=500, choices=(('gotv_ringo', 'Ringo'),('gotv_vtpass', 'VTpass'), ('gotv_autopilot', 'Autopilot'), ('gotv_merrybills', 'Merrybills')), null=True)
    startimes = models.CharField(max_length=500, choices=(('startimes_ringo', 'Ringo'),('startimes_vtpass', 'VTpass'), ('startimes_merrybills', 'Merrybills')), null=True)
    electricity = models.CharField(max_length=500, choices=(('electricity_ringo', 'Ringo'), ('electricity_vtpass', 'VTpass'), ('electricity_merrybills', 'Merrybills'), ('electricity_buypower', 'Buypower')), null=True)
    result = models.CharField(max_length=500, choices=(('result_ringo', 'Ringo'), ('result_vtpass', 'VTpass'), ('result_imansub', 'Imansub'), ('result_manual', 'Manual')), null=True)
    mtn_datashare = models.CharField(max_length=500, choices=(('autopilot_sme1', 'Autopilot'), ('gongoz_sme1', 'Gongoz'), ('topupaccess_sme1', 'Topupaccess'), ('imansub_sme1', 'IMANSUB'),('smeplug_sme1', 'Smeplug'),  ('plan_code', 'Plan Vending Medium'), ('atuns_sme1', 'ATUNS WEB'),  ('simserverslot_sme1', 'Simserver Web Slot'), ('ms_sme1', 'MS WEB'), ('ms2_sme1', 'MS WEB2'), ('simserverslot2_sme1', 'Simserver Web Slot2'), ('simserverslot3_sme1', 'Simserver Web Slot3') ,('manual_sme1', 'Manual')), null=True)
    mtn_datashare_fallback = models.CharField(
        max_length=500,
        choices=(
            ('autopilot_sme1', 'Autopilot'),
            ('gongoz_sme1', 'Gongoz'),
            ('topupaccess_sme1', 'Topupaccess'),
            ('imansub_sme1', 'IMANSUB'),
            ('atuns_sme1', 'ATUNS WEB'),
            ('ms_sme1', 'MS WEB'),
            ('ms2_sme1', 'MS WEB2'),
        ),
        null=True,
        blank=True
    )
    mtn_directgifting = models.CharField(max_length=500, choices=(('manual_directgifting', 'Manual'),('vtpass_directgifting', 'VTPASS'), ('imansub_directgifting', 'IMANSUB'), ('plan_code', 'Plan Vending Medium'), ('atuns_directgifting', 'ATUNS WEB'), ('autopilot_directgifting', 'Autopilot'), ('ms_directgifting', 'MS WEB'), ('ms2_directgifting', 'MS WEB2'), ('simserverslot2_directgifting', 'Simserver Web Slot2'),  ('simserverslot3_directgifting', 'Simserver Web Slot3')), null=True)
    mtn_awoofgifting = models.CharField(max_length=500, choices=(('manual_awoofgifting', 'Manual'), ('plan_code', 'Plan Vending Medium'), ('atuns_awoofgifting', 'ATUNS WEB'), ('autopilot_awoofgifting', 'Autopilot'), ('ms_awoofgifting', 'MS WEB'),('ms2_awoofgifting', 'MS WEB2')), null=True)
    recharge_card_printing = models.CharField(max_length=500, choices=(('recharge_manual', 'Manual'),), null=True)
    
    airtel_talkmore = models.CharField(max_length=500, choices=(('manual_airtelawoof', 'Manual'), ('plan_code', 'Plan Vending Medium'),  ('atuns_airtelawoof', 'ATUNS WEB'),('pluginng_airteltalkmore', 'PlugingNG'),('ms_airtelawoof', 'MS WEB'), ('ms2_airtelawoof', 'MS WEB 2'),('ms3_airtelawoof', 'MS WEB 3')), null=True)
    glo_talkmore = models.CharField(max_length=500, choices=(('manual_airtelawoof', 'Manual'), ('plan_code', 'Plan Vending Medium'),  ('atuns_airtelawoof', 'ATUNS WEB'),('pluginng_glotalkmore', 'PlugingNG'), ('ms_airtelawoof', 'MS WEB'), ('ms2_airtelawoof', 'MS WEB 2'),('ms3_airtelawoof', 'MS WEB 3')), null=True)
    mtn_talkmore = models.CharField(max_length=500, choices=(('manual_airtelawoof', 'Manual'), ('plan_code', 'Plan Vending Medium'),  ('atuns_airtelawoof', 'ATUNS WEB'),('pluginng_mtntalkmore', 'PlugingNG'),('autosync_mtntalkmore', 'AutosyncNG'),('ms_airtelawoof', 'MS WEB'), ('ms2_airtelawoof', 'MS WEB 2'),('ms3_airtelawoof', 'MS WEB 3')), null=True)

    def __str__(self):
        return 'Service switch'

    class Meta:
        verbose_name_plural = 'SERVICES SWITCH'


class Bonus(models.Model):
    email = models.CharField(max_length=500, null=True)
    referer = models.CharField(max_length=500, null=True)
    paid = models.BooleanField(default=False)

    def __str__(self):
        return self.email

    class Meta:
        verbose_name_plural = 'BONUS'


class ResultPin(models.Model):
    exam_type = models.CharField(max_length=500, null=True)
    price = models.IntegerField(null=True)
    api = models.IntegerField(null=True)

    def __str__(self):
        return self.exam_type

    class Meta:
        verbose_name_plural = 'EXAM PIN'



class PayRef(models.Model):
    user = models.ForeignKey(AppUser, on_delete=models.CASCADE, editable=False, blank=False, null=True,
                             related_name='payref')
    reference = models.CharField(max_length=500, null=True)

    def __str__(self):
        return self.reference

    class Meta:
        verbose_name_plural = 'PAYMENT REF'
        


class Fund_User(models.Model):
    username = models.CharField(max_length=100, null=True)
    amount = models.IntegerField(default=0)
    balance_before = models.CharField(max_length=500, null=True, blank=True, help_text="leave blank sytem sets this automatically")
    balance_after = models.CharField(max_length=500, null=True, blank=True, help_text="leave blank sytem sets this automatically")

    def __str__(self):
        return str(self.username)

    def clean(self):
        try:
            mb = AppUser.objects.get(username=self.username)
        except:
            raise ValidationError(f'Invalid user, enter correct username')

    def save(self, *args, **kwargs):

        mb = AppUser.objects.get(username=self.username)

        self.balance_before = mb.balance
        new = mb.balance + self.amount
        mb.fund(mb.id, self.amount)
        self.balance_after = new

        date_time = zone.localize(datetime.now())
        
        Wallet_summary.objects.create(user= mb, product="Admun Wallet Funding", amount = self.amount, previous_balance = self.balance_before, after_balance= new)
        
        Transact.objects.create(
            email=mb.email,
            user=mb,
            transaction="ADMIN WALLET FUNDING",
            status="Successful",
            cost=self.amount,
            old_balance=self.balance_before,
            new_balance=new,
            phone_number='None',
            d_network='ManualFunding',
            value = "WALLET FUNDING")
            
        Sale.objects.create(
            user=mb,
            network='Manual Funding',
            plan="Wallet Funding",
            status="Successful",
            cost=self.amount,
            date=date_time.strftime("%Y-%m-%d"),
            )
        
        try:
            from .services.notifications import send_wallet_funding_notification

            send_wallet_funding_notification(
                mb,
                self.amount,
                new,
                "Manual/Admin"
            )
        except:
            pass
        super(Fund_User, self).save(*args, **kwargs)

    class Meta:
        verbose_name_plural = 'FUND USER WALLET'


class Debit_User(models.Model):
    username = models.CharField(max_length=100, null=True)
    amount = models.IntegerField(default=0)
    balance_before = models.CharField(max_length=500, null=True, blank=True, help_text="leave blank sytem sets this automatically")
    balance_after = models.CharField(max_length=500, null=True, blank=True, help_text="leave blank sytem sets this automatically")

    def __str__(self):
        return str(self.username)

    def clean(self):
        try:
            mb = AppUser.objects.get(username=self.username)
        except:
            raise ValidationError(f'Invalid user, enter correct username')

    def save(self, *args, **kwargs):

        mb = AppUser.objects.get(username=self.username)

        self.balance_before = mb.balance
        new = mb.balance - self.amount
        mb.debit(mb.id, self.amount)
        self.balance_after = new
        date_time = zone.localize(datetime.now())
        
        Wallet_summary.objects.create(user= mb, product="Admun Wallet Debit", amount = self.amount, previous_balance = self.balance_before, after_balance= new)
        
        Transact.objects.create(
                email=mb.email,
                user=mb,
                transaction="ADMIN WALLET DEBIT",
                status="Successful",
                cost=str(self.amount),
                old_balance=self.balance_before,
                new_balance=new,
                phone_number='None',
                d_network='Debited',
                value = "WALLET DEEBITING"
                )

        super(Debit_User, self).save(*args, **kwargs)

    class Meta:
        verbose_name_plural = 'DEBIT USER WALLET'


class Blacklist(models.Model):
    number = models.CharField(max_length=500, null=True)

    def __str__(self):
        return self.number

    class Meta:
        verbose_name_plural = 'BLACK LIST NUMBERS'


class Fund_Bucket(models.Model):
    username = models.CharField(max_length=100, null=True)
    bucket_type = models.CharField(max_length=500, choices=(('mtn_sme', 'mtn_sme'), ('mtn_cg', 'mtn_cg'), ('glo_cg', 'glo_cg'), ('airtel_cg', 'airtel_cg'), ('mobile_cg', 'mobile_cg')), null=True)
    amount = models.FloatField(default=0.0, help_text="Enter number of GB")
    balance_before = models.CharField(max_length=500, null=True, blank=True,
                                      help_text="leave blank sytem sets this automatically")
    balance_after = models.CharField(max_length=500, null=True, blank=True,
                                     help_text="leave blank sytem sets this automatically")

    def __str__(self):
        return str(self.username)

    def clean(self):
        try:
            mb = AppUser.objects.get(username=self.username)
        except:
            raise ValidationError(f'Invalid user, enter correct username')

    def save(self, *args, **kwargs):

        mb = AppUser.objects.get(username=self.username)
        if self.bucket_type == 'mtn_sme':
            self.balance_before = mb.mtn_sme
            new = mb.mtn_sme + self.amount
            mb.fundmtnsme(mb.id,self.amount)
            self.balance_after = new

        elif self.bucket_type == 'mtn_cg':
            self.balance_before = mb.mtn_cg
            new = mb.mtn_cg + self.amount
            mb.fundmtncg(mb.id,self.amount)
            self.balance_after = new

        elif self.bucket_type == 'glo_cg':
            self.balance_before = mb.glo_cg
            new = mb.glo_cg + self.amount
            mb.fundglocg(mb.id,self.amount)
            self.balance_after = new

        elif self.bucket_type == 'airtel_cg':
            self.balance_before = mb.airtel_cg
            new = mb.airtel_cg + self.amount
            mb.fundairtelcg(mb.id,self.amount)
            self.balance_after = new

        elif self.bucket_type == 'mobile_cg':
            self.balance_before = mb.mobile_cg
            new = mb.mobile_cg + self.amount
            mb.fundmobilecg(mb.id,self.amount)
            self.balance_after = new

        date_time = zone.localize(datetime.now())
        Transact.objects.create(
            email=mb.email,
            user=mb,
            transaction="ADMIN BUCKET FUNDING",
            status="Successful",
            cost=self.amount,
            old_balance=self.balance_before,
            new_balance=new,
            phone_number='None',
            d_network='Admin Funding',
            value = "WALLET FUNDING")

        # mailer(mb.email, 'Wallet Funding Notification',
        #       f'Dear {mb.username}, your Atunsdata {self.bucket_type} bucket has been credited with {self.amount}, your new balance is {new}.')

        super(Fund_Bucket, self).save(*args, **kwargs)

    class Meta:
        verbose_name_plural = 'FUND USER BUCKET'


class Debit_Bucket(models.Model):
    username = models.CharField(max_length=100, null=True)
    bucket_type = models.CharField(max_length=500, choices=(
    ('mtn_sme', 'mtn_sme'), ('mtn_cg', 'mtn_cg'), ('glo_cg', 'glo_cg'), ('airtel_cg', 'airtel_cg'),
    ('mobile_cg', 'mobile_cg')), null=True)
    amount = models.FloatField(default=0.0, help_text="Enter number of GB")
    balance_before = models.CharField(max_length=500, null=True, blank=True,
                                      help_text="leave blank sytem sets this automatically")
    balance_after = models.CharField(max_length=500, null=True, blank=True,
                                     help_text="leave blank sytem sets this automatically")

    def __str__(self):
        return str(self.username)

    def clean(self):
        try:
            mb = AppUser.objects.get(username=self.username)
        except:
            raise ValidationError(f'Invalid user, enter correct username')

    def save(self, *args, **kwargs):

        mb = AppUser.objects.get(username=self.username)
        if self.bucket_type == 'mtn_sme':
            self.balance_before = mb.mtn_sme
            new = mb.mtn_sme - self.amount
            mb.debitmtnsme(mb.id,self.amount)
            self.balance_after = new

        elif self.bucket_type == 'mtn_cg':
            self.balance_before = mb.mtn_cg
            new = mb.mtn_cg - self.amount
            mb.debitmtncg(mb.id,self.amount)
            self.balance_after = new

        elif self.bucket_type == 'glo_cg':
            self.balance_before = mb.glo_cg
            new = mb.glo_cg - self.amount
            mb.debitglocg(mb.id,self.amount)
            self.balance_after = new

        elif self.bucket_type == 'airtel_cg':
            self.balance_before = mb.airtel_cg
            new = mb.airtel_cg - self.amount
            mb.debitairtelcg(mb.id,self.amount)
            self.balance_after = new

        elif self.bucket_type == 'mobile_cg':
            self.balance_before = mb.mobile_cg
            new = mb.mobile_cg - self.amount
            mb.debitmobilecg(mb.id,self.amount)
            self.balance_after = new

        date_time = zone.localize(datetime.now())
        
        Transact.objects.create(
            email=mb.email,
            user=mb,
            transaction="ADMIN BUCKET DEBIT",
            status="Successful",
            cost=self.amount,
            old_balance=self.balance_before,
            new_balance=new,
            phone_number='None',
            d_network='Debit',
            value = "WALLET DEBITING"
        )

        super(Debit_Bucket, self).save(*args, **kwargs)

    class Meta:
        verbose_name_plural = 'DEBIT USER BUCKET'


class Mtnsmebucket(models.Model):
    volume = models.IntegerField(null=True)
    amount = models.IntegerField(null=True)

    def __str__(self):
        return (str(self.volume) + " GB")

    class Meta:
        verbose_name_plural = 'MTN SME BUCKET'


class Mtncgbucket(models.Model):
    volume = models.IntegerField(null=True)
    amount = models.IntegerField(null=True)

    def __str__(self):
        return (str(self.volume) + " GB")

    class Meta:
        verbose_name_plural = 'MTN CG BUCKET'


class Glocgbucket(models.Model):
    volume = models.IntegerField(null=True)
    amount = models.IntegerField(null=True)

    def __str__(self):
        return (str(self.volume) + " GB")

    class Meta:
        verbose_name_plural = 'GLO CG BUCKET'


class Airtelcgbucket(models.Model):
    volume = models.IntegerField(null=True)
    amount = models.IntegerField(null=True)

    def __str__(self):
        return (str(self.volume) + " GB")

    class Meta:
        verbose_name_plural = 'AIRTEL CG BUCKET'


class Mobilecgbucket(models.Model):
    volume = models.IntegerField(null=True)
    amount = models.IntegerField(null=True)

    def __str__(self):
        return (str(self.volume) + " GB")

    class Meta:
        verbose_name_plural = '9MOBILE CG BUCKET'


class PaymentGatewayDisable(models.Model):
    monnify = models.CharField(max_length=500, choices=(('ENABLE', 'ENABLE'), ('DISABLE', 'DISABLE')), null=True)
    securewave = models.CharField(max_length=500, choices=(('ENABLE', 'ENABLE'), ('DISABLE', 'DISABLE')), null=True)
    palmpay = models.CharField(max_length=500, choices=(('ENABLE', 'ENABLE'), ('DISABLE', 'DISABLE')), null=True)
    payvessel = models.CharField(max_length=500, choices=(('ENABLE', 'ENABLE'), ('DISABLE', 'DISABLE')), null=True)
    paymentpoint = models.CharField(max_length=500, choices=(('ENABLE', 'ENABLE'), ('DISABLE', 'DISABLE')), null=True)

    def __str__(self):
        return 'Gateway disable'

    class Meta:
        verbose_name_plural = 'PAYMENT GATEWAY DISABLE'



class Lockbucket(models.Model):
    mtn_sme = models.CharField(max_length=500, choices=(('ENABLE', 'ENABLE'), ('DISABLE', 'DISABLE')), null=True)
    mtn_cg = models.CharField(max_length=500, choices=(('ENABLE', 'ENABLE'), ('DISABLE', 'DISABLE')), null=True)
    glo_cg = models.CharField(max_length=500, choices=(('ENABLE', 'ENABLE'), ('DISABLE', 'DISABLE')), null=True)
    airtel_cg = models.CharField(max_length=500, choices=(('ENABLE', 'ENABLE'), ('DISABLE', 'DISABLE')), null=True)
    mobile_cg = models.CharField(max_length=500, choices=(('ENABLE', 'ENABLE'), ('DISABLE', 'DISABLE')), null=True)

    def __str__(self):
        return 'Bucket lock'

    class Meta:
        verbose_name_plural = 'BUCKET DATA LOCK'

class BucketTransact(models.Model):
    user = models.ForeignKey(AppUser, on_delete=models.CASCADE, editable=False, blank=False, null=True)
    transaction = models.CharField(max_length=500, null=True)
    email = models.CharField(max_length=500, null=True)
    status = models.CharField(max_length=500, null=True)
    cost = models.CharField(max_length=500, null=True)
    date = models.CharField(max_length=500, null=True, default=getdate)
    old_balance = models.FloatField(max_length=500, null=True)
    new_balance = models.FloatField(max_length=500, null=True)
    phone_number = models.CharField(max_length=500, null=True)
    d_network = models.CharField(max_length=500, null=True)
    request_id = models.CharField(max_length=500, null=True, default=request_id_gen)

    def __str__(self):
        return self.status

    class Meta:
        verbose_name_plural = 'BUCKET TRANSACTIONS'
        
        

# NEW UPDATES_________

from django.db import models, transaction


class Load_exam_pin(models.Model):

    exam = models.CharField(
        max_length=30,
        choices=(
            ('WAEC', 'WAEC'),
            ('NECO', 'NECO')
        ),
        default='WAEC'
    )

    dump_pin = models.TextField()

    total_pin_loaded = models.CharField(
        max_length=100,
        null=True,
        blank=True,
        help_text="Leave blank, system automatically returns it"
    )

    def save(self, *args, **kwargs):

        # ---------------------------------------------------------
        # CLEAN PIN INPUT
        # ---------------------------------------------------------

        data = [
            pin.strip()
            for pin in self.dump_pin.splitlines()
            if pin.strip()
        ]

        self.total_pin_loaded = len(data)

        # ---------------------------------------------------------
        # ONLY LOAD PINS WHEN THIS IS A NEW LOAD RECORD
        # ---------------------------------------------------------

        is_new = self.pk is None

        # ---------------------------------------------------------
        # SAVE EVERYTHING ATOMICALLY
        # ---------------------------------------------------------

        with transaction.atomic():

            # Save the Load_exam_pin record first
            super().save(*args, **kwargs)

            if not is_new:
                return

            # -----------------------------------------------------
            # FIND THE HIGHEST NUMERIC SERIAL
            # -----------------------------------------------------

            last_id = 0

            existing_serials = (
                exam_pin.objects
                .values_list('serial', flat=True)
            )

            for serial in existing_serials:

                try:
                    serial_number = int(str(serial).strip())

                    if serial_number > last_id:
                        last_id = serial_number

                except (TypeError, ValueError):
                    # Ignore values such as:
                    # "Nil"
                    # ""
                    # None
                    continue

            # -----------------------------------------------------
            # CREATE NEW EXAM PINS
            # -----------------------------------------------------

            for pin in data:

                last_id += 1

                exam_pin.objects.create(
                    pin=pin,
                    exam=self.exam,
                    serial=last_id
                )

    def __str__(self):

        return " set " + str(self.id)

    class Meta:

        verbose_name_plural = 'LOAD EXAM PIN'


class exam_pin(models.Model):
    exam = models.CharField(max_length=30, choices=(('WAEC', 'WAEC'), ('NECO', 'NECO')), default='WAEC')
    available = models.BooleanField(default=True)
    pin = models.CharField(max_length=100, unique=True, null=True)
    serial = models.CharField(max_length=100, unique=True, null=True)

    def __str__(self):
        return str(self.exam) + "  " + str(self.pin) + "  " + str(self.serial)

    class Meta:
        verbose_name_plural = "EXAM PINS GENERATED"


class Load_Recharge_pin(models.Model):
    network = models.CharField(max_length=30, choices=(('MTN', 'MTN'), ('AIRTEL', 'AIRTEL'), ('GLO', 'GLO'), ('ETISALAT', 'ETISALAT')), default='MTN')
    dump_pin = models.TextField()
    amount = models.FloatField(default=0)
    load_code = models.CharField(max_length=100, null=True)
    total_pin_loaded = models.CharField(
        max_length=100, null=True, blank=True, help_text="Leave blank, system automatic return it")

    def save(self, *args, **kwargs):
        data = self.dump_pin.split("\n")
        self.total_pin_loaded = len(data)
        if Recharge_pin.objects.all():
            last_id = int(Recharge_pin.objects.all().last().serial)
        else:
            last_id = 0

        for x in data:
            last_id += 1
            Recharge_pin.objects.create(
                pin=x, network=self.network, amount=self.amount, serial=last_id, load_code=self.load_code)
        super(Load_Recharge_pin, self).save(*args, **kwargs)

    def __str__(self):
        return " set  " + str(self.id)

    class Meta:
        verbose_name_plural = 'LOAD RECHARGE PIN'

class Recharge_pin(models.Model):

    network = models.CharField(max_length=30, choices=(('MTN', 'MTN'), ('AIRTEL', 'AIRTEL'), ('GLO', 'GLO'), ('ETISALAT', 'ETISALAT')), default='MTN')
    available = models.BooleanField(default=True)
    amount = models.FloatField(default=100)
    pin = models.CharField(max_length=20, unique=False, null=True)
    serial = models.CharField(max_length=100, unique=False, null=True)
    load_code = models.CharField(max_length=100, null=True)

    def __str__(self):
        return str(self.network) + "  " + str(self.pin) + "  " + str(self.serial)
        
    class Meta:
        verbose_name_plural = "RECHARGE PINS GENERATED"
        
        

class Wallet_summary(models.Model):
    user = models.ForeignKey(AppUser, on_delete=models.CASCADE, editable=False, blank=False, null=True, related_name='wallet')
    product = models.CharField(max_length=500, blank=True)
    amount = models.CharField(max_length=30, blank=True)
    previous_balance = models.CharField(max_length=30, blank=True)
    after_balance = models.CharField(max_length=30, blank=True, null=True)
    status = models.CharField(max_length=30, choices=(('Successful', 'Successful'), ('Unsuccessful', 'Unsuccessful'), ('Pending', 'Pending')), default='Successful')
    date = models.CharField(max_length=500, null=True, default=getdate)
    request_id = models.CharField(max_length=500, null=True, default=request_id_gen)
    
    def __str__(self):
        return str(self.user.username)

    class Meta:
        verbose_name_plural = "WALLET SUMMARY"
        
# WHATSAPP BOT TABLES

class Whatsapptransactions(models.Model):
    user = models.ForeignKey(AppUser, on_delete=models.CASCADE, editable=False, blank=False, null=True, related_name='whatsapp')
    service = models.CharField(max_length=500, blank=True,null=True)
    network = models.CharField(max_length=500, blank=True,null=True)
    datatype = models.CharField(max_length=500, blank=True,null=True)
    volume = models.CharField(max_length=500, blank=True, null=True)
    amount = models.CharField(max_length=500, blank=True, null=True)
    phone = models.CharField(max_length=500, blank=True, null=True)
    date_initiated = models.CharField(max_length=500, null=True, default=getdate)
    step = models.IntegerField(null=True,blank=True)
    last_message = models.CharField(max_length=500, blank=True, null=True)
    completed = models.BooleanField(default=False)
    
    def __str__(self):
        return str(self.user.username)

    class Meta:
        verbose_name_plural = "WHATSAPP TRANSACTIONS"
        

       
        
class Whatsappchatsteps(models.Model):
    user = models.ForeignKey(AppUser, on_delete=models.CASCADE, editable=False, blank=False, null=True, related_name='chatsteps')
    service = models.CharField(max_length=500, blank=True,null=True)
    step_1 = models.CharField(max_length=500, blank=True,null=True)
    step_2 = models.CharField(max_length=500, blank=True,null=True)
    step_3 = models.CharField(max_length=500, blank=True, null=True)
    step_4 = models.CharField(max_length=500, blank=True, null=True)
    step_5 = models.CharField(max_length=500, blank=True, null=True)
    completed = models.BooleanField(default=False)
    def __str__(self):
        return str(self.user.username)

    class Meta:
        verbose_name_plural = "WHATSAPP CHAT STEPS"




class Whatsappmessages(models.Model):
    unregistered_user_message = models.TextField(blank=True,null=True)
    set_trans_pin_message = models.TextField(blank=True,null=True)
    greetings_message = models.TextField(blank=True,null=True)
    invalid_response_message = models.TextField(blank=True,null=True)
    exit_message = models.TextField(blank=True,null=True)
    def __str__(self):
        return str("Whatsapp messages")

    class Meta:
        verbose_name_plural = "WHATSAPP CHAT STEPS"




class WhatsAppUser(models.Model):
    username = models.CharField(max_length=500, null=False)
    phoneNumber = models.CharField(max_length=500, null=False)
    email = models.EmailField(null=True,blank=True)
    balance = models.FloatField(max_length=500, default=0.0, validators=[MinValueValidator(0.0)],)
    bonus = models.FloatField(max_length=500, default=0.0, validators=[MinValueValidator(0.0)],)
    palmpay_account = models.TextField(blank=True, null=True)
    order_id = models.CharField(max_length=200, null=True, blank=True)
    refcode = models.CharField(max_length=200, null=True, blank=True)
    referer = models.CharField(max_length=200, null=True, blank=True)
    first_fund = models.BooleanField(default=False)


    @classmethod
    def debit(cls, id, amount):
        with transaction.atomic():
            account = (cls.objects.select_for_update().get(id=id))
            
            # balance_before = account.balance
            if account.balance < amount or amount < 0:
                return False
            account.balance -= amount
            account.balance = round(account.balance, 2)
            account.save()
        
            
            
    @classmethod
    def fund(cls, id, amount):
        with transaction.atomic():
            account = (cls.objects.select_for_update().get(id=id))
            account.balance += amount
            account.balance = round(account.balance, 2)
            account.save()
            
    @classmethod
    def fundbonus(cls, id, amount):
        with transaction.atomic():
            account = (cls.objects.select_for_update().get(id=id))
            account.bonus += amount
            account.bonus = round(account.bonus, 2)
            account.save()
            
    

    def __str__(self):
        return self.username

    class Meta:
        verbose_name_plural = 'WHATSAPP USERS MANAGEMENT'



class Whatsapptransactionsguest(models.Model):
    user = models.ForeignKey(WhatsAppUser, on_delete=models.CASCADE, editable=False, blank=False, null=True, related_name='whatsapp')
    service = models.CharField(max_length=500, blank=True,null=True)
    network = models.CharField(max_length=500, blank=True,null=True)
    datatype = models.CharField(max_length=500, blank=True,null=True)
    volume = models.CharField(max_length=500, blank=True, null=True)
    amount = models.CharField(max_length=500, blank=True, null=True)
    phone = models.CharField(max_length=500, blank=True, null=True)
    date_initiated = models.CharField(max_length=500, null=True, default=getdate)
    step = models.IntegerField(null=True,blank=True)
    last_message = models.CharField(max_length=500, blank=True, null=True)
    completed = models.BooleanField(default=False)
    
    def __str__(self):
        return str(self.user.username)

    class Meta:
        verbose_name_plural = "WHATSAPP TRANSACTIONS STEPS FOR GUESTS"
        
        
        
class Whatsappchatstepsguest(models.Model):
    user = models.ForeignKey(WhatsAppUser, on_delete=models.CASCADE, editable=False, blank=False, null=True, related_name='chatsteps')
    service = models.CharField(max_length=500, blank=True,null=True)
    step_1 = models.CharField(max_length=500, blank=True,null=True)
    step_2 = models.CharField(max_length=500, blank=True,null=True)
    step_3 = models.CharField(max_length=500, blank=True, null=True)
    step_4 = models.CharField(max_length=500, blank=True, null=True)
    step_5 = models.CharField(max_length=500, blank=True, null=True)
    completed = models.BooleanField(default=False)
    def __str__(self):
        return str(self.user.username)

    class Meta:
        verbose_name_plural = "WHATSAPP CHAT STEPS FOR GUESTS"



class DynamicPayRef(models.Model):
    user = models.ForeignKey(WhatsAppUser, on_delete=models.CASCADE, editable=False, blank=False, null=True,
                             related_name='whatsapp_payref')
    reference = models.CharField(max_length=500, null=True)

    def __str__(self):
        return self.reference

    class Meta:
        verbose_name_plural = 'WHATSAPP PAYMENT REF'



class Guest_Wallet_summary(models.Model):
    user = models.ForeignKey(WhatsAppUser, on_delete=models.CASCADE, editable=False, blank=False, null=True,
                             related_name='whatsapp_summary')
    product = models.CharField(max_length=500, blank=True)
    amount = models.CharField(max_length=30, blank=True)
    previous_balance = models.CharField(max_length=30, blank=True)
    after_balance = models.CharField(max_length=30, blank=True, null=True)
    status = models.CharField(max_length=30, choices=(('Successful', 'Successful'), ('Unsuccessful', 'Unsuccessful'), ('Pending', 'Pending')), default='Successful')
    date = models.CharField(max_length=500, null=True, default=getdate)
    request_id = models.CharField(max_length=500, null=True, default=request_id_gen)
    
    def __str__(self):
        return str(self.user.username)

    class Meta:
        verbose_name_plural = "WHATSAPP USERS WALLET SUMMARY"




class Airteltalkmore(models.Model):
    vending_medium = models.CharField(max_length=500, choices=(('manual_airtelawoof', 'Manual'),  ('atuns_airtelawoof', 'ATUNS WEB'),('apisub_airtelawoof', 'Apisubportal'),('pluginng_airteltalkmore', 'PlugingNG'), ('autopilot_airtelawoof', 'Autopilot'), ('ms_airtelawoof', 'MS WEB'), ('ms2_airtelawoof', 'MS WEB 2'),('ms3_airtelawoof', 'MS WEB 3')), null=True)
    volume = models.CharField(max_length=500, null=True)
    amount = models.IntegerField(null=True)
    amount2 = models.IntegerField(null=True)
    amount3 = models.IntegerField(null=True)
    api1 = models.FloatField(null=True)
    api2 = models.FloatField(null=True)
    api3 = models.FloatField(null=True)
    plan_id = models.CharField(max_length=500, null=True, blank=True,help_text="leave blank sytem sets this automatically")
    Atuns_web_id = models.CharField(max_length=500, null=True, blank=True)
    ms_id = models.CharField(max_length=500, null=True, blank=True)
    ms_id_2 = models.CharField(max_length=500, null=True, blank=True)
    ms_id_3 = models.CharField(max_length=500, null=True, blank=True)
    autopilot_id = models.CharField(max_length=500, null=True, blank=True)
    apisubportal_plan_id = models.CharField(max_length=500, null=True, blank=True)
    pluginng_plan_id = models.CharField(max_length=500, null=True, blank=True)
    quicksim_plan_id = models.CharField(max_length=500, null=True, blank=True)
    validity = models.CharField(max_length=500, null=True, blank=True)

    def __str__(self):
        return self.volume
        
    def save(self, *args, **kwargs):
        self.plan_id = self.volume + '_AIRTEL-TALKMORE'
        
        super(Airteltalkmore, self).save(*args, **kwargs)

    class Meta:
        verbose_name_plural = 'AIRTEL TALKMORE AIRTIME'        


class Glotalkmore(models.Model):
    vending_medium = models.CharField(max_length=500, choices=(('manual_airtelawoof', 'Manual'),  ('atuns_airtelawoof', 'ATUNS WEB'),('apisub_airtelawoof', 'Apisubportal'),('pluginng_glotalkmore', 'PlugingNG'), ('autopilot_airtelawoof', 'Autopilot'), ('ms_airtelawoof', 'MS WEB'), ('ms2_airtelawoof', 'MS WEB 2'),('ms3_airtelawoof', 'MS WEB 3')), null=True)
    volume = models.CharField(max_length=500, null=True)
    amount = models.IntegerField(null=True)
    amount2 = models.IntegerField(null=True)
    amount3 = models.IntegerField(null=True)
    api1 = models.FloatField(null=True)
    api2 = models.FloatField(null=True)
    api3 = models.FloatField(null=True)
    plan_id = models.CharField(max_length=500, null=True, blank=True,help_text="leave blank sytem sets this automatically")
    Atuns_web_id = models.CharField(max_length=500, null=True, blank=True)
    ms_id = models.CharField(max_length=500, null=True, blank=True)
    ms_id_2 = models.CharField(max_length=500, null=True, blank=True)
    ms_id_3 = models.CharField(max_length=500, null=True, blank=True)
    autopilot_id = models.CharField(max_length=500, null=True, blank=True)
    apisubportal_plan_id = models.CharField(max_length=500, null=True, blank=True)
    pluginng_plan_id = models.CharField(max_length=500, null=True, blank=True)
    quicksim_plan_id = models.CharField(max_length=500, null=True, blank=True)
    validity = models.CharField(max_length=500, null=True, blank=True)

    def __str__(self):
        return self.volume
        
    def save(self, *args, **kwargs):
        self.plan_id = self.volume + '_GLO-TALKMORE'
        
        super(Glotalkmore, self).save(*args, **kwargs)

    class Meta:
        verbose_name_plural = 'GLO TALKMORE AIRTIME'        



class Mtntalkmore(models.Model):
    vending_medium = models.CharField(max_length=500, choices=(('manual_airtelawoof', 'Manual'),  ('atuns_airtelawoof', 'ATUNS WEB'),('apisub_airtelawoof', 'Apisubportal'),('pluginng_mtntalkmore', 'PlugingNG'),('autosync_mtntalkmore', 'AutosyncNG'), ('autopilot_airtelawoof', 'Autopilot'), ('ms_airtelawoof', 'MS WEB'), ('ms2_airtelawoof', 'MS WEB 2'),('ms3_airtelawoof', 'MS WEB 3')), null=True)
    volume = models.CharField(max_length=500, null=True)
    amount = models.IntegerField(null=True)
    amount2 = models.IntegerField(null=True)
    amount3 = models.IntegerField(null=True)
    api1 = models.FloatField(null=True)
    api2 = models.FloatField(null=True)
    api3 = models.FloatField(null=True)
    plan_id = models.CharField(max_length=500, null=True, blank=True,help_text="leave blank sytem sets this automatically")
    Atuns_web_id = models.CharField(max_length=500, null=True, blank=True)
    ms_id = models.CharField(max_length=500, null=True, blank=True)
    ms_id_2 = models.CharField(max_length=500, null=True, blank=True)
    ms_id_3 = models.CharField(max_length=500, null=True, blank=True)
    autopilot_id = models.CharField(max_length=500, null=True, blank=True)
    apisubportal_plan_id = models.CharField(max_length=500, null=True, blank=True)
    pluginng_plan_id = models.CharField(max_length=500, null=True, blank=True)
    autosync_plan_id = models.CharField(max_length=500, null=True, blank=True)
    quicksim_plan_id = models.CharField(max_length=500, null=True, blank=True)
    validity = models.CharField(max_length=500, null=True, blank=True)

    def __str__(self):
        return self.volume
        
    def save(self, *args, **kwargs):
        self.plan_id = self.volume + '_MTN-TALKMORE'
        
        super(Mtntalkmore, self).save(*args, **kwargs)

    class Meta:
        verbose_name_plural = 'MTN TALKMORE AIRTIME'        



class WhatsAppBroadcast(models.Model):
    body = models.TextField(null=True, blank=True)
    
    def save(self, *args, **kwargs):
        super(WhatsAppBroadcast, self).save(*args, **kwargs)

    class Meta:
        verbose_name_plural = 'WHATSAPP BROADCAST'



class WhatsAppBroadcastGuest(models.Model):
    body = models.TextField(null=True, blank=True)
    
    def save(self, *args, **kwargs):
        super(WhatsAppBroadcastGuest, self).save(*args, **kwargs)

    class Meta:
        verbose_name_plural = 'WHATSAPP GUEST BROADCAST'
        

@receiver(post_save, sender=WhatsAppBroadcast)
def push_broadcast_created_handler(sender, instance, created, *args, **kwargs):
    try:
        users = AppUser.objects.all()
        body = instance.body
        send_notification_to_all_customers(users,body)

    except:
        pass


@receiver(post_save, sender=WhatsAppBroadcastGuest)
def push_broadcastguest_created_handler(sender, instance, created, *args, **kwargs):
    try:
        users = WhatsAppUser.objects.all()
        body = instance.body
        send_notification_to_all_customers(users,body)

    except:
        pass




class Lockbotservices(models.Model):
    service = models.CharField(max_length=500, null=True)
    availability = models.CharField(max_length=500, choices=(('ENABLE', 'ENABLE'), ('DISABLE', 'DISABLE')), null=True)


    def __str__(self):
        return self.service

    class Meta:
        verbose_name_plural = 'BOT SERVICES LOCK'

class Transactbot(models.Model):
    user = models.ForeignKey(WhatsAppUser, on_delete=models.CASCADE, editable=False, blank=False, null=True)
    transaction = models.TextField(null=True)
    # email = models.CharField(max_length=500, null=True)
    status = models.CharField(max_length=500, null=True)
    cost = models.CharField(max_length=500, null=True)
    date = models.CharField(max_length=500, null=True, default=getdate)
    # old_balance = models.FloatField(max_length=500, null=True)
    # new_balance = models.FloatField(max_length=500, null=True)
    phone_number = models.CharField(max_length=500, null=True)
    d_network = models.CharField(max_length=500, null=True)
    request_id = models.CharField(max_length=500, null=True, default=request_id_gen)
    value = models.CharField(max_length=500, null=True, blank=True)

    def __str__(self):
        return self.status

    class Meta:
        verbose_name_plural = 'WHATSAPP USERS TRANSACTIONS'




class Series_vending_medium(models.Model):
    mtn_datashare_medium = models.CharField(max_length=300,null=True,choices=(('autopilot_sme1', 'Autopilot'),('autopilot2_sme1', 'Autopilot_2'),('smeplug_sme1', 'Smeplug'), ('atuns_sme1', 'ATUNS WEB'),  ('simserverslot_sme1', 'Simserver Web Slot'), ('ms_sme1', 'MS WEB'), ('ms2_sme1', 'MS WEB2'), ('simserverslot2_sme1', 'Simserver Web Slot2'), ('simserverslot3_sme1', 'Simserver Web Slot3'),('gongoz_sme1', 'Gongoz'),('unaysenet_sme1', 'Unaysenet'),('sirpdata_sme1', 'Sirpdata'),('alkam_sme1', 'Alkamhub'),('mvtelecoms_sme1', 'MVTELECOMS'),('manual_sme1', 'Manual')))
    glo_cg_medium = models.CharField(max_length=300,null=True,choices=(('manual_glocg', 'Manual'), ('atuns_glocg', 'ATUNS WEB'), ('simserverslot_glocg', 'Simserver Web Slot'),('autopilot_glocg', 'Autopilot'), ('ms_glocg', 'MS WEB'),('ms2_glocg', 'MS WEB2'),('simserverslot2_glocg', 'Simserver Web Slot2'), ('simserverslot3_glocg', 'Simserver Web Slot3')))

    def _str_(self):
        return self.mtn_datashare_medium
        
    class Meta:
        verbose_name_plural = 'APIs SERIES VENDING'



class VendorCounter(models.Model):
    name = models.CharField(max_length=50, null=True)
    value = models.PositiveIntegerField(default=0)

    def _str_(self):
        return f"{self.name}: {self.value}"
        



class PushNotification(models.Model):
    user = models.ForeignKey(AppUser, on_delete=models.CASCADE,
                             editable=False, blank=False, null=True)

    title = models.CharField(max_length=50, blank=True)
    body = models.TextField(null=True, blank=True)
    create_date = models.DateTimeField(default=timezone.now)

    def save(self, *args, **kwargs):
        super(PushNotification, self).save(*args, **kwargs)

    class Meta:
        verbose_name_plural = 'SEND PUSH NOTIFICATION'

@receiver(post_save, sender=PushNotification)
def push_notification_created_handler(sender, instance, created, *args, **kwargs):
    try:
        title = instance.title
        body = instance.body
        # print('we pushed it')
        # logging.info(f'PushNotification: title => {title} body  => {body}')
        send_notification_to_all_customers_firebase(title, body)

    except:
        pass





