import datetime
from django.forms import ValidationError
from django.shortcuts import render,get_object_or_404,redirect,HttpResponse
from django.contrib.auth import authenticate, login , logout
from django.views.generic import TemplateView
from django.contrib.auth.models import User
from django.contrib import messages
from django.http import *
import random

import requests
from projects import settings

from django.contrib.sites.shortcuts import get_current_site
from django.template.loader import render_to_string
from django.utils.encoding import force_str, force_bytes
from django.utils.http import urlsafe_base64_encode,urlsafe_base64_decode
from django.core.mail import EmailMessage, send_mail

from .token import account_activation_token
from django.views.decorators.http import require_GET
from django.db.models import Q

from django.core.mail import EmailMultiAlternatives
from django.utils.html import strip_tags
from django.views.decorators.csrf import csrf_exempt
from django.utils.safestring import SafeText
# from googletrans import Translator
import json
from userapp.models import CostumUser
from django.core.validators import validate_email
from django.contrib import messages
import logging
import regex
import re
from django.urls import reverse


from userapp.utils import COUNTRIES
# Create your views here.

logger = logging.getLogger(__name__)

MAX_LENGTH_FIELD = 40

LANG = (
    ("fr","Français"),
    ("en","Anglais")
)

# ::::::::::::::::::::::::: TRANSLATE :::::::::::::::::::::::::::::::::::::





def send_my_mail(request,sujet,message,to:list, user,cta,url=""):

    current_site = get_current_site(request)
    
    message = render_to_string('utils/mail_temp_2.html', {
        'user': user,
        'domain': current_site.domain+":"+ str(settings.PORT) if settings.PORT else current_site.domain,
        'url':url,
        'cta':cta,
        'message':message
    })

    send_mail( sujet, "_", settings.DEFAULT_FROM_EMAIL, to, html_message=message )



    
    
@require_GET
def robots_txt(request):
    lines = [
        "sitemap: https://test.com/sitemap.xml",
        "user-Agent: *",
        
        "disallow: *",
        "user-agent: Googlebot",
        "allow: *",
        "user-agent: Bingbot",
        "allow: *",
        "user-agent: Applebot",
        "allow: *",
        "user-agent: SiteCheckerBotCrawler",
        "allow: *"
        
        
    ]
    return HttpResponse("\n".join(lines), content_type="text/plain")

def is_ajax(request):
    return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'


def conf(request):
    return render (request,'pages/temp_email.html')


# @csrf_exempt
# def signup(request):
#     current_site = get_current_site(request)
#     if request.headers.get('Origin') not in settings.CORS_ALLOWED_ORIGINS:
#         return JsonResponse({"status":"error","message":"BAD REQUEST"},status=403)

#     if(is_ajax(request=request)) and request.method  == "POST":
#         data ={}
#         mimetype = 'application/json'
#         password = request.POST.get('password',"")
#         email =request.POST.get('email',"")
#         first_name =request.POST.get('first_name',"")
#         last_name =request.POST.get('last_name',"")
#         lang =request.POST.get('langue',"")
#         postcode =request.POST.get('postcode',"")
#         country =request.POST.get('countrie',"")
#         lat =request.POST.get('lat',"0")
#         lon =request.POST.get('lon',"0")
#         address =request.POST.get('address',"")
#         # age =request.POST.get('age',"")
#         # sexe =request.POST.get('sexe',"")
        
#         # company =request.POST.get('company',"")

#         #  :::::::::::::::::: CONTRAINT ::::::::::::::::::::::

#         #  :::::::::::::::::: SESSION ::::::::::::::::::::::
#         if request.user.is_authenticated:
#             message = rvtrans("Une session est en cours.",dest=None,slice=0,safe=False,request=request)
#             data={"message":message,"type":"error"}
#             return HttpResponse(json.dumps(data), mimetype)

#         #  :::::::::::::::::: CHECK RECAPTCHAT ::::::::::::::::::::::
#         recaptcha_response = request.POST.get('recap','')
#         print('recap ::::::::::',recaptcha_response)
#         recaptcha_data = {
#             'secret': settings.RECAPTCHA_PRIVATE_KEY,
#             'response': recaptcha_response,
#         }

#         recaptcha_verification = requests.post('https://www.google.com/recaptcha/api/siteverify', data=recaptcha_data)
#         verification_data = recaptcha_verification.json()
#         print(verification_data)
#         if not verification_data['success'] or verification_data['score']<0.7:
#             message = rvtrans("le formulaire non valide",dest=None,slice=0,safe=False,request=request)
#             data={"message":message,"type":"error"}
#             return HttpResponse(json.dumps(data), mimetype)

#         #  :::::::::::::::::: REQUIREMENTS ::::::::::::::::::::::
#         if password == "" or first_name == "" or last_name == ""  :#or age =="" or sexe == "" or nationality == "" :
#             message = rvtrans("Merci de renseigner les champs requis",dest=None,slice=0,safe=False,request=request)
#             data={"message":message,"type":"error"}
#             return HttpResponse(json.dumps(data), mimetype)
        
#         if len(password) > MAX_LENGTH_FIELD or len(first_name) > MAX_LENGTH_FIELD  or len(last_name) > MAX_LENGTH_FIELD or len(address) > 80:#  or len(age) > MAX_LENGTH_FIELD   or len(nationality) > MAX_LENGTH_FIELD or len(company) > MAX_LENGTH_FIELD  :
#             message = rvtrans("les champs ne doivent pas depasser {}".format(MAX_LENGTH_FIELD),dest=None,slice=0,safe=False,request=request)
#             data={"message":message,"type":"error"}
#             return HttpResponse(json.dumps(data), mimetype)
        
#         #  :::::::::::::::::: CHECK SAFE SECURITY ::::::::::::::::::::::
        
#         def is_al_num(chaine):
#             pattern = r'^[\w ._]+$'
#             return bool(regex.match(pattern, chaine))
        
#         def is_al_num_special(chaine):
#             pattern = r'^[\w ,\-\._°\(\)]+$'
#             return bool(regex.match(pattern, chaine))

#         if not is_al_num(first_name)  or not is_al_num(last_name)  : #or (not is_al_num(sexe) and len(str(sexe)) != 0)  or (not is_al_num(nationality) and len(str(nationality)) != 0) or  (not is_al_num(company) and len(str(company)) != 0):
#             message = rvtrans("les champs sauf le mot de passe doivent contenir uniquement l'alphabet et le chiffre",dest=None,slice=0,safe=False,request=request)
#             data={"message":message,"type":"error"}
#             return HttpResponse(json.dumps(data), mimetype)
        

#         def checkPassWord(password):
#             if not re.search(r"\d", password):
#                 return False
#             if not re.search(r"[A-Z]", password):
#                 return False
#             if not re.search(r"[a-z]", password):
#                 return False
#             # if not re.search(r"[!@#$%^&*(),.?\":{}|<>]", password):
#             #     return False
            
#             return True
        
        
#         #  :::::::::::::::::: PASSWORD ::::::::::::::::::::::
#         if len(password) < 8 or not checkPassWord(password) or len(password) > 20:
#             message = rvtrans("Le mot de passe doit comporter entre 8 et 20 caractères et comprendre au moins une lettre majuscule, une lettre minuscule, un chiffre.",dest=None,slice=0,safe=False,request=request)
#             data={"message":message,"type":"error"}
#             return HttpResponse(json.dumps(data), mimetype)
        


#         #  :::::::::::::::::: EMAIL ::::::::::::::::::::::
#         def checkmail(email):
#             pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
#             if re.match(pattern, email):
#                 return True
#             else:
#                 return False
#         try:
#             validate_email(email)
#             if not checkmail(email) or email == settings.EMAIL_HOST_USER:
#                 raise Exception("Le mail n'est pas valide")
            
#         except Exception as e:
#             message = rvtrans("Le mail n'est pas valide",dest=None,slice=0,safe=False,request=request)
#             data={"message":message,"type":"error"}
#             return HttpResponse(json.dumps(data), mimetype)
        

#         try:

#             userExist = User.objects.filter(username__exact=email)
        
#             if len(userExist)!= 0:
#                 message = rvtrans("Cet utilisateur existe déja",dest=None,slice=0,safe=False,request=request)
#                 data={"message":message,"type":"erreur"}
#                 return HttpResponse(json.dumps(data), mimetype)
#             user = User()
#             user = User.objects.create_user(password=password,email=email,first_name=SafeText(first_name), last_name=SafeText(last_name),username=email,is_active = False)
#             cuser = get_object_or_404(CostumUser,user=user)
#             # cuser.address = SafeText(address)
#             # cuser.lang = None
#             # cuser.postcode = postcode
#             # cuser.lat = lat
#             # cuser.lon = lon
#             # cuser.country = country
            
#             cuser.save()
#             user.save()
            
            
#             url =  "/auth/activate/{}/{}/".format(urlsafe_base64_encode(force_bytes(user.pk)),account_activation_token.make_token(user))
            
#             try:
#                 if request.session["mynext"] is not None:
#                     previous_page = request.session["mynext"]
#                     next = previous_page
#                 else:
#                     next = "/"
#             except Exception as e:
#                 next = "/"

#             try:
#                 url+= "?next="+ next
#             except Exception as e:
#                 pass

#             message = """
#                 Merci d'activer ton compte.
            
#             """
#             message = rvtrans(message,dest=None,slice=0,safe=False,request=request)
#             subject = rvtrans("Activer mon compte  ",dest=None,slice=0,safe=False,request=request)
#             to_email = email
            
#             email_from = settings.EMAIL_HOST_USER
#             try:
#                 send_my_mail(request,subject,message,[to_email], user,subject,url=url)
#             except Exception as e:
#                 logger.error(e)

#             user = User.objects.filter(email__exact=email)
            
            
#             data = {}
#             if len(user) != 0 :
#                 message = rvtrans("Compte enregistré, vérifiez votre email pour activer votre compte",dest=None,slice=0,safe=False,request=request)
#                 # message = rvtrans("Compte enregistré",dest=None,slice=0,safe=False,request=request)
#                 data={"message":message,"type":"success"}
#                 return HttpResponse(json.dumps(data), mimetype)
            
#         except Exception as e:
            
            
#             try: 
#                 if user:
#                     user.delete()
#                     logger.info('deleting user .. ')
#             except Exception as e:
#                 print(e) 
    
#     mimetype = 'application/json'  
#     message = rvtrans("Une erreur inconnue, veuillez contacter le support",dest=None,slice=0,safe=False,request=request)
#     data={"message":message,"type":"error"}
#     return HttpResponse(json.dumps(data), mimetype)




# @csrf_exempt
def signin(request):
    current_site = get_current_site(request)
    if request.headers.get('Origin') not in settings.CORS_ALLOWED_ORIGINS:
        return JsonResponse({"status":"error","message":"BAD REQUEST"},status=403)

    
    if is_ajax(request=request):
        data ={}
        mimetype = 'application/json'
        usernameU = request.POST.get('email',"")
        passwordU = request.POST.get('password',"")
        current_url = request.GET.get('next',"#")
        
        print(usernameU,passwordU)
        #  :::::::::::::::::: CONTRAINTE ::::::::::::::::::::::

        #  :::::::::::::::::: SESSION ::::::::::::::::::::::
        if request.user.is_authenticated:
            message = "vous avez déjà une session en cours"
            data={"message":message,"type":"error"}
            return HttpResponse(json.dumps(data), mimetype)

        #  :::::::::::::::::: CHECK RECAPTCHAT ::::::::::::::::::::::
        recaptcha_response = request.POST.get('recap','')
        print('recap ::::::::::',recaptcha_response)
        recaptcha_data = {
            'secret': settings.RECAPTCHA_PRIVATE_KEY,
            'response': recaptcha_response,
        }

        recaptcha_verification = requests.post('https://www.google.com/recaptcha/api/siteverify', data=recaptcha_data)
        verification_data = recaptcha_verification.json()
        
        logger.info(verification_data)
        # if not verification_data['success'] or verification_data['score'] < 0.7:
        #     message = "Le formulaire n'est pas valide !" 
        #     data={"message":message,"type":"error"}
        #     return HttpResponse(json.dumps(data), mimetype)
        
        #  :::::::::::::::::: EMAIL ::::::::::::::::::::::
        def checkmail(email):
            pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
            if re.match(pattern, email):
                return True
            else:
                return False
            
        isEmail = True
        try:
            validate_email(usernameU)
            if not checkmail(usernameU) or usernameU == settings.EMAIL_HOST_USER:
                raise Exception("l'email n'est pas valide")
            
        except Exception as e:
            message = "l'email n'est pas valide"
            data={"message":message,"type":"error"}
            isEmail = False
            # return HttpResponse(json.dumps(data), mimetype)

        if usernameU =="" or passwordU=='':
            message = "Merci de renseigner tous les champs" 
            data={"message":message,"type":"error"}
            return HttpResponse(json.dumps(data), mimetype)
        
        if len(usernameU) > MAX_LENGTH_FIELD or len(passwordU) > MAX_LENGTH_FIELD :
            message =  "Les champs ne doivents pas dépasser {}".format(MAX_LENGTH_FIELD)
            data={"message":message,"type":"error"}
            return HttpResponse(json.dumps(data), mimetype)
        
        try:
            
            try:
                userS = User.objects.get(username__exact=usernameU)
            except Exception as e:
                print(e)
                message = "Email ou mot de passe incorrect !" 
                data={"message":message,"type":"error"}
                return HttpResponse(json.dumps(data), mimetype) 
                
            if  userS.is_active == False:
                
                # mail_subject = 'Activer votre compte'
                
                # message = """
                # Merci d'activer votre compte.
            
                # """
 
            
                # url = "/auth/activate/{}/{}/".format(urlsafe_base64_encode(force_bytes(userS.pk)),account_activation_token.make_token(userS))

                # try:
                #     if request.session["mynext"] is not None:
                #         previous_page = request.session["mynext"]
                #         next = previous_page
                #     else:
                #         next = "/"
                # except Exception as e:
                #     next = "/"

                # try:
                #     url+= "?next="+ next
                # except Exception as e:
                #     pass
                
                # to_email = usernameU
                # subject =  "Activer mon compte" 
                
                # email_from = settings.EMAIL_HOST_USER
                # try:
                #     send_my_mail(request,subject,message,[to_email], userS,subject,url=url)
                # except Exception as e:
                #     logger.error(e)
                
                message = "Votre compte n'est pas encore activé"
                data={"message":message,"type":"error"}
                return HttpResponse(json.dumps(data), mimetype)
            
            
            user = authenticate(username=userS.username, password=passwordU)
            
            
            if user is not None and user.is_active:

                try:
                    login(request,user) 
                except Exception as e:
                    message =  "Utilisateur ou mot de passe incorrect" 
                    data={"message":message,"type":"error"}
                    return HttpResponse(json.dumps(data), mimetype)
                
               

                try:
                    if request.session["mynext"] is not None:
                        previous_page = request.session["mynext"]
                        url = previous_page
                    else:
                        url = "/"
                except Exception as e:
                    url = "/"   
                    print(e)
                    
                print("REDIRECT URL:::::::::  ",url)
                data={"message":"authentification réussit","type":"success","url":reverse("app:dashboard_home")}
                return HttpResponse(json.dumps(data), mimetype) 
            else:
                message =  "Incorrect email or password" 
                data={"message":message,"type":"error"}
                return HttpResponse(json.dumps(data), mimetype) 
            
        except Exception as e:
            print(e)
    mimetype = 'application/json'
    message =  "Une erreur inconnue, veuillez contacter le support" 
    data={"message":message,"type":"error"}
    return HttpResponse(json.dumps(data), mimetype) 
        


def generateLinkForPasswordUpdate(request):
    current_site = get_current_site(request)
    # if request.headers.get('Origin') not in settings.CORS_ALLOWED_ORIGINS:
    #     return JsonResponse({"status":"error","message":"BAD REQUEST"},status=403)

    
    if is_ajax(request=request):
        data ={}
        mimetype = 'application/json'
        usernameU = request.POST.get('email',"")
        
        #  :::::::::::::::::: CONTRAINTE ::::::::::::::::::::::

        #  :::::::::::::::::: SESSION ::::::::::::::::::::::
        if request.user.is_authenticated:
            message =  "tu as déja une session en cours" 
            data={"message":message,"type":"error"}
            return HttpResponse(json.dumps(data), mimetype)

        #  :::::::::::::::::: CHECK RECAPTCHAT ::::::::::::::::::::::
        recaptcha_response = request.POST.get('recap','')
        print('recap ::::::::::',recaptcha_response)
        recaptcha_data = {
            'secret': settings.RECAPTCHA_PRIVATE_KEY,
            'response': recaptcha_response,
        }

        recaptcha_verification = requests.post('https://www.google.com/recaptcha/api/siteverify', data=recaptcha_data)
        verification_data = recaptcha_verification.json()
        # print(verification_data)

        if not verification_data['success'] or verification_data['score'] < 0.7:
            message = "Form is not valid" 
            data={"message":message,"type":"error"}
            return HttpResponse(json.dumps(data), mimetype)
        
        #  :::::::::::::::::: EMAIL ::::::::::::::::::::::
        def checkmail(email):
            pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
            if re.match(pattern, email):
                return True
            else:
                return False
        try:
            validate_email(usernameU)
            if not checkmail(usernameU) or usernameU == settings.EMAIL_HOST_USER:
                raise Exception("L'email n'est pas valide.")
            
        except Exception as e:
            logger.info(e)
            message =  "L'email n'est pas valide." 
            data={"message":message,"type":"error"}
            return HttpResponse(json.dumps(data), mimetype)


        if usernameU =="" :
            message =  "Merci de renseigner les champs." 
            data={"message":message,"type":"error"}
            return HttpResponse(json.dumps(data), mimetype)
        
        if len(usernameU) > MAX_LENGTH_FIELD :
            message = "les champs ne doivent pas dépasser {}".format(MAX_LENGTH_FIELD) 
            data={"message":message,"type":"error"}
            return HttpResponse(json.dumps(data), mimetype)
        
        try:
            
            userS = User.objects.get(username=usernameU)
            mail_subject = 'Activer mon compte '
            
            message = """
            Avez-vous oublié votre mot de passe? si ce n'est pas le cas, veuillez ignorer cet e-mail.
        
            """ 
        
            url = "/auth/to_updatepass/{}/{}/".format(urlsafe_base64_encode(force_bytes(userS.pk)),account_activation_token.make_token(userS))

            print(url)
            to_email = usernameU
            subject =  "Réinitialiser mon mot de passe" 
            cta =  "Réinitialiser " 
            
            email_from = settings.EMAIL_HOST_USER
            try:
                send_my_mail(request,subject,message,[to_email], userS,cta,url=url)
                message =  "Veuillez vérifier votre courrier électronique pour mettre à jour votre mot de passe" 
                data={"message":message,"type":"success"}
                return HttpResponse(json.dumps(data), mimetype)
            except Exception as e:
                logger.error(e)
            
            
            
        except Exception as e:
            print('::::::::::::::::',e)
            
    mimetype = 'application/json'
    message = "Une erreur inconnue lors du processus de réinitialisation, veuillez contacter notre support" 
    data={"message":message,"type":"error"}
    return HttpResponse(json.dumps(data), mimetype) 




def updatePassword(request):
    current_site = get_current_site(request)
    if request.headers.get('Origin') not in settings.CORS_ALLOWED_ORIGINS:
        return JsonResponse({"status":"error","message":"BAD REQUEST"},status=403)

    
    if is_ajax(request=request):
        data ={}
        mimetype = 'application/json'
        usernameU = request.POST.get('username',"")
        password = request.POST.get('password',"")
        
        #  :::::::::::::::::: CONTRAINTE ::::::::::::::::::::::

        #  :::::::::::::::::: SESSION ::::::::::::::::::::::
        if request.user.is_authenticated:
            message = "tu as deja une session en cours" 
            data={"message":message,"type":"error"}
            return HttpResponse(json.dumps(data), mimetype)

        #  :::::::::::::::::: CHECK RECAPTCHAT ::::::::::::::::::::::
        recaptcha_response = request.POST.get('recap','')
        print('recap ::::::::::',recaptcha_response)
        recaptcha_data = {
            'secret': settings.RECAPTCHA_PRIVATE_KEY,
            'response': recaptcha_response,
        }

        recaptcha_verification = requests.post('https://www.google.com/recaptcha/api/siteverify', data=recaptcha_data)
        verification_data = recaptcha_verification.json()
        print(verification_data)

        # if not verification_data['success'] or verification_data['score'] < 0.7:
        #     message ="le formulaire n'est pas valide"
        #     data={"message":message,"type":"error"}
        #     return HttpResponse(json.dumps(data), mimetype)
        
        if len(password) > MAX_LENGTH_FIELD :
            message = "le mot de passe ne doit pas dépasser {}".format(MAX_LENGTH_FIELD) 
            data={"message":message,"type":"error"}
            return HttpResponse(json.dumps(data), mimetype)
        
        def checkPassWord(password):
            if not re.search(r"\d", password):
                return False
            if not re.search(r"[A-Z]", password):
                return False
            if not re.search(r"[a-z]", password):
                return False
            if not re.search(r"[!@#$%^&*(),.?\":{}|<>]", password):
                return False
            
            return True
        
        #  :::::::::::::::::: PASSWORD ::::::::::::::::::::::
        if len(password) < 8 or not checkPassWord(password) or len(password) > 30:
            message =  "Le mot de passe doit comporter entre 8 et 30 caractères et comprendre au moins une lettre majuscule, une lettre minuscule et un chiffre." 
            data={"message":message,"type":"error"}
            return HttpResponse(json.dumps(data), mimetype)
        
        try:
            
            userS = User.objects.get(username=usernameU)
            mail_subject = 'Activer mon compte '
            
            message = """
            Votre mot de passe a été bien changé.
        
            """

            to_email = usernameU
            subject =  "Changer votre mot de passe" 
            cta = "Changer le mot de passe"
            
            email_from = settings.EMAIL_HOST_USER
            try:
                userS.set_password(password)
                userS.save()
                try:
                    send_my_mail(request,subject,message,[to_email], userS,cta,url="")
                except Exception as e:
                    logger.error(e)

                message = "Votre mot de passe a été bien changé"
                data={"message":message,"type":"success"}
                return HttpResponse(json.dumps(data), mimetype)
            except Exception as e:
                logger.error(e)
            
            
            
        except Exception as e:
            print('::::::::::::::::',e)
            
    mimetype = 'application/json'
    message = "Une erreur inconnue lors du processus de réinitialisation, veuillez contacter notre support."
    data={"message":message,"type":"error"}
    return HttpResponse(json.dumps(data), mimetype) 


class Logout (TemplateView):

    def get(self, request, *args, **kwargs):
        
        logout(request)
    
        return redirect('/')






def activate(request, uidb64, token):
    try:
        uid = force_str(urlsafe_base64_decode(uidb64))

        user = User.objects.get(pk=uid)
    except(TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None
    if user is not None and account_activation_token.check_token(user,token):
        user.is_active = True
        user.save()

        # Rediriger vers la page de définition du mot de passe
        # au lieu de connecter automatiquement l'utilisateur
        messages.success(request, 'Votre compte a été activé avec succès. Veuillez définir votre mot de passe.')
        return redirect('userapp:to_updatepass', uidb64=uidb64, token=token)
        
    else:
        data = {}
        data["message"] = "Le lien d'activation est incorrect ou expiré."
        return render(request, 'error.html', data)


def to_updatepass(request, uidb64, token):
    try:
        uid = force_str(urlsafe_base64_decode(uidb64))
        user = User.objects.get(pk=uid)

    except(TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None
    if user is not None and account_activation_token.check_token(user,token):
        pass
        return render(request,"account/updatepass.html", {"username":user.username})
        
    else:
        return redirect('/404')
    


def to_login(request):
    data = {}
    
    current_url = request.GET.get('next',"#")
    # print(current_url)
    
    if request.user.is_authenticated:
        return redirect("/")
    
    try:
        
        pass     
    
    except Exception as e:
        
        print(e)
    
    data['current_url'] = current_url
    return render(request,"account/signin.html", data)



def to_signup(request):
    data = {}
    
    cur_url = request.GET.get('next',"#")
    email = request.GET.get("email","")
    fname = request.GET.get("fname","")
    lname = request.GET.get("lname","")
    
    
    if request.user.is_authenticated:
        return redirect("/")
    
    try:
        pass
                
    
    except Exception as e:
        
        print(e)
    # print(all_countries)
    
    data["email"]= email
    data["fname"]= fname
    data["lname"]= lname
    
    return render(request,"account/signup.html", data)


def to_forgetpassword(request):
    data = {}
    
    
    if request.user.is_authenticated:
        return redirect("/")
    
    try:
        pass
                
    
    except Exception as e:
        
        print(e)
        
    return render(request,"account/forgetpass.html", data)