from django.shortcuts import render
from django.views.generic import TemplateView
from django.views.generic.base import View
from django.shortcuts import render ,HttpResponse, redirect
from django.contrib.auth import authenticate ,login,logout
from django.contrib import messages
from . import forms
from django.contrib.auth.models import User
from django.http import JsonResponse
from django.core import mail
import math, random, string
from django.conf import settings
from django.template.loader import render_to_string
from .models import *
from seer_user.models import *
from fortune_teller.models import *
from django.db.models import Q,Count
from django.core.paginator import Paginator
import csv
from .functions import *
from datetime import datetime
import json
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
import ast
import csv
from django.utils.timezone import make_aware
from django.db.models import Sum
import calendar
from pyfcm import FCMNotification
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .serializers import *
import stripe


# Create your views here.

def generateTranscationsId():
	lastObj= SeerUserTranscation.objects.all().last()
	if lastObj:
		if not lastObj.transcation_id:
			return 'TRANS000001'

		theId=lastObj.transcation_id
		theId=theId[5:]
		theId=int(theId)+1
		theId=str(theId)
		theId=theId.zfill(5)
		return "TRANS"+str(theId)
	else:
		return 'TRANS000001'

def checkEmail(request):
	text = request.GET.get('email')
	post = User.objects.filter(username=text).first()
	if post:
		return HttpResponse ('true')
	else:
		message = 'This email does not exist in our database'
		return JsonResponse(message,safe=False)
	
def checkLoginPassword(request):
	text = request.GET.get('email','')
	password = request.GET.get('password')
	user         = User.objects.get(username=text)
	if user.check_password(password) == False:
		message = 'Please enter the correct password'
		return JsonResponse(message,safe=False)
	else:
		return HttpResponse ('true')
	
def adminCheckPassword(request):
	old_password = request.GET.get('old_password')
	user         = User.objects.get(email=request.user.email)
	if user.check_password(old_password) == False:
		message = 'Does not match with the old password.'
		return JsonResponse(message,safe=False)
	else:
		return HttpResponse ('true')
	

class adminLogin(TemplateView):
	template_name = 'login.html'
	def get(self,request):
		return render(request,self.template_name)
	def post(self,request):
		form = forms.adminLoginForm(request.POST)
		if form.is_valid():
			email    = form.cleaned_data.get('email')
			password = form.cleaned_data.get('password')

			user = authenticate(username=email, password=password)
			if user:
					print('yes')
					login(request, user)
					messages.success(request, "Login successfully")
					return redirect('/dashboard')

			else:
				messages.success(request, "Invalid email and password.")
				return render(request, self.template_name)
		else:
			return render(request, 'login', {'form': form})


class adminForgetPassword(TemplateView):
	template_name = 'forgot-password.html'
	def get(self,request):
		return render(request,self.template_name)
	
	def post(self,request):
		form = forms.adminforgetpassword(request.POST)
		if form.is_valid():
			email =  form.cleaned_data.get('email')
			admin_obj = SuperAdmin.objects.filter(email = email).first()
			ran_num = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(12)])
			baselink =  '/forgot-admin/' + str(admin_obj.email) + '/' + ran_num
			completelink = str(settings.BASE_URL) + baselink
			admin_obj.forgotPasswordLink = baselink
			admin_obj.save()            
			subject = 'Forgot Password'
			html_message = render_to_string('forget_admin_password_email.html', {'link': completelink})
			plain_message = html_message
			from_email = settings.EMAIL_HOST_USER
			to = email
			mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message)
			messages.success(request, "A link has been successfully sent to your mail.")
			return redirect('/admin-forget-password')
		else:
			return render(request, self.template_name, {'form': form})

class forgetPasswordVerification(TemplateView):
	template_name = 'reset-password.html'
	def get(self,request):
		link = str(self.request.path)
		user_email = link.split('/')[-2]
		link_expiry = SuperAdmin.objects.filter(email = user_email).first()
		if link_expiry.forgotPasswordLink == "LinkExpiry":
			return render(request,'link-expire.html')
		admin_obj = SuperAdmin.objects.filter(email = user_email, forgotPasswordLink = link).first()
		if admin_obj:
			valid = True
		else:
			valid = False
		return render(request,self.template_name,locals())

	def post(self,request):
		form = forms.forgetverification(request.POST)
		if form.is_valid():
			new_password = form.cleaned_data.get('new_password')
			confirm_new_password = form.cleaned_data.get('confirm_new_password')
			link = str(self.request.path)
			user_email = link.split('/')[-3]
			print('user_email',user_email)
			admin_obj = SuperAdmin.objects.filter(email = user_email).first()
			user_obj = User.objects.filter(id=admin_obj.user.id).first()
			if user_obj:
				user_obj.set_password(new_password)
				user_obj.save()
				admin_obj.forgotPasswordLink = "LinkExpiry"
				admin_obj.save()
				messages.success(request, "Password changed successfully")
				return redirect('/')
			else:
				messages.error(request, "Something went wrong")
				return redirect('/')
		else:
			return render(request, self.template_name, {'form': form})	


class dashboard(TemplateView):
	template_name = 'dashboard.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		user_obj = SeerUser.objects.all().count()
		fortune_obj = FortuneTeller.objects.all().count()
		five_user_obj = SeerUser.objects.filter(end_date__isnull = True).order_by('-id')[:5]
		five_fortune_obj = FortuneTeller.objects.filter(end_date__isnull = True).order_by('-id')[:5]
		total_bookings = FortuneAppointmentBook.objects.all().count()
		total_earning = SeerUserTranscation.objects.aggregate(total_amount=Sum('amount'))['total_amount']

		base_url = str(settings.BASE_URL)
		booking_data = FortuneAppointmentBook.objects.all()[:5]
		month_list = ['01' , '02' , '03' , '04' , '05' , '06' , '07' ,'08' , '09' , '10' , '11' , '12']
		bookings = []
		import datetime
		today = datetime.date.today()
		year = today.year
		for mnth in month_list:
			all_booking = FortuneAppointmentBook.objects.filter(created_at__year=year ,created_at__month=mnth,end_date__isnull =True).count()
			bookings.append(all_booking)
		

		earning = [sum(float(transcation.amount) for transcation in SeerUserTranscation.objects.filter(created_at__year=year,created_at__month=i))
			for i in range(1,13)]
		return render(request,self.template_name,locals())
	
class userList(TemplateView):
	template_name = 'users_list.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		try:
			admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
			base_url = str(settings.BASE_URL)
			user_obj = SeerUser.objects.filter(end_date__isnull = True).order_by('-id')
			search_post = request.GET.get('search')
			start_from = request.GET.get('start_from')
			start_to = request.GET.get('start_to')
			time = "11:59:59"
			lookups = Q()
			if search_post:
				lookups.add(Q(first_name__icontains=search_post)|Q(last_name__icontains=search_post)|Q(email__icontains=search_post)|Q(phone_number__icontains=search_post), Q.AND)
			if start_from and start_to:
				lookups.add(Q(created_at__range=[start_from, start_to + ' '+ time]), Q.AND)
			user_obj = SeerUser.objects.filter(lookups,end_date__isnull = True).order_by('-id')
			paginator = Paginator(user_obj, 10)
			page_number = request.GET.get('page')
			user_data = paginator.get_page(page_number)
			return render(request,self.template_name,locals())
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard') 

class changeUserStatus(TemplateView):
	@method_decorator(login_required(login_url='/'))
	def post(self,request):
		try:
			pub        = SeerUser.objects.get(id = request.POST['main_id'])
			pub.status = request.POST['status']
			pub.save()
			if pub.status == "1":
				messages.success(request, "User status is activated")
				return HttpResponse(request.META.get('HTTP_REFERER'))
			else:
				messages.error(request, "User status is deactivated")
				return HttpResponse(request.META.get('HTTP_REFERER'))
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('admin-dashboard')


class viewUser(TemplateView):
	template_name = 'view_user_detail.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request,id):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		user_obj = SeerUser.objects.filter(id=id,end_date__isnull=True).first()
		if user_obj.images:
			user_images =  ast.literal_eval(user_obj.images)[0]
		else:
			user_images = ''
		base_url = str(settings.BASE_URL)
		upcoming_booking = FortuneAppointmentBook.objects.filter(Q(appointment_status='Pending')|Q(appointment_status='Accepted'),seer_user = id)
		past_booking = FortuneAppointmentBook.objects.filter(seer_user = id).exclude(appointment_status__in=['Pending', 'Accepted']).order_by('-id')
		return render(request,self.template_name,locals())
	

class EditUser(TemplateView):
	template_name = 'edit_user.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request,id):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		user_obj = SeerUser.objects.filter(id=id,end_date__isnull=True).first()
		return render(request,self.template_name,locals())
	def post(self,request,id):
		form = forms.editfortuneteller(request.POST)
		if form.is_valid():
			first_name = form.cleaned_data.get('first_name')
			last_name = form.cleaned_data.get('last_name')
			email = form.cleaned_data.get('email')
			phone_number = form.cleaned_data.get('phone_number')
			SeerUser.objects.filter(id=id).update(first_name = first_name,last_name = last_name)
			messages.success(request, "Updated Succesfully")
			return redirect('user-list')
		else:
			return render(request,self.template_name)
		
def checkphoneedituser(request):
	customer_id = request.GET.get('customer_id')
	phone_number = request.GET.get('phone_number')
	post = SeerUser.objects.filter(phone_number=phone_number).exclude(id=customer_id).first()
	if post:
		message = 'This phone number already exist.'
		return JsonResponse(message,safe=False)
	else:
		return HttpResponse ('true')


class FortunetellerList(TemplateView):
	template_name = 'fortuneteller_list.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		try:
			admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
			fortune_obj = FortuneTeller.objects.filter(end_date__isnull = True).order_by('-id')
			search_post = request.GET.get('search')
			search_post = request.GET.get('search')
			start_from = request.GET.get('start_from')
			start_to = request.GET.get('start_to')
			time = "11:59:59"
			lookups = Q()
			if search_post:
				lookups.add(Q(first_name__icontains=search_post)|Q(last_name__icontains=search_post)|Q(email__icontains=search_post)|Q(phone_number__icontains=search_post), Q.AND)
			if start_from and start_to:
				lookups.add(Q(created_at__range=[start_from, start_to + ' '+ time]), Q.AND)
			fortune_obj = FortuneTeller.objects.filter(lookups,end_date__isnull = True).order_by('-id')
			paginator = Paginator(fortune_obj, 10)
			page_number = request.GET.get('page')
			fortune_data = paginator.get_page(page_number)
			base_url = str(settings.BASE_URL)
			return render(request,self.template_name,locals())
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard') 
	
class ViewFortuneteller(TemplateView):
	template_name = 'view_fortuneteller_detail.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request,id):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		fortune_obj = FortuneTeller.objects.filter(id=id,end_date__isnull=True).first()
		base_url = str(settings.BASE_URL)
		upcoming_booking = FortuneAppointmentBook.objects.filter(Q(appointment_status='Pending')|Q(appointment_status='Accepted'),fortune_teller = id)
		past_booking = FortuneAppointmentBook.objects.filter(fortune_teller = id).exclude(appointment_status__in=['Pending', 'Accepted']).order_by('-id')
		return render(request,self.template_name,locals())
	

class ChangeFortuneTellerStatus(View):
	@method_decorator(login_required(login_url='/'))
	def post(self,request):
		try:
			pub        = FortuneTeller.objects.get(id = request.POST['main_id'])
			pub.status = request.POST['status']
			pub.save()
			if pub.status == "1":
				messages.success(request, "Status is activated")
				return HttpResponse(request.META.get('HTTP_REFERER'))
			else:
				messages.error(request, "Status is deactivated")
				return HttpResponse(request.META.get('HTTP_REFERER'))
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('admin-dashboard')


class EditFortuneTeller(TemplateView):
	template_name = 'edit_fortunetelller.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request,id):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		fortune_obj = FortuneTeller.objects.filter(id=id,end_date__isnull=True).first()
		return render(request,self.template_name,locals())
	def post(self,request,id):
		form = forms.editfortuneteller(request.POST)
		if form.is_valid():
			first_name = form.cleaned_data.get('first_name')
			last_name = form.cleaned_data.get('last_name')
			email = form.cleaned_data.get('email')
			phone_number = form.cleaned_data.get('phone_number')
			FortuneTeller.objects.filter(id=id).update(first_name = first_name,last_name = last_name)
			messages.success(request, "Updated Succesfully")
			return redirect('fortuneteller-list')
		else:
			return render(request,self.template_name)

def CheckPhoneFortuneEdit(request):
	customer_id = request.GET.get('customer_id')
	phone_number = request.GET.get('phone_number')
	post = FortuneTeller.objects.filter(phone_number=phone_number).exclude(id=customer_id).first()
	if post:
		message = 'This phone number already exist.'
		return JsonResponse(message,safe=False)
	else:
		return HttpResponse ('true')


class HobbiesList(TemplateView):
	template_name = 'hobbies_list.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		try:
			admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
			data_obj = Hobbies.objects.filter(end_date__isnull = True).order_by('-id')
			search_post = request.GET.get('search')
			if search_post:
				data_obj = Hobbies.objects.filter(Q(hobby__icontains=search_post),end_date__isnull = True).order_by('-id')
			paginator = Paginator(data_obj, 10)
			page_number = request.GET.get('page')
			hobbies_obj = paginator.get_page(page_number)
			return render(request,self.template_name,locals())

		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard') 
	 
		
class AddHobbies(TemplateView):
	template_name = 'add_hobbies.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		return render(request,self.template_name,locals())
	
	def post(self,request):
		try:
			form = forms.hobbies_form(request.POST)
			if form.is_valid():
				hobby_name = form.cleaned_data.get('hobby_name')
				Hobbies.objects.create(hobby=hobby_name)
				messages.success(request, "Created Succesfully")
				return redirect('hobbies-list')
			else:
				return render(request,self.template_name)
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard')

class EditHobbies(TemplateView):
	template_name = 'edit_hobbies.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request,id):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		hobbies_obj = Hobbies.objects.filter(id=id,end_date__isnull=True).first()
		return render(request,self.template_name,locals())
	
	def post(self,request,id):
		try:
			form = forms.hobbies_form(request.POST)
			if form.is_valid():
				hobby_name = form.cleaned_data.get('hobby_name')
				Hobbies.objects.filter(id=id).update(hobby=hobby_name)
				messages.success(request, "Updated Succesfully")
				return redirect('hobbies-list')
			else:
				return render(request,self.template_name)
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard')

class changeHobbiesStatus(TemplateView):
	@method_decorator(login_required(login_url='/'))
	def post(self,request):
		try:
			pub        = Hobbies.objects.get(id = request.POST['main_id'])
			pub.status = request.POST['status']
			pub.save()
			if pub.status == "1":
				messages.success(request, "Hobbies status is activated")
				return HttpResponse(request.META.get('HTTP_REFERER'))
			else:
				messages.error(request, "Hobbies status is deactivated")
				return HttpResponse(request.META.get('HTTP_REFERER'))
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('admin-dashboard')




class ServiceList(TemplateView):
	template_name = 'service_list.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		try:
			admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
			data_obj = Service.objects.filter(end_date__isnull = True).order_by('-id')
			search_post = request.GET.get('search')
			if search_post:
				data_obj = Service.objects.filter(Q(service_name__icontains=search_post),end_date__isnull = True).order_by('-id')
			paginator = Paginator(data_obj, 10)
			page_number = request.GET.get('page')
			service_obj = paginator.get_page(page_number)
			return render(request,self.template_name,locals())
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard') 


class AddService(TemplateView):
	template_name = 'add_service.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		return render(request,self.template_name,locals())
	
	def post(self,request):
		try:
			form = forms.service_form(request.POST)
			if form.is_valid():
				service_name = form.cleaned_data.get('service_name')
				status = 1
				Service.objects.create(service_name=service_name,status=status)
				messages.success(request, "Created Succesfully")
				return redirect('service-list')
			else:
				return render(request,self.template_name)
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard')

class EditService(TemplateView):
	template_name = 'edit_service.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request,id):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		service_obj = Service.objects.filter(id=id,end_date__isnull=True).first()
		return render(request,self.template_name,locals())
  
	def post(self,request,id):
		try:
			form = forms.service_form(request.POST)
			if form.is_valid():
				service_name = form.cleaned_data.get('service_name')
				status = 1
				Service.objects.filter(id=id).update(service_name=service_name,status=status)
				messages.success(request, "Update Succesfully")
				return redirect('service-list')
			else:
				return render(request,self.template_name)
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard')


class changeServiceStatus(TemplateView):
	@method_decorator(login_required(login_url='/'))
	def post(self,request):
		try:
			pub        = Service.objects.get(id = request.POST['main_id'])
			pub.status = request.POST['status']
			pub.save()
			if pub.status == "1":
				messages.success(request, "Service status is activated")
				return HttpResponse(request.META.get('HTTP_REFERER'))
			else:
				messages.error(request, "Service status is deactivated")
				return HttpResponse(request.META.get('HTTP_REFERER'))
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('admin-dashboard')


class SkillList(TemplateView):
	template_name = 'skill_list.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		try:
			admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
			data_obj = Skill.objects.filter(end_date__isnull = True).order_by('-id')
			search_post = request.GET.get('search')
			if search_post:
				data_obj = Skill.objects.filter(Q(skill_name__icontains=search_post),end_date__isnull = True).order_by('-id')
			paginator = Paginator(data_obj, 10)
			page_number = request.GET.get('page')
			service_obj = paginator.get_page(page_number)
			return render(request,self.template_name,locals())
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard') 


class AddSkill(TemplateView):
	template_name = 'add_skills.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		return render(request,self.template_name,locals())
	
	def post(self,request):
		try:
			form = forms.skill_form(request.POST)
			if form.is_valid():
				skill_name = form.cleaned_data.get('skill_name')
				status = 1
				Skill.objects.create(skill_name=skill_name,status=status)
				messages.success(request, "Created Succesfully")
				return redirect('skill-list')
			else:
				return render(request,self.template_name)
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard')

class EditSkill(TemplateView):
	template_name = 'edit_skill.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request,id):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		service_obj = Skill.objects.filter(id=id,end_date__isnull=True).first()
		return render(request,self.template_name,locals())
  
	def post(self,request,id):
		try:
			form = forms.skill_form(request.POST)
			if form.is_valid():
				skill_name = form.cleaned_data.get('skill_name')
				status = 1
				Skill.objects.filter(id=id).update(skill_name=skill_name,status=status)
				messages.success(request, "Update Succesfully")
				return redirect('skill-list')
			else:
				return render(request,self.template_name)
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard')


class changeSkillStatus(TemplateView):
	@method_decorator(login_required(login_url='/'))
	def post(self,request):
		try:
			pub        = Skill.objects.get(id = request.POST['main_id'])
			pub.status = request.POST['status']
			pub.save()
			if pub.status == "1":
				messages.success(request, "Skill status is activated")
				return HttpResponse(request.META.get('HTTP_REFERER'))
			else:
				messages.error(request, "Skill status is deactivated")
				return HttpResponse(request.META.get('HTTP_REFERER'))
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('admin-dashboard')



class PaymentLists(TemplateView):
	template_name = 'payment_list.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		data_obj = SeerUserTranscation.objects.all().order_by('-id')
		search_post = request.GET.get('search')
		booking_date = request.GET.get('booking_date')
		time = "11:59:59"
		lookups = Q()
		if search_post:
			lookups.add(Q(seer_user__first_name__icontains=search_post)|Q(seer_user__last_name__icontains=search_post)|Q(booking__fortune_teller__first_name__icontains=search_post)|Q(booking__fortune_teller__last_name__icontains=search_post)|Q(transcation_id__icontains=search_post), Q.AND)
		

		if booking_date:
			date_string = str(booking_date) 
			booking_date_time = make_aware(datetime.fromisoformat(date_string))
			print('booking_date_time', booking_date_time)
			lookups.add(Q(created_at__date=booking_date_time), Q.AND)


		data_obj = SeerUserTranscation.objects.filter(lookups).order_by('-id')
		paginator = Paginator(data_obj, 10)
		page_number = request.GET.get('page')
		payment_obj = paginator.get_page(page_number)
		return render(request,self.template_name,locals())


class PaymentDetails(TemplateView):
	template_name = 'payment_details.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request,id):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		payment_obj = SeerUserTranscation.objects.filter(id=id).first()
		print('payment_obj',payment_obj)
		return render(request,self.template_name,locals())


class BookingLists(TemplateView):
	template_name = 'booking_list.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		data_obj = FortuneAppointmentBook.objects.all().order_by('-id')
		search_post = request.GET.get('search')
		if search_post:
			data_obj = FortuneAppointmentBook.objects.filter(Q(fortune_teller__first_name__icontains=search_post)|Q(fortune_teller__last_name__icontains=search_post)|Q(seer_user__first_name__icontains=search_post)|Q(seer_user__last_name__icontains=search_post)|Q(service__service_name__icontains=search_post),end_date__isnull = True).order_by('-id')
		paginator = Paginator(data_obj, 10)
		page_number = request.GET.get('page')
		booking_obj = paginator.get_page(page_number)
		return render(request,self.template_name,locals())

class BookingDetails(TemplateView):
	template_name = 'booking_details.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request,id):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		booking_obj = FortuneAppointmentBook.objects.filter(id=id).first()
		return render(request,self.template_name,locals())


def ExportCSVBooking(request):
	queryset = FortuneAppointmentBook.objects.all()
	response = HttpResponse(content_type='text/csv')
	response['Content-Disposition'] = 'attachment; filename="booking.csv"'
	writer = csv.writer(response)
	writer.writerow(['Appointment Id', 'Fortuneteller Name', 'User Name','Appointment Date','Appointment Time','Service Name','Service Type', 'Appointment Status', 'Price'])

	# Write the data rows
	for item in queryset:
		writer.writerow([item.appointment_id, item.fortune_teller.first_name+' '+item.fortune_teller.last_name, item.seer_user.first_name+' '+item.seer_user.last_name,item.appointment_date,item.appointment_time,item.service.service_name,item.service_type,item.appointment_status,item.price])

	return response
	

class EditProfileDatabase(TemplateView):
	template_name = 'edit_profile_database.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request,id):
		tab_name = request.GET.get('profile')
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()

		'''===========Horoscope============='''
		if tab_name == 'horoscope':
			profile_obj = Horoscope.objects.filter(id=id,end_date__isnull=True).first()
			title_value = profile_obj.horoscope
			'''===========Chinese Zodiac============='''
		elif tab_name == 'chinese_zodiac':
			profile_obj = ChineseZodiac.objects.filter(id=id,end_date__isnull=True).first()
			title_value = profile_obj.chinese_zodiac
			'''===========Five Element============='''
		elif tab_name == 'five_element':
			profile_obj = FiveElements.objects.filter(id=id,end_date__isnull=True).first()
			title_value = profile_obj.element_name
			'''===========MBTI============='''
		elif tab_name == 'mbti':
			profile_obj = MBTI.objects.filter(id=id,end_date__isnull=True).first()
			title_value = profile_obj.mbti_name
		return render(request,self.template_name,locals())
	
	def post(self,request,id):
		try:
			tab_name = request.POST.get('profile')
			print('tab_name====',tab_name)
			if tab_name == 'horoscope':
				modal_name = Horoscope
				modal_field = 'horoscope'
			elif tab_name == 'chinese_zodiac':
				modal_name = ChineseZodiac
				modal_field = 'chinese_zodiac'
			elif tab_name == 'five_element':
				modal_name = FiveElements
				modal_field = 'element_name'
			elif tab_name == 'mbti':
				modal_name = MBTI
				modal_field = 'mbti_name'
			form = forms.profiledatabaseform(request.POST)
			if form.is_valid():
				profile_title = form.cleaned_data.get('profile_title')
				profile_tagline = form.cleaned_data.get('profile_tagline')
				profile_description = form.cleaned_data.get('profile_description')
				
				# modal_name.objects.filter(id=id).update(modal_field=profile_title,tagline=profile_tagline,description=profile_description)
				
				# Create a dictionary to map field names to values
				update_data = {
					modal_field: profile_title,
					'tagline': profile_tagline,
					'description': profile_description
				}

				# Update the model using **update_data
				modal_name.objects.filter(id=id).update(**update_data)

				messages.success(request, "Updated Succesfully")
				return redirect('profile-database')
			else:
				return render(request,self.template_name)
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard')



class ProfileDatabase(TemplateView):
	template_name = 'profile_database.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		try:
			admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
			
			'''===========Horoscope============='''
			horoscope_obj = Horoscope.objects.filter(end_date__isnull = True).order_by('id')
			paginator = Paginator(horoscope_obj, 10)
			all_page_number = request.GET.get('horoscope')
			all_horoscope_obj = paginator.get_page(all_page_number)

			'''===========Chinese Zodiac============='''
			chinese_zodiac_obj = ChineseZodiac.objects.filter(end_date__isnull = True).order_by('id')
			paginator = Paginator(chinese_zodiac_obj, 10)
			all_page_number = request.GET.get('chinese_zodiac')
			all_chinese_obj = paginator.get_page(all_page_number)
			
			'''===========Five Element============='''
			five_elements_obj = FiveElements.objects.filter(end_date__isnull = True).order_by('id')
			paginator = Paginator(five_elements_obj, 10)
			all_page_number = request.GET.get('five_element')
			all_five_element_obj = paginator.get_page(all_page_number)
			
			'''===========MBTI============='''
			mbti_obj = MBTI.objects.filter(end_date__isnull = True).order_by('-id')
			paginator = Paginator(mbti_obj, 10)
			all_page_number = request.GET.get('mbti')
			all_mbti_obj = paginator.get_page(all_page_number)

			return render(request,self.template_name,locals())
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard') 
		

def importProfileDataCSV(request):
	try:
		if request.method == 'POST' and request.FILES['myFileInput']:
			csv_file = request.FILES['myFileInput']
			tab_name = request.POST.get('active_tab')
			print(tab_name)
			decoded_file = csv_file.read().decode('utf-8').splitlines()
			reader = csv.DictReader(decoded_file)
			duplicate_count = 0
			if tab_name == 'horoscope-tab':
				# horoscope_profile_data = Horoscope.objects.all()
				# if horoscope_profile_data:
				# 	messages.warning(request, "Data is already exist.")
				# 	return redirect('profile-database')
				for row in reader:
					try:
						user = request.user.id
						user_obj = User.objects.filter(id = user)
						if not user_obj:
							messages.error(request, f"Invalid user found. Error in line {reader.line_num}.")
							return redirect('profile-database')
					except ValueError:
						messages.error(request, f"User must be an integer. Error in line {reader.line_num}.")
						return redirect('profile-database')


				
					if 'Horoscope' not in row:
						messages.error(request,f"horoscope is missing in csv. Error in line {reader.line_num}.")
						return redirect('profile-database')
					if 'Tagline' not in row:
						messages.error(request,f"tagline is missing in csv. Error in line {reader.line_num}.")
						return redirect('profile-database')
					if 'Description' not in row:
						messages.error(request,f"description is missing in csv. Error in line {reader.line_num}.")
						return redirect('profile-database')
					
					existing_profile_data = Horoscope.objects.filter(horoscope=row['Horoscope']).first()
					# if existing_profile_data:
					# 	duplicate_count += 1
					# 	messages.warning(request, f"Duplicate data found in line {reader.line_num}.")
					# 	continue
					
					if existing_profile_data:
						# Update existing record
						existing_profile_data.horoscope = row['Horoscope']
						existing_profile_data.tagline = row['Tagline']
						existing_profile_data.description = row['Description']
						existing_profile_data.save()
					
					else:
						horoscope_obj = Horoscope(
							horoscope=row['Horoscope'],
							tagline=row['Tagline'],
							description=row['Description'],
							
						)
						horoscope_obj.save()
			elif tab_name == 'zodiac-tab':
				# zodiac_profile_data = ChineseZodiac.objects.all()
				# if zodiac_profile_data:
				# 	messages.warning(request, "Data is already exist.")
				# 	return redirect('profile-database')
				for row in reader:
					try:
						user = request.user.id
						user_obj = User.objects.filter(id = user)
						if not user_obj:
							messages.error(request, f"Invalid user found. Error in line {reader.line_num}.")
							return redirect('profile-database')
					except ValueError:
						messages.error(request, f"User must be an integer. Error in line {reader.line_num}.")
						return redirect('profile-database')

				
					if 'Chinese Zodiac' not in row:
						messages.error(request,f"Chinese Zodiac is missing in csv. Error in line {reader.line_num}.")
						return redirect('profile-database')
					if 'Tagline' not in row:
						messages.error(request,f"tagline is missing in csv. Error in line {reader.line_num}.")
						return redirect('profile-database')
					if 'Description' not in row:
						messages.error(request,f"description is missing in csv. Error in line {reader.line_num}.")
						return redirect('profile-database')
					
					existing_profile_data = ChineseZodiac.objects.filter(chinese_zodiac=row['Chinese Zodiac']).first()
					# if existing_profile_data:
					# 	duplicate_count += 1
					# 	messages.warning(request, f"Duplicate data found in line {reader.line_num}.")
					# 	continue

					if existing_profile_data:
						# Update existing record
						existing_profile_data.chinese_zodiac = row['Chinese Zodiac']
						existing_profile_data.tagline = row['Tagline']
						existing_profile_data.description = row['Description']
						existing_profile_data.save()

					else:
						zodiac_obj = ChineseZodiac(
							chinese_zodiac=row['Chinese Zodiac'],
							tagline=row['Tagline'],
							description=row['Description'],
							
						)
						zodiac_obj.save()
			elif tab_name == 'element-tab':
				# element_profile_data = FiveElements.objects.all()
				# if element_profile_data:
				# 	messages.warning(request, "Data is already exist.")
				# 	return redirect('profile-database')
				for row in reader:
					try:
						user = request.user.id
						user_obj = User.objects.filter(id = user)
						if not user_obj:
							messages.error(request, f"Invalid user found. Error in line {reader.line_num}.")
							return redirect('profile-database')
					except ValueError:
						messages.error(request, f"User must be an integer. Error in line {reader.line_num}.")
						return redirect('profile-database')

				
					if 'Five Element' not in row:
						messages.error(request,f"five element is missing in csv. Error in line {reader.line_num}.")
						return redirect('profile-database')
					if 'Tagline' not in row:
						messages.error(request,f"tagline is missing in csv. Error in line {reader.line_num}.")
						return redirect('profile-database')
					if 'Description' not in row:
						messages.error(request,f"description is missing in csv. Error in line {reader.line_num}.")
						return redirect('profile-database')
					
					existing_profile_data = FiveElements.objects.filter(element_name=row['Five Element']).first()
					# if existing_profile_data:
					# 	duplicate_count += 1
					# 	messages.warning(request, f"Duplicate data found in line {reader.line_num}.")
					# 	continue

					if existing_profile_data:
						# Update existing record
						existing_profile_data.element_name = row['Five Element']
						existing_profile_data.tagline = row['Tagline']
						existing_profile_data.description = row['Description']
						existing_profile_data.save()

					else:
						elements_obj = FiveElements(
							element_name=row['Five Element'],
							tagline=row['Tagline'],
							description=row['Description'],
							
						)
						elements_obj.save()
			elif tab_name == 'mbti-tab':
				# mbti_profile_data = MBTI.objects.all()
				# if mbti_profile_data:
				# 	messages.warning(request, "Data is already exist.")
				# 	return redirect('profile-database')
				for row in reader:
					try:
						user = request.user.id
						user_obj = User.objects.filter(id = user)
						if not user_obj:
							messages.error(request, f"Invalid user found. Error in line {reader.line_num}.")
							return redirect('profile-database')
					except ValueError:
						messages.error(request, f"User must be an integer. Error in line {reader.line_num}.")
						return redirect('profile-database')

				
					if 'MBTI' not in row:
						messages.error(request,f"mbti is missing in csv. Error in line {reader.line_num}.")
						return redirect('profile-database')
					if 'Tagline' not in row:
						messages.error(request,f"tagline is missing in csv. Error in line {reader.line_num}.")
						return redirect('profile-database')
					if 'Description' not in row:
						messages.error(request,f"description is missing in csv. Error in line {reader.line_num}.")
						return redirect('profile-database')
					

					existing_profile_data = MBTI.objects.filter(mbti_name=row['MBTI']).first()
					# if existing_profile_data:
					# 	duplicate_count += 1
					# 	messages.warning(request, f"Duplicate data found in line {reader.line_num}.")
					# 	continue

					if existing_profile_data:
						# Update existing record
						existing_profile_data.mbti_name = row['MBTI']
						existing_profile_data.tagline = row['Tagline']
						existing_profile_data.description = row['Description']
						existing_profile_data.save()

					else:
						mbti_obj = MBTI(
							mbti_name=row['MBTI'],
							tagline=row['Tagline'],
							description=row['Description'],
							
						)
						mbti_obj.save()
			else:
				messages.error(request, "Invalid tab selected.")
				return redirect('profile-database')

			if duplicate_count > 0:
				messages.error(request, f"{duplicate_count} duplicate record(s) found in CSV.")
				return redirect('profile-database')
			else:
				messages.success(request, "Uploaded successfully")
				return redirect('profile-database')
		messages.success(request, "Something went wrong")
		return redirect('profile-database')
	except Exception as e:
		messages.warning(request, "Something went wrong.Please try again.")
		return redirect('dashboard') 

class EditUserCompatibility(TemplateView):
	template_name = 'edit_user_compatibility.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request,id):
		tab_name = request.GET.get('compatibility')
		print('tab_name====',tab_name)
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()

		'''===========Horoscope============='''
		if tab_name == 'horoscope':
			compatibility_obj = CompatibilityHoroscope.objects.filter(id=id,end_date__isnull=True).first()
			female_value = compatibility_obj.female_horoscope
			male_value = compatibility_obj.male_horoscope

			'''===========Chinese Zodiac============='''
		elif tab_name == 'chinese_zodiac':
			compatibility_obj = CompatibilityChineseZodiac.objects.filter(id=id,end_date__isnull=True).first()
			female_value = compatibility_obj.female_chinese_zodiac
			male_value = compatibility_obj.male_chinese_zodiac
			'''===========Five Element============='''
		elif tab_name == 'five_element':
			compatibility_obj = CompatibilityFiveElements.objects.filter(id=id,end_date__isnull=True).first()
			female_value = compatibility_obj.female_element_name
			male_value = compatibility_obj.male_element_name
			'''===========MBTI============='''
		elif tab_name == 'mbti':
			compatibility_obj = CompatibilityMBTI.objects.filter(id=id,end_date__isnull=True).first()
			female_value = compatibility_obj.female_mbti_name
			male_value = compatibility_obj.male_mbti_name
		return render(request,self.template_name,locals())
	
	def post(self,request,id):
		try:
			tab_name = request.POST.get('compatibility')
			print('tab_name====',tab_name)
			if tab_name == 'horoscope':
				modal_name = CompatibilityHoroscope
				female_modal_field = 'female_horoscope'
				male_modal_field = 'male_horoscope'
			elif tab_name == 'chinese_zodiac':
				modal_name = CompatibilityChineseZodiac
				female_modal_field = 'female_chinese_zodiac'
				male_modal_field = 'male_chinese_zodiac'
			elif tab_name == 'five_element':
				modal_name = CompatibilityFiveElements
				female_modal_field = 'female_element_name'
				male_modal_field = 'male_element_name'
			elif tab_name == 'mbti':
				modal_name = CompatibilityMBTI
				female_modal_field = 'female_mbti_name'
				male_modal_field = 'male_mbti_name'
			form = forms.usercompatibilityform(request.POST)
			if form.is_valid():
				female = form.cleaned_data.get('female')
				male = form.cleaned_data.get('male')
				compatibility_score = form.cleaned_data.get('compatibility_score')
				tagline = form.cleaned_data.get('tagline')
				description = form.cleaned_data.get('description')
				
				# modal_name.objects.filter(id=id).update(modal_field=profile_title,tagline=profile_tagline,description=profile_description)
				
				# Create a dictionary to map field names to values
				update_data = {
					female_modal_field: female,
					male_modal_field: male,
					'compatibility_score':compatibility_score,
					'tagline': tagline,
					'description': description
				}

				# Update the model using **update_data
				modal_name.objects.filter(id=id).update(**update_data)

				messages.success(request, "Updated Succesfully")
				return redirect('user-compatibility')
			else:
				return render(request,self.template_name)
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard')


class UserCompatibility(TemplateView):
	template_name = 'user_compatibility.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		try:
			admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()

			'''===========Horoscope============='''
			horoscope_obj = CompatibilityHoroscope.objects.filter(end_date__isnull = True).order_by('id')
			paginator = Paginator(horoscope_obj, 10)
			all_page_number = request.GET.get('horoscope')
			all_horoscope_obj = paginator.get_page(all_page_number)

			'''===========Chinese Zodiac============='''
			chinese_zodiac_obj = CompatibilityChineseZodiac.objects.filter(end_date__isnull = True).order_by('id')
			paginator = Paginator(chinese_zodiac_obj, 10)
			all_page_number = request.GET.get('chinese_zodiac')
			all_chinese_obj = paginator.get_page(all_page_number)

			'''===========Five Element============='''
			five_elements_obj = CompatibilityFiveElements.objects.filter(end_date__isnull = True).order_by('id')
			paginator = Paginator(five_elements_obj, 10)
			all_page_number = request.GET.get('five_element')
			all_five_element_obj = paginator.get_page(all_page_number)
			
			'''===========MBTI============='''
			mbti_obj = CompatibilityMBTI.objects.filter(end_date__isnull = True).order_by('-id')
			paginator = Paginator(mbti_obj, 10)
			all_page_number = request.GET.get('mbti')
			all_mbti_obj = paginator.get_page(all_page_number)

			return render(request,self.template_name,locals())
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard') 


def importUserCompatibilityDataCSV(request):
	try:
		if request.method == 'POST' and request.FILES['myFileInput']:
			csv_file = request.FILES['myFileInput']
			tab_name = request.POST.get('active_tab')
			print(tab_name)
			decoded_file = csv_file.read().decode('utf-8').splitlines()
			reader = csv.DictReader(decoded_file)
			duplicate_count = 0
			if tab_name == 'horoscope-tab':
				# Delete all existing entries
				CompatibilityHoroscope.objects.all().delete()
				for row in reader:
					try:
						user = request.user.id
						user_obj = User.objects.filter(id = user)
						if not user_obj:
							messages.error(request, f"Invalid user found. Error in line {reader.line_num}.")
							return redirect('user-compatibility')
					except ValueError:
						messages.error(request, f"User must be an integer. Error in line {reader.line_num}.")
						return redirect('user-compatibility')
				
					if 'Female' not in row:
						messages.error(request,f"female is missing in csv. Error in line {reader.line_num}.")
						return redirect('user-compatibility')
					if 'Male' not in row:
						messages.error(request,f"male is missing in csv. Error in line {reader.line_num}.")
						return redirect('user-compatibility')
					if 'Score' not in row:
						messages.error(request,f"score is missing in csv. Error in line {reader.line_num}.")
						return redirect('user-compatibility')
					if 'Tagline' not in row:
						messages.error(request,f"tagline is missing in csv. Error in line {reader.line_num}.")
						return redirect('user-compatibility')
					if 'Description' not in row:
						messages.error(request,f"description is missing in csv. Error in line {reader.line_num}.")
						return redirect('user-compatibility')
					
					existing_profile_data = CompatibilityHoroscope.objects.filter(
						female_horoscope=row['Female'],
						male_horoscope=row['Male'],
						compatibility_score=row['Score'],
						tagline=row['Tagline'],
						description=row['Description'],
						end_date__isnull=True,
					).first()

					if existing_profile_data:
						duplicate_count += 1
						messages.warning(request, f"Duplicate data found in line {reader.line_num}.")
						continue


					horoscope_obj = CompatibilityHoroscope(
						female_horoscope=row['Female'],
						male_horoscope=row['Male'],
						compatibility_score=row['Score'],
						tagline=row['Tagline'],
						description=row['Description'],
						
					)
					horoscope_obj.save()
			elif tab_name == 'zodiac-tab':
				# Delete all existing entries
				CompatibilityChineseZodiac.objects.all().delete()
				for row in reader:
					try:
						user = request.user.id
						user_obj = User.objects.filter(id = user)
						if not user_obj:
							messages.error(request, f"Invalid user found. Error in line {reader.line_num}.")
							return redirect('user-compatibility')
					except ValueError:
						messages.error(request, f"User must be an integer. Error in line {reader.line_num}.")
						return redirect('profile-database')
				
					if 'Female' not in row:
						messages.error(request,f"female is missing in csv. Error in line {reader.line_num}.")
						return redirect('user-compatibility')
					if 'Male' not in row:
						messages.error(request,f"male is missing in csv. Error in line {reader.line_num}.")
						return redirect('user-compatibility')
					if 'Score' not in row:
						messages.error(request,f"score is missing in csv. Error in line {reader.line_num}.")
						return redirect('user-compatibility')
					if 'Tagline' not in row:
						messages.error(request,f"tagline is missing in csv. Error in line {reader.line_num}.")
						return redirect('user-compatibility')
					if 'Description' not in row:
						messages.error(request,f"description is missing in csv. Error in line {reader.line_num}.")
						return redirect('user-compatibility')
					
					existing_profile_data = CompatibilityChineseZodiac.objects.filter(
						female_chinese_zodiac=row['Female'],
						male_chinese_zodiac=row['Male'],
						compatibility_score=row['Score'],
						tagline=row['Tagline'],
						description=row['Description'],
						end_date__isnull=True,
					).first()
					if existing_profile_data:
						duplicate_count += 1
						messages.warning(request, f"Duplicate data found in line {reader.line_num}.")
						continue

					zodiac_obj = CompatibilityChineseZodiac(
						female_chinese_zodiac=row['Female'],
						male_chinese_zodiac=row['Male'],
						compatibility_score=row['Score'],
						tagline=row['Tagline'],
						description=row['Description'],
						
					)
					zodiac_obj.save()
			elif tab_name == 'element-tab':
				# Delete all existing entries
				CompatibilityFiveElements.objects.all().delete()
				for row in reader:
					try:
						user = request.user.id
						user_obj = User.objects.filter(id = user)
						if not user_obj:
							messages.error(request, f"Invalid user found. Error in line {reader.line_num}.")
							return redirect('user-compatibility')
					except ValueError:
						messages.error(request, f"User must be an integer. Error in line {reader.line_num}.")
						return redirect('user-compatibility')
				
					if 'Female' not in row:
						messages.error(request,f"female is missing in csv. Error in line {reader.line_num}.")
						return redirect('user-compatibility')
					if 'Male' not in row:
						messages.error(request,f"male is missing in csv. Error in line {reader.line_num}.")
						return redirect('user-compatibility')
					if 'Score' not in row:
						messages.error(request,f"score is missing in csv. Error in line {reader.line_num}.")
						return redirect('user-compatibility')
					if 'Tagline' not in row:
						messages.error(request,f"tagline is missing in csv. Error in line {reader.line_num}.")
						return redirect('user-compatibility')
					if 'Description' not in row:
						messages.error(request,f"description is missing in csv. Error in line {reader.line_num}.")
						return redirect('user-compatibility')
					

					existing_profile_data = CompatibilityFiveElements.objects.filter(
						female_element_name=row['Female'],
						male_element_name=row['Male'],
						compatibility_score=row['Score'],
						tagline=row['Tagline'],
						description=row['Description'],
						end_date__isnull=True,
					).first()
					if existing_profile_data:
						duplicate_count += 1
						messages.warning(request, f"Duplicate data found in line {reader.line_num}.")
						continue


					elements_obj = CompatibilityFiveElements(
						female_element_name=row['Female'],
						male_element_name=row['Male'],
						compatibility_score=row['Score'],
						tagline=row['Tagline'],
						description=row['Description'],
						
					)
					elements_obj.save()
			elif tab_name == 'mbti-tab':
				# Delete all existing entries
				CompatibilityMBTI.objects.all().delete()
				for row in reader:
					try:
						user = request.user.id
						user_obj = User.objects.filter(id = user)
						if not user_obj:
							messages.error(request, f"Invalid user found. Error in line {reader.line_num}.")
							return redirect('user-compatibility')
					except ValueError:
						messages.error(request, f"User must be an integer. Error in line {reader.line_num}.")
						return redirect('user-compatibility')
				
					if 'Female' not in row:
						messages.error(request,f"female is missing in csv. Error in line {reader.line_num}.")
						return redirect('user-compatibility')
					if 'Male' not in row:
						messages.error(request,f"male is missing in csv. Error in line {reader.line_num}.")
						return redirect('user-compatibility')
					if 'Score' not in row:
						messages.error(request,f"score is missing in csv. Error in line {reader.line_num}.")
						return redirect('user-compatibility')
					if 'Tagline' not in row:
						messages.error(request,f"tagline is missing in csv. Error in line {reader.line_num}.")
						return redirect('user-compatibility')
					if 'Description' not in row:
						messages.error(request,f"description is missing in csv. Error in line {reader.line_num}.")
						return redirect('user-compatibility')
					
					existing_profile_data = CompatibilityMBTI.objects.filter(
						female_mbti_name=row['Female'],
						male_mbti_name=row['Male'],
						compatibility_score=row['Score'],
						tagline=row['Tagline'],
						description=row['Description'],
						end_date__isnull=True,
					).first()
					if existing_profile_data:
						duplicate_count += 1
						messages.warning(request, f"Duplicate data found in line {reader.line_num}.")
						continue


					mbti_obj = CompatibilityMBTI(
						female_mbti_name=row['Female'],
						male_mbti_name=row['Male'],
						compatibility_score=row['Score'],
						tagline=row['Tagline'],
						description=row['Description'],
						
					)
					mbti_obj.save()
			else:
				messages.error(request, "Invalid tab selected.")
				return redirect('user-compatibility')

			if duplicate_count > 0:
				messages.error(request, f"{duplicate_count} duplicate record(s) found in CSV.")
				return redirect('user-compatibility')
			else:
				messages.success(request, "Uploaded successfully")
				return redirect('user-compatibility')
		else:
			messages.error(request, "Something went wrong")
			return redirect('user-compatibility')
	except Exception as e:
		messages.warning(request, "Something went wrong.Please try again.")
		return redirect('dashboard')



class EditAdvisorsCompatibility(TemplateView):
	template_name = 'edit_advisor_compatibility.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request,id):
		tab_name = request.GET.get('advisor')
		print('tab_name',tab_name)
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		'''===========Horoscope============='''
		if tab_name == 'horoscope':
			advisor_obj = AdvisorCompatibilityHoroscope.objects.filter(id=id,end_date__isnull=True).first()
			tagline = advisor_obj.tagline
			'''===========MBTI============='''
		elif tab_name == 'mbti':
			advisor_obj = AdvisorCompatibilityMBTI.objects.filter(id=id,end_date__isnull=True).first()
			tagline = advisor_obj.tagline_for_relationship
		return render(request,self.template_name,locals())
	
	def post(self,request,id):
		try:
			tab_name = request.POST.get('advisor_tab')
			print('tab_name====',tab_name)
			if tab_name == 'horoscope':
				modal_name = AdvisorCompatibilityHoroscope
				modal_field = 'tagline'
			elif tab_name == 'mbti':
				modal_name = AdvisorCompatibilityMBTI
				modal_field = 'tagline_for_relationship'
			form = forms.advisorscompatibilityform(request.POST)
			if form.is_valid():
				advisor = form.cleaned_data.get('advisor')
				user = form.cleaned_data.get('user')
				compatibility_score = form.cleaned_data.get('compatibility_score')
				tagline = form.cleaned_data.get('tagline')
				
				# modal_name.objects.filter(id=id).update(modal_field=profile_title,tagline=profile_tagline,description=profile_description)
				
				# Create a dictionary to map field names to values
				update_data = {
					'advisor': advisor,
					'user': user,
					'compatibility_score': compatibility_score,
					modal_field: tagline
				}

				# Update the model using **update_data
				modal_name.objects.filter(id=id).update(**update_data)

				messages.success(request, "Updated Succesfully")
				return redirect('advisor-compatibility')
			else:
				return render(request,self.template_name)
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard')

class AdvisorsCompatibility(TemplateView):
	template_name = 'advisors_compatibility.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		try:
			admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()

			'''===========Horoscope============='''
			horoscope_obj = AdvisorCompatibilityHoroscope.objects.filter(end_date__isnull = True).order_by('id')
			paginator = Paginator(horoscope_obj, 10)
			all_page_number = request.GET.get('horoscope')
			all_horoscope_obj = paginator.get_page(all_page_number)

			'''===========MBTI============='''
			mbti_obj = AdvisorCompatibilityMBTI.objects.filter(end_date__isnull = True).order_by('id')
			paginator = Paginator(mbti_obj, 10)
			all_page_number = request.GET.get('mbti')
			all_mbti_obj = paginator.get_page(all_page_number)
			return render(request,self.template_name,locals())
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard') 

def importAdvisorCompatibilityCSV(request):
	try:
		if request.method == 'POST' and request.FILES['myFileInput']:
			csv_file = request.FILES['myFileInput']
			tab_name = request.POST.get('active_tab')
			print(tab_name)
			decoded_file = csv_file.read().decode('utf-8').splitlines()
			reader = csv.DictReader(decoded_file)
			duplicate_count = 0
			if tab_name == 'horoscope-tab':
				# Delete all existing entries
				AdvisorCompatibilityHoroscope.objects.all().delete()
				for row in reader:
					try:
						user = request.user.id
						user_obj = User.objects.filter(id = user)
						if not user_obj:
							messages.error(request, f"Invalid user found. Error in line {reader.line_num}.")
							return redirect('advisor-compatibility')
					except ValueError:
						messages.error(request, f"User must be an integer. Error in line {reader.line_num}.")
						return redirect('advisor-compatibility')

				
					if 'Advisor' not in row:
						messages.error(request,f"Advisor is missing in csv. Error in line {reader.line_num}.")
						return redirect('advisor-compatibility')
					if 'User' not in row:
						messages.error(request,f"User is missing in csv. Error in line {reader.line_num}.")
						return redirect('advisor-compatibility')
					if 'Score' not in row:
						messages.error(request,f"score is missing in csv. Error in line {reader.line_num}.")
						return redirect('advisor-compatibility')
					if 'Tagline' not in row:
						messages.error(request,f"tagline is missing in csv. Error in line {reader.line_num}.")
						return redirect('advisor-compatibility')
					
					existing_profile_data = AdvisorCompatibilityHoroscope.objects.filter(
						advisor=row['Advisor'],
						user=row['User'],
						compatibility_score=row['Score'],
						tagline=row['Tagline'],
						end_date__isnull=True,
					).first()
					if existing_profile_data:
						duplicate_count += 1
						messages.warning(request, f"Duplicate data found in line {reader.line_num}.")
						continue


					horoscope_obj = AdvisorCompatibilityHoroscope(
						advisor=row['Advisor'],
						user=row['User'],
						compatibility_score=row['Score'],
						tagline=row['Tagline'],
						
					)
					horoscope_obj.save()
			elif tab_name == 'mbti-tab':
				# Delete all existing entries
				AdvisorCompatibilityMBTI.objects.all().delete()
				for row in reader:
					try:
						user = request.user.id
						user_obj = User.objects.filter(id = user)
						if not user_obj:
							messages.error(request, f"Invalid user found. Error in line {reader.line_num}.")
							return redirect('advisor-compatibility')
					except ValueError:
						messages.error(request, f"User must be an integer. Error in line {reader.line_num}.")
						return redirect('advisor-compatibility')

				
					if 'Advisor' not in row:
						messages.error(request,f"Advisor is missing in csv. Error in line {reader.line_num}.")
						return redirect('advisor-compatibility')
					if 'User' not in row:
						messages.error(request,f"User is missing in csv. Error in line {reader.line_num}.")
						return redirect('advisor-compatibility')
					if 'Score' not in row:
						messages.error(request,f"score is missing in csv. Error in line {reader.line_num}.")
						return redirect('advisor-compatibility')
					if 'Tag Line for relationship' not in row:
						messages.error(request,f"tagline is missing in csv. Error in line {reader.line_num}.")
						return redirect('advisor-compatibility')
					
					existing_profile_data = AdvisorCompatibilityMBTI.objects.filter(
						advisor=row['Advisor'],
						user=row['User'],
						compatibility_score=row['Score'],
						tagline_for_relationship=row['Tag Line for relationship'],
						end_date__isnull=True,
					).first()
					if existing_profile_data:
						duplicate_count += 1
						messages.warning(request, f"Duplicate data found in line {reader.line_num}.")
						continue

					
					mbti_obj = AdvisorCompatibilityMBTI(
						advisor=row['Advisor'],
						user=row['User'],
						compatibility_score=row['Score'],
						tagline_for_relationship=row['Tag Line for relationship'],
						
					)
					mbti_obj.save()
			else:
				messages.error(request, "Invalid tab selected.")
				return redirect('advisor-compatibility')

			if duplicate_count > 0:
				messages.error(request, f"{duplicate_count} duplicate record(s) found in CSV.")
				return redirect('advisor-compatibility')
			else:
				messages.success(request, "Uploaded successfully")
				return redirect('advisor-compatibility')
		messages.success(request, "Something went wrong")
		return redirect('advisor-compatibility')
	except Exception as e:
		messages.warning(request, "Something went wrong.Please try again.")
		return redirect('dashboard')



class AdminProfile(TemplateView):
	template_name = 'admin_profile.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		try:
			admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
			return render(request,self.template_name,locals())
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard') 
		
	def post(self,request):
		try:
			form = forms.adminprofile_form(request.POST)
			if form.is_valid():
				first_name = form.cleaned_data.get('first_name')
				last_name = form.cleaned_data.get('last_name')
				email = form.cleaned_data.get('email')
				phone_number = form.cleaned_data.get('phone_number')
				address = form.cleaned_data.get('address')
				SuperAdmin.objects.filter(user=request.user.id).update(firstName=first_name,lastName=last_name,email=email,phoneNumber=phone_number,address=address)
				if request.FILES.get('avatar'):
					fileUrl=uploadTheImages(request.FILES.get('avatar'))
					fileUrl='/'+fileUrl
					SuperAdmin.objects.filter(user=request.user.id).update(image=str(fileUrl))
				messages.success(request, "Update Succesfully")
				return redirect('admin-profile')
			else:
				return render(request,self.template_name)
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard')


class ContentPageListing(TemplateView):
	template_name = 'content_page_list.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		try:
			admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
			content_obj = ContentManagement.objects.filter(end_date__isnull = True)
			return render(request,self.template_name,locals())
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard') 
		

class UpdateContentPage(TemplateView):
	template_name = 'update_content_page.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request,id):
		try:
			admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
			content_obj = ContentManagement.objects.filter(id = id).first()
			return render(request,self.template_name,locals())
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard') 
		
	def post(self,request,id):
		try:
			form = forms.updatecontent_form(request.POST)
			if form.is_valid():
				content = form.cleaned_data.get('content')
				ContentManagement.objects.filter(id=id).update(text=content)
				messages.success(request, "Update Succesfully")
				return redirect('content-page-listing')
			else:
				return render(request,self.template_name)
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard')


class RefundMoneyList(TemplateView):
	template_name = 'refund_money_list.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		data_obj = AdminRefundRequest.objects.filter(end_date__isnull = True).order_by('-id')
		search_post = request.GET.get('search')
		refund_date = request.GET.get('refund_date')
		time = "11:59:59"
		lookups = Q()

		if refund_date:
			date_string = str(refund_date) 
			refund_date_time = make_aware(datetime.fromisoformat(date_string))
			lookups.add(Q(created_at__date=refund_date_time), Q.AND)

		if search_post:
			lookups.add(Q(booking__fortune_teller__first_name__icontains=search_post)|Q(booking__fortune_teller__last_name__icontains=search_post)|Q(booking__seer_user__first_name__icontains=search_post)|Q(booking__seer_user__last_name__icontains=search_post)|Q(booking__service__service_name__icontains=search_post), Q.AND)


		data_obj = AdminRefundRequest.objects.filter(lookups,end_date__isnull = True).order_by('-id')

		paginator = Paginator(data_obj, 10)
		page_number = request.GET.get('page')
		refund_obj = paginator.get_page(page_number)

		return render(request,self.template_name,locals())


class RefundMoneyDetails(TemplateView):
	template_name = 'refund_money_details.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request,id):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		data_obj = AdminRefundRequest.objects.filter(end_date__isnull = True,id=id).first()
		return render(request,self.template_name,locals())
	@method_decorator(login_required(login_url='/'))
	def post(self, request, id):
		# try:
			data_obj = AdminRefundRequest.objects.filter(end_date__isnull=True, id=id).first()
			refund_type = request.POST.get('refund_type')
			refund_amount = data_obj.refund_amount
			appointment_obj = FortuneAppointmentBook.objects.filter(id=data_obj.appointment.id).first()
			if refund_type == 'wallet':
				if data_obj.status == 'Pending':
					user_wallet = SeerUserWallet.objects.filter(seer_user=appointment_obj.seer_user).first()
					new_amount = user_wallet.amount + refund_amount
					user_wallet.amount = new_amount
					user_wallet.save()
					data_obj.status = 'Completed'
					data_obj.date_processed = datetime.now()
					data_obj.save()
					SeerUserTranscation.objects.create(transcation_id=generateTranscationsId(), transcation_type="refund", booking=appointment_obj, seer_user=appointment_obj.seer_user, amount=refund_amount, payment_mode="wallet")
					SeerUserNotifications.objects.create(message='Your refund for appointment ID:' + appointment_obj.appointment_id + ' has been processed. Refund amount: $' + str(refund_amount), notification_type="refund", seer_user=appointment_obj.seer_user)
					messages.success(request, "Refund to Wallet Successful")
				else:
					messages.error(request, "Already Refunded")
			elif refund_type == 'account':
				seer_user_trans = SeerUserTranscation.objects.filter(booking=appointment_obj).first()
				if seer_user_trans.charge_id:
					if data_obj.status == 'Pending':
						exact_amount = refund_amount * 100
						stripe.api_key = settings.STRIPE_SECRET_KEY
						stripe.Refund.create(charge=seer_user_trans.charge_id,amount=exact_amount)
						data_obj.status = 'Completed'
						data_obj.date_processed = datetime.now()
						data_obj.save()
						SeerUserTranscation.objects.create(transcation_id=generateTranscationsId(), transcation_type="refund", booking=appointment_obj, seer_user=appointment_obj.seer_user, amount=refund_amount, payment_mode="wallet")
						SeerUserNotifications.objects.create(message='Your refund for appointment ID:' + appointment_obj.appointment_id + ' has been processed. Refund amount: $' + str(refund_amount), notification_type="refund", seer_user=appointment_obj.seer_user)
						messages.success(request, "Refund to Account Successful")
					else:
						messages.error(request, "Already Refunded")
				else:
						messages.error(request, "Charge ID is not provided. Cannot process the refund. Proceed with wallet.")
			else:
				messages.error(request, "Invalid Refund Type")
			
			return redirect('refund-money-list')
		# except Exception as e:
			# messages.error(request, "Something Went Wrong")
			# return redirect('refund-money-list')


def ExportCSVRefund(request):
	queryset = SeerUserTranscation.objects.filter(transcation_type='refund')
	if not queryset:
		messages.warning(request, "No data found")
		return redirect('/refund-money-list')
	response = HttpResponse(content_type='text/csv')
	response['Content-Disposition'] = 'attachment; filename="refund.csv"'
	writer = csv.writer(response)
	writer.writerow(['Appointment Id', 'Fortuneteller Name', 'Customer Name','Appointment Date','Appointment Time','Service Name','Refund Amount', 'Refund Date', 'Refund Status'])

	# Write the data rows
	for item in queryset:
		writer.writerow([item.booking.appointment_id,
		item.booking.fortune_teller.first_name+' '+item.booking.fortune_teller.last_name,
		item.booking.seer_user.first_name+' '+item.booking.seer_user.last_name,
		item.booking.appointment_date,
		item.booking.appointment_time,
		item.booking.service.service_name,
		'$ '+ str(item.booking.price),
		item.booking.created_at,
		'Completed'])
	return response


class AdminLogout(TemplateView):
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		logout(request)
		messages.success(request, "Logout Succesfully")
		return redirect('/')
	

class AdminResetPassword(TemplateView):
	template_name = 'admin_reset_password.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		return render(request,self.template_name,locals())

	def post(self,request):
		try:
			form = forms.change_password_form(request.POST)
			if form.is_valid():
				password = request.POST.get("confirmPassword")
				user     = User.objects.get(email=request.user.email)
				user.set_password(password)
				user.save()
				logout(request)
				messages.info(request, 'You have successfully reset your password')
				return redirect('/')
			else:
				return render(request, 'admin_reset_password.html', {'form': form})
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard')   


class CancellationCharge(TemplateView):
	template_name = 'cancellation_charge.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		general_obj =  GeneralSettings.objects.all().first()
		return render(request,self.template_name,locals())
	
	def post(self,request):
		form = forms.generalsettingform(request.POST)
		if form.is_valid():
			cancellation_charge = form.cleaned_data.get('cancellation_charge')
			refer_friend_off = form.cleaned_data.get('refer_friend_off')
			commission_percentage = form.cleaned_data.get('commission_percentage')

			check_data = GeneralSettings.objects.all().first()
			if check_data:
				GeneralSettings.objects.filter(id=check_data.id).update(cancellation_charge = cancellation_charge,refer_friend_off=refer_friend_off,commission_percentage=commission_percentage)
			else:
				GeneralSettings.objects.create(cancellation_charge=cancellation_charge,refer_friend_off=refer_friend_off)
			messages.success(request, "Charges added succesfully")	
			return redirect('/cancellation-charge')
		else:
			return render(request,'cancellation_charge.html',{'form':form})
			



class HelpSupportList(TemplateView):
	template_name = 'help_support_list.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		try:
			admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
			total = HelpSupport.objects.all().count()
			resolved = HelpSupport.objects.filter(status = True).count()
			pending = HelpSupport.objects.filter(status = False).count()
			help_obj = HelpSupport.objects.all().order_by('-id')
			paginator = Paginator(help_obj, 10)
			page_number = request.GET.get('page')
			sup_obj = paginator.get_page(page_number)
			return render(request,self.template_name,locals())
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('dashboard') 
	


class HelpSupportView(TemplateView):
	template_name = 'help_support_view.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request,id):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		sup_obj =  HelpSupport.objects.filter(id=id).first()
		return render(request,self.template_name,locals())



class HelpSupportSend(TemplateView):
	template_name = 'help_support_send.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request,id):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		help =  HelpSupport.objects.filter(id=id).first()
		return render(request,self.template_name,locals())
	
	def post(self,request,id):
			form = forms.sendsupportform(request.POST)
			if form.is_valid():
				email =  form.cleaned_data.get('email')
				subject = form.cleaned_data.get('subject')
				reply = form.cleaned_data.get('reply')
				html_message = render_to_string('support_email.html', {'reply_text': reply,'email':email,'subject':subject})
				plain_message = html_message
				from_email = settings.EMAIL_HOST_USER
				to = email
				mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message)
				HelpSupport.objects.filter(id=id).update(reply=reply,reply_date = datetime.now(),status=True)
				help_obj = HelpSupport.objects.filter(id=id).first()
				if help_obj.seer_user:
					registration_id = help_obj.seer_user.fcm_token
					server_key = str(settings.FIREBASE_SERVER_KEY)
					if help_obj.seer_user.device_type == 'Android':

						data_message = {		'type': 'help_support',
												'title' : 'HELP & SUPPORT',
												"message" : 'You recived a mail for help and support from seer team.'
											}
						
						result = FCMNotification(api_key=server_key).notify_single_device(registration_id=registration_id,  data_message=data_message)
					if help_obj.seer_user.device_type == 'Ios':
						message_title = 'HELP & SUPPORT',
						message_body =  'You recived a mail for help and support from seer team.'
						data_message = {		'type': 'help_support',
												'title' : 'HELP & SUPPORT',
												"message" : 'You recived a mail for help and support from seer team.'
											}
						result = FCMNotification(api_key=server_key).notify_single_device(registration_id=registration_id, message_title=message_title, 
						message_body=message_body, data_message=data_message)
				else:
					registration_id = help_obj.fortune_teller.fcm_token
					server_key = str(settings.FIREBASE_SERVER_KEY)
					if help_obj.fortune_teller.device_type == 'Android':

						data_message = {		'type': 'help_support',
												'title' : 'HELP & SUPPORT',
												"message" : 'You recived a mail for help and support from seer team.'
											}
						
						result = FCMNotification(api_key=server_key).notify_single_device(registration_id=registration_id,  data_message=data_message)
					if help_obj.fortune_teller.device_type == 'Ios':
						message_title = 'HELP & SUPPORT',
						message_body =  'You recived a mail for help and support from seer team.'
						data_message = {		'type': 'help_support',
												'title' : 'HELP & SUPPORT',
												"message" : 'You recived a mail for help and support from seer team.'
											}
						result = FCMNotification(api_key=server_key).notify_single_device(registration_id=registration_id, message_title=message_title, 
						message_body=message_body, data_message=data_message)

				messages.success(request, "send successfully")
				return redirect('/help-support-list')
			else:
				return render(request,'help_support_send.html',{'form':form})

class LifestyleQuestionList(TemplateView):
	template_name = 'life_question_list.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		data_obj =  LifestyleQuestion.objects.filter(end_date__isnull = True)
		search_post = request.GET.get('search')
		lookups = Q()
		if search_post:
			lookups.add(Q(question_title__icontains=search_post), Q.AND)
		data_obj = LifestyleQuestion.objects.filter(lookups,end_date__isnull = True).order_by('-id')
		paginator = Paginator(data_obj, 10)
		page_number = request.GET.get('page')
		ques_obj = paginator.get_page(page_number)
		return render(request,self.template_name,locals())


class AddLifestyleQuestion(TemplateView):
	template_name = 'add_lifestyle_question.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request,id):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		return render(request,self.template_name,locals())
	
	def post(self,request):
		form = forms.addlifestyleform(request.POST)
		if form.is_valid():
			lifestyle_question = form.cleaned_data.get('lifestyle_question')
			option = form.cleaned_data.get('option')

			lifestyle_obj = LifestyleQuestion.objects.create(question_title=lifestyle_question)
			LifestyleOptions.objects.create(lifestyle_question = lifestyle_obj,option=option)
			if request.POST.get('hidden-field'):
				hidden_value = request.POST.get('hidden-field')
				rows_data = json.loads(hidden_value)
				for row in rows_data:
					option = row['option']
					LifestyleOptions.objects.create(lifestyle_question=lifestyle_obj,option=option)
			messages.success(request, "Question Added Successfully")
			return redirect('/lifestyle-questions-list')
		else:
			return render(request,'add_lifestyle_question.html',{'form':form})

class EditLifestyleQuestion(TemplateView):
	template_name = 'edit_lifestyle_question.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request,id):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		question_obj = LifestyleQuestion.objects.filter(id=id).first()
		option_obj_first = LifestyleOptions.objects.filter(lifestyle_question = id).first()
		option_obj = LifestyleOptions.objects.filter(lifestyle_question=id)[1:]
		return render(request,self.template_name,locals())
	
	def post(self,request,id):
		form = forms.addlifestyleform(request.POST)
		if form.is_valid():
			lifestyle_question = form.cleaned_data.get('lifestyle_question')
			option_data = form.cleaned_data.get('option')
			lifestyle_obj = LifestyleQuestion.objects.filter(id=id).update(question_title=lifestyle_question)
			lifestyle_main =  LifestyleQuestion.objects.filter(id=id).first()
			options_obj = LifestyleOptions.objects.filter(lifestyle_question=lifestyle_main.id)
			for option_all in options_obj:
				option_all.delete()
			LifestyleOptions.objects.create(lifestyle_question = lifestyle_main,option=option_data)
			if request.POST.get('hidden-field-two'):
				variation_obj = LifestyleOptions.objects.filter(lifestyle_question=id)[1:]
				for var in variation_obj:
					var.delete()
				hidden_value = request.POST.get('hidden-field-two').split(',')
				for row in hidden_value:
					option_data = row
					LifestyleOptions.objects.create(lifestyle_question=lifestyle_main,option=option_data)
			messages.success(request, "Question Updated Successfully")
			return redirect('/lifestyle-questions-list')
		else:
			return render(request,'edit_lifestyle_question.html',{'form':form})

def RemoveLifestyleOption(request):
	text = request.GET.get('option_id')
	mbit_obj = LifestyleOptions.objects.filter(id=text).first()
	mbit_obj.delete()
	return HttpResponse('success')

class MbtiQuestionList(TemplateView):
	template_name = 'mbit_question_list.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		data_obj =  MbtiQuestion.objects.filter(end_date__isnull = True).order_by('-id')
		search_post = request.GET.get('search')
		lookups = Q()
		if search_post:
			lookups.add(Q(question_title__icontains=search_post), Q.AND)
		data_obj = MbtiQuestion.objects.filter(lookups,end_date__isnull = True).order_by('-id')
		paginator = Paginator(data_obj, 10)
		page_number = request.GET.get('page')
		ques_obj = paginator.get_page(page_number)
		return render(request,self.template_name,locals())


class AddMbtiQuestion(TemplateView):
	template_name = 'add_mbit_question.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		return render(request,self.template_name,locals())

	@method_decorator(login_required(login_url='/'))
	def post(self,request):
		form = forms.addMbitform(request.POST)
		if form.is_valid():
			mbit_question_data = form.cleaned_data.get('mbit_question')
			option = form.cleaned_data.get('option')
			mbit_obj = MbtiQuestion.objects.create(question_title=mbit_question_data)
			MbtiOptions.objects.create(mbti_question = mbit_obj,option=option)
			if request.POST.get('hidden-field'):
				hidden_value = request.POST.get('hidden-field')
				rows_data = json.loads(hidden_value)
				for row in rows_data:
					option = row['option']
					MbtiOptions.objects.create(mbti_question=mbit_obj,option=option)
			messages.success(request, "Question Added Successfully")
			return redirect('/mbit-questions-list')
		else:
			return render(request,'add_mbit_question.html',{'form':form})

class EditMbtiQuestion(TemplateView):
	template_name = 'edit_mbti_question.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request,id):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		question_obj = MbtiQuestion.objects.filter(id=id).first()
		option_obj_first = MbtiOptions.objects.filter(mbti_question = id).first()
		option_obj = MbtiOptions.objects.filter(mbti_question=id)[1:]
		return render(request,self.template_name,locals())
	
	def post(self,request,id):
		form = forms.addMbitform(request.POST)
		if form.is_valid():
			mbit_question_data = form.cleaned_data.get('mbit_question')
			option_data = form.cleaned_data.get('option')

			mbti_obj = MbtiQuestion.objects.filter(id=id).update(question_title=mbit_question_data)

			mbti_main =  MbtiQuestion.objects.filter(id=id).first()

			options_obj = MbtiOptions.objects.filter(mbti_question=mbti_main.id)
			for option_all in options_obj:
				option_all.delete()

			MbtiOptions.objects.create(mbti_question = mbti_main,option=option_data)
			
			if request.POST.get('hidden-field-two'):
				variation_obj = MbtiOptions.objects.filter(mbti_question=id)[1:]
				for var in variation_obj:
					var.delete()
				hidden_value = request.POST.get('hidden-field-two').split(',')
				for row in hidden_value:
					option_data = row
					MbtiOptions.objects.create(mbti_question=mbti_main,option=option_data)
			messages.success(request, "Question Updated Successfully")
			return redirect('/mbti-questions-list')
		else:
			return render(request,'edit_mbti_question.html',{'form':form})


	
def RemoveMbitOption(request):
	text = request.GET.get('option_id')
	mbit_obj = MbtiOptions.objects.filter(id=text).first()
	mbit_obj.delete()
	return HttpResponse('success')


class AdminNotificationsList(TemplateView):
	template_name = 'admin_notifications.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()

		all_notify = AdminNotifications.objects.filter(end_date__isnull = True).order_by('-id')
		paginator = Paginator(all_notify, 10)
		all_page_number = request.GET.get('all_page')
		all_notify_obj = paginator.get_page(all_page_number)

		read_notify = AdminNotifications.objects.filter(is_read=1,end_date__isnull = True).order_by('-id')
		paginator = Paginator(read_notify, 10)
		read_page_number = request.GET.get('read_page')
		read_notify_obj = paginator.get_page(read_page_number)

		unread_notify = AdminNotifications.objects.filter(is_read = 0,end_date__isnull = True).order_by('-id')
		paginator = Paginator(unread_notify, 10)
		unread_page_number = request.GET.get('unread_page')
		unread_notify_obj = paginator.get_page(unread_page_number)


		return render(request,self.template_name,locals())


class ReadAllNotifications(View):
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		notify_obj = AdminNotifications.objects.filter(is_read = 0,end_date__isnull = True)
		for notify in notify_obj:
			notify.is_read = 1
			notify.save()
		messages.success(request,'All notifications readed successfully')
		return redirect('/admin-notifications')

class FaqListing(TemplateView):
	template_name = 'faq_listing.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		data_obj = Faq.objects.filter(end_date__isnull = True).order_by('-id')
		paginator = Paginator(data_obj, 10)
		page_number = request.GET.get('page')
		faq_obj = paginator.get_page(page_number)
		return render(request,self.template_name,locals())



class AddFaq(TemplateView):
	template_name = 'add_faq.html'
	@method_decorator(login_required(login_url='/'))
	def post(self,request):
		form = forms.addfaqform(request.POST)
		if form.is_valid():
			title = form.cleaned_data.get('title')
			content = form.cleaned_data.get('content')
			type = form.cleaned_data.get('type')
			Faq.objects.create(title=title,content=content,type=type)
			messages.success(request, 'Created Successfully')
			return redirect('/faq-listing')
		else:
			return render(request,'add_faq.html')



class EditFaq(TemplateView):
	template_name = 'edit_faq.html'
	@method_decorator(login_required(login_url='/'))
	def get(self,request,id):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		faq_obj = Faq.objects.filter(id=id,end_date__isnull = True).first()
		return render(request,self.template_name,locals())
	

	def post(self,request,id):
		form = forms.addfaqform(request.POST)
		if form.is_valid():
			title = form.cleaned_data.get('title')
			content = form.cleaned_data.get('content')
			type = form.cleaned_data.get('type')
			Faq.objects.filter(id=id).update(title=title,content=content,type=type)
			messages.success(request, 'Updated Successfully')
			return redirect('/faq-listing')
		else:
			return render(request,'edit_faq.html')


class DeleteFaq(View):
	@method_decorator(login_required(login_url='/'))
	def get(self,request,id):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		Faq.objects.filter(id=id).update(end_date=datetime.now())
		messages.success(request, 'Faq Deleted Successfully')
		return redirect('/faq-listing')


class UserReports(TemplateView):
	template_name = 'user_reports.html'
	@method_decorator(login_required(login_url='/'))
	def get (self,request):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		data_obj = (
			FortuneAppointmentBook.objects
			.values('seer_user__id','seer_user__first_name','seer_user__last_name','seer_user__email','seer_user__primary_image','seer_user__created_at','seer_user__status')
			.annotate(total_appointments=Count('seer_user'))
			.order_by('seer_user')
		)
		search_post = request.GET.get('search')
		lookups = Q()
		if search_post:
			lookups.add(Q(seer_user__first_name=search_post)|Q(seer_user__last_name=search_post)|Q(seer_user__email=search_post), Q.AND)
		data_obj = (
			FortuneAppointmentBook.objects.filter(lookups)
			.values('seer_user__id','seer_user__first_name','seer_user__last_name','seer_user__email','seer_user__primary_image','seer_user__created_at','seer_user__status')
			.annotate(total_appointments=Count('seer_user'))
			.order_by('seer_user')
		)
		paginator = Paginator(data_obj, 10)
		page_number = request.GET.get('page')
		user_appointments = paginator.get_page(page_number)
		return render(request,self.template_name,locals())




class ExportUserCsvReport(View):
	def get(self,request):
		queryset = (
			FortuneAppointmentBook.objects
			.values('seer_user__id','seer_user__first_name','seer_user__last_name','seer_user__email','seer_user__primary_image','seer_user__created_at','seer_user__status')
			.annotate(total_appointments=Count('seer_user'))
			.order_by('seer_user')
		)
		response = HttpResponse(content_type='text/csv')
		response['Content-Disposition'] = 'attachment; filename="user_report.csv"'
		writer = csv.writer(response)
		writer.writerow(['User Id', 'User Name', 'User Email' ,'User Image', 'User Created Date','User Status','Booked Appointments'])

		# Write the data rows
		for item in queryset:
			writer.writerow([item['seer_user__id'], item['seer_user__first_name'] + ' ' + item['seer_user__last_name'], item['seer_user__email'] ,item['seer_user__primary_image'], item['seer_user__created_at'], item['seer_user__status'], item['total_appointments']])

		return response


class ViewUserReport(TemplateView):
	template_name = 'view_user_report.html'
	def get(self,request,id):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		booking_data = FortuneAppointmentBook.objects.filter(seer_user = id)
		month_list = ['01' , '02' , '03' , '04' , '05' , '06' , '07' ,'08' , '09' , '10' , '11' , '12']
		bookings = []
		import datetime
		today = datetime.date.today()
		year = today.year
		for mnth in month_list:
			all_booking = FortuneAppointmentBook.objects.filter(created_at__year=year ,created_at__month=mnth,end_date__isnull =True,seer_user = id).count()
			bookings.append(all_booking)
		return render(request,self.template_name,locals())


class FortuneTellerReports(TemplateView):
	template_name = 'fortune_report.html'
	@method_decorator(login_required(login_url='/'))
	def get (self,request):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		data_obj = (
			FortuneAppointmentBook.objects
			.values('fortune_teller__id','fortune_teller__first_name','fortune_teller__last_name','fortune_teller__email','fortune_teller__image','fortune_teller__created_at','fortune_teller__status')
			.annotate(total_appointments=Count('fortune_teller'))
			.order_by('fortune_teller')
		)
		search_post = request.GET.get('search')
		lookups = Q()
		if search_post:
			lookups.add(Q(fortune_teller__first_name=search_post)|Q(fortune_teller__last_name=search_post)|Q(fortune_teller__email=search_post), Q.AND)
		data_obj = (
			FortuneAppointmentBook.objects.filter(lookups)
			.values('fortune_teller__id','fortune_teller__first_name','fortune_teller__last_name','fortune_teller__email','fortune_teller__image','fortune_teller__created_at','fortune_teller__status')
			.annotate(total_appointments=Count('fortune_teller'))
			.order_by('fortune_teller')
		)
		paginator = Paginator(data_obj, 10)
		page_number = request.GET.get('page')
		user_appointments = paginator.get_page(page_number)
		return render(request,self.template_name,locals())



class ViewFortuneTellerReports(TemplateView):
	template_name = 'view_fortune_report.html'
	def get(self,request,id):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		booking_data = FortuneAppointmentBook.objects.filter(fortune_teller = id)
		month_list = ['01' , '02' , '03' , '04' , '05' , '06' , '07' ,'08' , '09' , '10' , '11' , '12']
		bookings = []
		import datetime
		today = datetime.date.today()
		year = today.year
		for mnth in month_list:
			all_booking = FortuneAppointmentBook.objects.filter(created_at__year=year ,created_at__month=mnth,end_date__isnull =True,fortune_teller = id).count()
			bookings.append(all_booking)
		return render(request,self.template_name,locals())
	

class ExportFortuneCsvReport(View):
	def get(self,request):
		queryset = (
			FortuneAppointmentBook.objects
			.values('fortune_teller__id','fortune_teller__first_name','fortune_teller__last_name','fortune_teller__email','fortune_teller__image','fortune_teller__created_at','fortune_teller__status')
			.annotate(total_appointments=Count('seer_user'))
			.order_by('seer_user')
		)
		response = HttpResponse(content_type='text/csv')
		response['Content-Disposition'] = 'attachment; filename="fortuneteller_report.csv"'
		writer = csv.writer(response)
		writer.writerow(['FortuneTeller Id', 'FortuneTeller Name', 'FortuneTeller Email' ,'FortuneTeller Image', 'FortuneTeller Created Date','FortuneTeller Status','Appointments Recived'])

		# Write the data rows
		for item in queryset:
			writer.writerow([item['fortune_teller__id'], item['fortune_teller__first_name'] + ' ' + item['fortune_teller__last_name'], item['fortune_teller__email'] ,item['fortune_teller__image'], item['fortune_teller__created_at'], item['fortune_teller__status'], item['total_appointments']])

		return response
	

class AllTranscationsReports(TemplateView):
	template_name = 'all_transcation_report.html'
	def get(self,request):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		data_obj = SeerUserTranscation.objects.all().order_by('-id')
		paginator = Paginator(data_obj, 10)
		page_number = request.GET.get('page')
		payment_obj = paginator.get_page(page_number)
		return render(request,self.template_name,locals())


class ExportTranscationReportCSV(View):
	def get(self,request):
		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
		data_obj = SeerUserTranscation.objects.all().order_by('-id')
		response = HttpResponse(content_type='text/csv')
		response['Content-Disposition'] = 'attachment; filename="fortuneteller_report.csv"'
		writer = csv.writer(response)
		writer.writerow(['Transcation Id', 'Username', 'User Email' ,'Payment Mode', 'Date','Amount','Status'])

		# Write the data rows
		for item in data_obj:
			if item.booking.is_paid == 1 :
				status = 'Completed'
			else:
				status = 'Pending'
			writer.writerow([item.transcation_id, item.seer_user.first_name + ' ' + item.seer_user.last_name, item.seer_user.email ,item.payment_mode, item.created_at, item.amount, status])

		return response
""" ========== This code is for manually transfer the amount to fortune teller strip account ============ """
# class GetPayoutAllRequest(TemplateView):
# 	template_name = 'all_payout_request.html'
# 	def get(self,request):
# 		admin_obj = SuperAdmin.objects.filter(user=request.user.id).first()
# 		data_obj = FortunePayoutTranscation.objects.all().order_by('-id')
# 		search_post = request.GET.get('search')
# 		lookups = Q()
# 		if search_post:
# 			print('search_post',search_post)
# 			data_obj = FortunePayoutTranscation.objects.filter(Q(transcation_id=search_post)|Q(fortune_teller__first_name__icontains=search_post)|Q(fortune_teller__last_name__icontains=search_post))
# 		# data_obj = FortunePayoutTranscation.objects.filter(lookups).order_by('-id')
# 		paginator = Paginator(data_obj, 10)
# 		page_number = request.GET.get('page')
# 		payout_obj = paginator.get_page(page_number)
# 		return render(request,self.template_name,locals())
	

# class ChangePayoutRequestStatus(View):
# 	def post(self,request):
# 		try:
# 			appoint_id = request.POST.get('appoint_id')
# 			new_status = request.POST.get('new_status')
# 			try:
# 				service = FortunePayoutTranscation.objects.get(id=appoint_id)
# 				if new_status == 'approved':
# 					fortune_obj = FortuneTeller.objects.filter(id=service.fortune_teller.id).first()
# 					tranfer_amount = TransferToConnectedAccount(fortune_obj.stripe_connect_account_id,service.amount)
# 					subject = 'Payout Request Approved'
# 					html_message = render_to_string('payout_approved_email.html',{'email':fortune_obj.email,'first_name':fortune_obj.first_name,'last_name':fortune_obj.last_name,'payout_accpeted_date':datetime.now(),'amount':service.amount})
# 					plain_message = html_message
# 					from_email = settings.EMAIL_HOST_USER
# 					to = 'nitin@yopmail.com'
# 					mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message)
# 					messages.success(request, "Status changed successfully")
# 					service.transcation_status = new_status
# 					service.save()
# 					FortuneTellerNotifications.objects.create(message='Your payout request for Amount of $'+str(service.amount)+ ' has been approved successfuly',notification_type="appointment_earning",fortune_teller=fortune_obj)
					
# 				else:
# 					service.transcation_status = new_status
# 					service.save()
# 				return HttpResponse(request.META.get('HTTP_REFERER'))
# 			except Exception as e:
# 				print('================',e)
# 				messages.warning(request, "Something went wrong.Please try again.")
# 				return JsonResponse({'success': False, 'error': str(e)})
# 		except Exception as e:
# 			messages.warning(request, "Something went wrong.Please try again.")
# 			return redirect('salon-dashboard')

""" ========== End Of Code ============ """

class GetCountries(APIView):
	def get(self,request):
		try:
			country_obj = Countries.objects.filter(end_date__isnull =True).order_by('country_name')
			all_data = CountrySerializer(country_obj,many=True).data
			return Response({'message':'Success','data':all_data})
		except Exception as e:
			print(e)
			return Response({'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)
		
class GetStates(APIView):
	def get(self,request):
		try:
			data =  request.query_params
			country_id = data.get('id')
			if not country_id:
				return Response({"message":'id is required'},status=status.HTTP_400_BAD_REQUEST)
			state_obj = State.objects.filter(country=country_id,end_date__isnull =True).order_by('state_name')
			all_data = StateSerializer(state_obj,many=True).data
			return Response({'message':'Success','data':all_data})
		except Exception as e:
			print(e)
			return Response({'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class GetCities(APIView):
	def get(self,request):
		try:
			data =  request.query_params
			state_id = data.get('id')
			if not state_id:
				return Response({"message":'id is required'},status=status.HTTP_400_BAD_REQUEST)
			city_obj = City.objects.filter(state=state_id,end_date__isnull =True).order_by('city_name')
			all_data = CitySerializer(city_obj,many=True).data
			return Response({'message':'Success','data':all_data})
		except Exception as e:
			print(e)
			return Response({'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)




def create_states_and_cities_from_json(json_data):
	data = json.loads(json_data)
	country, _ = Countries.objects.get_or_create(country_name="USA")
	for state_name, cities in data.items():
		# Create the state instance
		state = State.objects.create(country=country, state_name=state_name)
		# Create the city instances for this state
		for city_name in cities:
			City.objects.create(state=state, city_name=city_name)



def import_states_cities(request):
	if request.method == 'GET':
		try:
			# Replace 'path/to/your/file.json' with the actual file path
			json_file_path = 'US_States_and_Cities.json'
			with open(json_file_path, 'r') as file:
				json_data = file.read()
			create_states_and_cities_from_json(json_data)
			return JsonResponse({'message': 'States and cities imported successfully.'}, status=200)
		except FileNotFoundError:
			return JsonResponse({'error': 'JSON file not found.'}, status=404)
		except json.JSONDecodeError:
			return JsonResponse({'error': 'Invalid JSON data in the file.'}, status=400)
	else:
		return JsonResponse({'error': 'Only POST requests are allowed.'}, status=405)

