from concurrent.futures.thread import _python_exit, _worker
from pipes import Template
from django.views.generic.base import View
from django.views.generic import TemplateView
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect
from django.http.response import HttpResponse
from admin_panel.models import *
from . import forms
from django.contrib import messages
from django.core import mail
from django.template.loader import render_to_string
import math, random, string
from django.conf import settings
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from .functions import *
from django.db.models import Q,Sum
import datetime
import json
from django.db.models import Count
import ast
from django.views.generic import TemplateView
from passlib.hash import django_pbkdf2_sha256 as handler
import datetime
from django.http import HttpResponseRedirect
from worker_panel.models import *
from user_panel.models import *
from django.utils import timezone
import csv
from collections import defaultdict


#Funtion based views
def checkEmail(request):
	text = request.GET.get('email')
	post = User.objects.filter(email=text,is_superuser = 1).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(email=text,is_superuser = 1)
	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,is_superuser = 1)
	if user.check_password(old_password) == False:
		message = 'Does not match with the old password.'
		return JsonResponse(message,safe=False)
	else:
		return HttpResponse ('true')



def generateTranscationsId():
	lastObj= UserTranscation.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'

class AdminLogIn(TemplateView):
	template_name = 'admin-signin.html'
	def get(self,request):
		if(request.user.is_authenticated):
			return HttpResponseRedirect('/admin-dashboard')
		return render(request,self.template_name)
	
	def post(self,request):
		try:
			form = forms.AdminSigninForm(request.POST)
			if form.is_valid():
				email    = form.cleaned_data.get('email')
				password = form.cleaned_data.get('password')
				user     = authenticate(email=email, password=password)
				if user.status == False:
					messages.error(request, "You account has been deactivated by superadmin.")
					return render(request, self.template_name)

				if user.end_date:
					messages.error(request, "You account has been deleted by superadmin.")
					return render(request, self.template_name)

				if user:
						login(request, user)
						messages.success(request, "Login successfully")
						return redirect('/admin-dashboard')

				else:
					messages.error(request, "Invalid email and password.")
					return render(request, self.template_name)
			else:
				return render(request,self.template_name, {'form': form})
		except Exception as e:
			messages.warning(request, "Something went wrong.Please try again.")
			return redirect('admin-signin')     
		

class AdminForgetPassword(TemplateView):
	template_name = 'forgot-password.html'
	def get(self,request):
		if(request.user.is_authenticated):
			return HttpResponseRedirect('/admin-dashboard')
		return render(request,self.template_name)
	
	def post(self,request):
		form = forms.AdminForgetPasswordForm(request.POST)
		if form.is_valid():
			email =  form.cleaned_data.get('email')
			admin_obj = User.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.forgot_password_link = 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 = User.objects.filter(email = user_email).first()
		if link_expiry.forgot_password_link == "LinkExpiry":
			return render(request,'link_expire.html')
		admin_obj = User.objects.filter(email = user_email, forgot_password_link = link).first()
		if admin_obj:
			valid = True
		else:
			valid = False
		return render(request,self.template_name,locals())

	def post(self,request):
		form = forms.ForgetVerificationForm(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_obj = User.objects.filter(email = user_email).first()
			if user_obj:
				user_obj.set_password(new_password)
				user_obj.forgot_password_link = "LinkExpiry"
				user_obj.save()
				messages.success(request, "Password changed successfully")
				return redirect('/admin-login')
			else:
				messages.error(request, "Something went wrong")
				return redirect('/admin-login')
		else:
			return render(request, self.template_name, {'form': form})	


class AdminDashboard(TemplateView):
	template_name = 'dashboard.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request):
		now = timezone.now()
		current_year = now.year
		total_users = User.objects.filter(end_date__isnull = True,is_user = 1).count()
		total_workers = User.objects.filter(end_date__isnull = True,is_worker = 1).count()
		all_worker = User.objects.filter(end_date__isnull = True,is_worker = 1)[:5]
		all_user = User.objects.filter(is_user= 1,end_date__isnull = True)[:5]
		total_bookings = UserBookings.objects.filter(end_date__isnull = True).count()
		booking_obj =  UserBookings.objects.filter(end_date__isnull = True)[:5]
		total_payments = UserTranscation.objects.filter(created_at__year=current_year,end_date__isnull = True).aggregate(Sum('amount'))['amount__sum']


		# Fetch data from the UserTranscation model
		data = UserTranscation.objects.filter(created_at__year=current_year)

		# Prepare data for Highcharts
		month_names = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

		# Create a defaultdict to store amounts for each month
		amounts_by_month = defaultdict(float)
		for entry in data:
			amounts_by_month[entry.created_at.month] += float(entry.amount)

		# Fill in zeros for months without entries
		categories = [month_names[i - 1] for i in range(1, 13)]
		series_data = [{'name': 'Corn', 'data': [amounts_by_month[i] for i in range(1, 13)]}]


		# Fetch data from the UserBookings model
		bookings_this_year = UserBookings.objects.filter(start_date__year=2024)  # Assuming you want data for the current year
		bookings_last_year = UserBookings.objects.filter(start_date__year=2023)  # Assuming you want data for the previous year

		# Prepare data for Highcharts
		months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

		bookings_this_year_data = [bookings_this_year.filter(start_date__month=i).count() for i in range(1, 13)]
		bookings_last_year_data = [bookings_last_year.filter(start_date__month=i).count() for i in range(1, 13)]

		context = {
			'months': months,
			'bookings_this_year_data': bookings_this_year_data,
			'bookings_last_year_data': bookings_last_year_data,
			'categories': categories,
			'series_data': series_data,
		}
		
		return render(request,self.template_name,locals())
	

class AdminProfile(TemplateView):
	template_name = 'admin_profile.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request):
		return render(request,self.template_name,locals())
		
	def post(self,request):
			form = forms.AdminProfileForm(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')
				User.objects.filter(id=request.user.id).update(first_name=first_name,last_name=last_name,email=email,phone_number=phone_number)
				if request.FILES.get('avatar'):
					fileUrl=uploadTheImages(request.FILES.get('avatar'))
					fileUrl='/'+fileUrl
					User.objects.filter(id=request.user.id).update(avatar=str(fileUrl))
				messages.success(request, "Update Succesfully")
				return redirect('admin-profile')
			else:
				return render(request,self.template_name)
		
		
class AdminResetPassword(TemplateView):
	template_name = 'admin_reset_password.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request):
		return render(request,self.template_name,locals())

	def post(self,request):
		try:
			form = forms.ChangePasswordForm(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('/admin-login')
			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('admin-dashboard') 
		

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


class privacyPolicy(View):
	template_name = 'privacy_policy.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request):
		cont_obj = ContentPages.objects.filter(page_type='Privacy').first()
		return render(request,self.template_name,locals())
	
	def post(self,request):
		form = forms.content_page_form(request.POST)
		if form.is_valid():
			title = form.cleaned_data.get('title')
			content = form.cleaned_data.get('content')
			data = ContentPages.objects.filter(page_type='Privacy').first()
			if data:
				ContentPages.objects.filter(id=data.id).update(title=title,content=content,page_type='Privacy')
			else:
				ContentPages.objects.create(title=title,content=content,page_type='Privacy')
			messages.success(request, 'Updated Successfully')
			return redirect('/privacy-policy')
		else:
			return render(request,self.template_name,locals())


class termsAndConditions(View):
	template_name = 'terms.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request):
		cont_obj = ContentPages.objects.filter(page_type='Terms').first()
		return render(request,self.template_name,locals())
	
	def post(self,request):
		form = forms.content_page_form(request.POST)
		if form.is_valid():
			title = form.cleaned_data.get('title')
			content = form.cleaned_data.get('content')
			data = ContentPages.objects.filter(page_type='Terms').first()
			if data:
				ContentPages.objects.filter(id=data.id).update(title=title,content=content,page_type='Terms')
			else:
				ContentPages.objects.create(title=title,content=content,page_type='Terms')
			messages.success(request, 'Updated Successfully')
			return redirect('/terms-and-conditions')
		else:
			return render(request,self.template_name,locals())


class faqListing(View):
	template_name = 'faq_listing.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request):
		data_obj = Faq.objects.filter(end_date__isnull = True).order_by('-id')
		paginator = Paginator(data_obj, 8)
		page_number = request.GET.get('page')
		faq_obj = paginator.get_page(page_number)
		return render(request,self.template_name,locals())
	


class addFaq(View):
	template_name = 'add_faq.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request):
		return render(request,self.template_name,locals())

	def post(self,request):
		form = forms.content_page_form(request.POST)
		if form.is_valid():
			title = form.cleaned_data.get('title')
			content = form.cleaned_data.get('content')
			Faq.objects.create(title=title,content=content)
			messages.success(request, 'Created Successfully')
			return redirect('/faq-listing')
		else:
			return render(request,self.template_name,locals())


class editFaq(View):
	template_name = 'edit_faq.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request,id):
		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.content_page_form(request.POST)
		if form.is_valid():
			title = form.cleaned_data.get('title')
			content = form.cleaned_data.get('content')
			Faq.objects.filter(id=id).update(title=title,content=content)
			messages.success(request, 'Updated Successfully')
			return redirect('/faq-listing')
		else:
			return render(request,self.template_name,locals())

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


class adminNotifications(TemplateView):
	template_name = 'admin_notifications.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request):
		notify_obj = AdminNotifications.objects.all().order_by('-id')
		return render(request,self.template_name,locals())

    
class deleteAdminNotifications(View):
    def get(self,request):
        try:
            if request.method == 'GET':
                ids = request.GET.get('delete_id')
                if ids:
                    int_id_list = [int(id) for id in ids.split(',')]
                    AdminNotifications.objects.filter(pk__in=int_id_list).delete()
                    messages.success(request,"Deleted Sucessfully")
                else:
                    messages.error(request,"At least One notification must be selected")
                return redirect('/admin-notifications')

            else:
                return redirect('/admin-notifications')
        except Exception as e:
            messages.warning(request, "Something went wrong.Please try again.")
            return redirect('admin-dashboard')  




class helpAndSupportList(TemplateView):
	template_name = 'help_support_list.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request):
		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, 8)
		page_number = request.GET.get('page')
		sup_obj = paginator.get_page(page_number)
		return render(request,self.template_name,locals())


class viewHelpAndSupport(TemplateView):
	template_name = 'help_support_view.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request,id):
		sup_obj = HelpSupport.objects.filter(id=id).first()
		return render(request,self.template_name,locals())
	


class sendReplyHelpSupport(TemplateView):
	template_name = 'help_support_reply.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request,id):
		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 = 'support@olfix.co.uk'
			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.datetime.now(),status=True)
			messages.success(request, "send successfully")
			return redirect('/help-and-support-list')
		else:
			return render(request,self.template_name,locals())



class customerListing(TemplateView):
	template_name = 'customer_listing.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request):
		data_obj = User.objects.filter(is_user = 1 ,end_date__isnull = True).order_by('-id')
		search_post = request.GET.get('search')
		if search_post:
			data_obj = User.objects.filter(Q(phone_number__icontains=search_post)|Q(email__icontains = search_post)|Q(first_name__icontains = search_post)|Q(last_name__icontains = search_post),end_date__isnull = True,is_user = 1).order_by('-id')
		search_start = request.GET.get('start_date')
		time = datetime.datetime.now().strftime('%H:%M:%S')
		search_end = request.GET.get('end_date') 
		if search_start:
			data_obj = User.objects.filter(start_date__range=[search_start, search_end + ' '+ time],end_date__isnull=True,is_user = 1).order_by('-id')
		paginator = Paginator(data_obj, 8)
		page_number = request.GET.get('page')
		cust_obj = paginator.get_page(page_number)
		return render(request,self.template_name,locals())
	

class customerDetails(TemplateView):
	template_name = 'customer_details.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request,id):
		cust_obj = User.objects.filter(id=id,is_user = 1 ,end_date__isnull = True).first()
		upcoming = UserBookings.objects.filter(user = cust_obj,booking_status = 'Accepted')
		past = UserBookings.objects.filter(user = cust_obj,booking_status = 'Completed')

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

class editCustomerDetails(TemplateView):
	template_name = 'edit_customer_details.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request,id):
		user_obj =  User.objects.filter(id=id,is_user = 1 ,end_date__isnull = True).first()
		return render(request,self.template_name,locals())

	def post(self,request,id):
		form = forms.editcustomerform(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')
			User.objects.filter(id=id,is_user = 1).update(first_name = first_name,last_name = last_name,email = email,phone_number = phone_number)
			if request.FILES.get('avatar'):
				fileUrl=uploadTheImages(request.FILES.get('avatar'))
				fileUrl='/'+fileUrl
				User.objects.filter(id=id).update(avatar=str(fileUrl))
			messages.success(request, "Updated successfully")
			return redirect('/get-customer-listing')
		else:
			return render(request,self.template_name,locals())

class deleteCustomer(View):
	def get(self, request,id):
		user_obj  =  User.objects.filter(id=id,is_user=1,end_date__isnull = True ).first()
		user_obj.end_date = datetime.datetime.now()
		user_obj.save()
		messages.success(request, "User deleted successfully")
		return redirect('/get-customer-listing')


class changeCustomerStatus(View):     
	@method_decorator(login_required(login_url='/admin-login'))
	def post(self,request):
		try:
			pub        = User.objects.get(id = request.POST['main_id'])
			pub.status = request.POST['status']
			pub.save()
			if pub.status == "1":
				messages.success(request, "Customer status is activated")
				return HttpResponse(request.META.get('HTTP_REFERER'))
			else:
				messages.error(request, "Customer 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 categoryListing(TemplateView):
	template_name = 'category_listing.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request):
		data_obj = Category.objects.filter(end_date__isnull = True).order_by('-id')
		search_post = request.GET.get('search')
		if search_post:
			data_obj = Category.objects.filter(Q(name__icontains=search_post),end_date__isnull = True).order_by('-id')
		paginator = Paginator(data_obj, 8)
		page_number = request.GET.get('page')
		cat_obj = paginator.get_page(page_number)
		return render(request,self.template_name,locals())
	

class addCategory(TemplateView):
	template_name = 'add_category.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request):
		return render(request,self.template_name,locals())
	
	def post(self,request):
		form = forms.addcategoryform(request.POST)
		if form.is_valid():
			name = form.cleaned_data.get('name')
			cat_obj = Category.objects.create(name = name)
			if request.FILES.get('image'):
				fileUrl=uploadTheImages(request.FILES.get('image'))
				fileUrl='/'+fileUrl
				cat_obj.image=str(fileUrl)
				cat_obj.save()
			messages.success(request, "Created successfully")
			return redirect('/category-listing')
		else:
			return render(request,self.template_name,locals())



class editCategory(TemplateView):
	template_name = 'edit_category.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request,id):
		cat_obj =  Category.objects.filter(id=id).first()
		return render(request,self.template_name,locals())
	
	def post(self,request,id):
		form =  forms.addcategoryform(request.POST)
		if form.is_valid():
			name = form.cleaned_data.get('name')
			Category.objects.filter(id=id).update(name = name)
			if request.FILES.get('image'):
				fileUrl=uploadTheImages(request.FILES.get('image'))
				fileUrl='/'+fileUrl
				Category.objects.filter(id=id).update(image = fileUrl)
			messages.success(request, "Created successfully")
			return redirect('/category-listing')
		else:
			return render(request,self.template_name,locals())


class changeCategoryStatus(View):
	
	def post(self,request):
		try:
			pub        = Category.objects.get(id = request.POST['main_id'])
			pub.status = request.POST['status']
			pub.save()
			if pub.status == "1":
				messages.success(request, "Category status is activated")
				return HttpResponse(request.META.get('HTTP_REFERER'))
			else:
				messages.error(request, "Category 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 deleteCategory(View):
	def get(self, request,id):
		cat_obj  =  Category.objects.filter(id=id,end_date__isnull = True ).first()
		cat_obj.end_date = datetime.datetime.now()
		cat_obj.save()
		messages.success(request, "Category deleted successfully")
		return redirect('/category-listing')





class subCategoryListing(TemplateView):
	template_name = 'sub_category_listing.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request):
		data_obj = SubCategory.objects.filter(end_date__isnull = True).order_by('-id')
		search_post = request.GET.get('search')
		if search_post:
			data_obj = SubCategory.objects.filter(Q(name__icontains=search_post)|Q(category__name__icontains=search_post),end_date__isnull = True).order_by('-id')
		paginator = Paginator(data_obj, 8)
		page_number = request.GET.get('page')
		cat_obj = paginator.get_page(page_number)
		return render(request,self.template_name,locals())


class addSubCategory(TemplateView):
	template_name = 'add_sub_category.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request):
		main = Category.objects.filter(end_date__isnull = True)
		return render(request,self.template_name,locals())
	
	def post(self,request):
		form = forms.addsubcategoryform(request.POST)
		if form.is_valid():
			name = form.cleaned_data.get('name')
			category = form.cleaned_data.get('category')
			category_obj = Category.objects.get(id=category)

			cat_obj = SubCategory.objects.create(name = name,category = category_obj)
			if request.FILES.get('image'):
				fileUrl=uploadTheImages(request.FILES.get('image'))
				fileUrl='/'+fileUrl
				cat_obj.image=str(fileUrl)
				cat_obj.save()
			messages.success(request, "Created successfully")
			return redirect('/sub-category-listing')
		else:
			return render(request,self.template_name,locals())



class editSubCategory(TemplateView):
	template_name = 'edit_sub_category.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request,id):
		cat_obj =  SubCategory.objects.filter(id=id).first()
		main = Category.objects.filter(end_date__isnull = True)
		return render(request,self.template_name,locals())
	
	def post(self,request,id):
		form =  forms.addsubcategoryform(request.POST)
		if form.is_valid():
			name = form.cleaned_data.get('name')
			category = form.cleaned_data.get('category')
			category_obj = Category.objects.get(id=category)
			cat_obj = SubCategory.objects.filter(id=id).update(name = name,category = category_obj)
			if request.FILES.get('image'):
				fileUrl=uploadTheImages(request.FILES.get('image'))
				fileUrl='/'+fileUrl
				SubCategory.objects.filter(id=id).update(image = fileUrl)
			messages.success(request, "Created successfully")
			return redirect('/sub-category-listing')
		else:
			return render(request,self.template_name,locals())


class changeSubCategoryStatus(View):
	@method_decorator(login_required(login_url='/admin-login'))
	def post(self,request):
		try:
			pub        = SubCategory.objects.get(id = request.POST['main_id'])
			pub.status = request.POST['status']
			pub.save()
			if pub.status == "1":
				messages.success(request, "Sub Category status is activated")
				return HttpResponse(request.META.get('HTTP_REFERER'))
			else:
				messages.error(request, "Sub Category 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 deleteSubCategory(View):
	def get(self, request,id):
		cat_obj  =  SubCategory.objects.filter(id=id,end_date__isnull = True ).first()
		cat_obj.end_date = datetime.datetime.now()
		cat_obj.save()
		messages.success(request, "Category deleted successfully")
		return redirect('/sub-category-listing')


class paymentListing(TemplateView):
	template_name = 'payment_listing.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request):
		from datetime import datetime
		data_obj = UserTranscation.objects.all().order_by('-id')
		search_post = request.GET.get('search')
		if search_post:
			data_obj = UserTranscation.objects.filter(Q(booking__user__first_name__icontains=search_post)|Q(booking__user__last_name__icontains=search_post)|Q(booking__worker__first_name__icontains=search_post)|Q(booking__worker__last_name__icontains=search_post)|Q(booking__booking_id__icontains=search_post),end_date__isnull = True).order_by('-id')
	
		start_date_str = request.GET.get('start_date')
		if start_date_str:
			start_date = datetime.strptime(start_date_str, '%Y-%m-%d').date()
			data_obj = UserTranscation.objects.filter(created_at__date=start_date)

		paginator = Paginator(data_obj, 8)
		page_number = request.GET.get('page')
		payment_obj = paginator.get_page(page_number)

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

class getReports(TemplateView):
	template_name = 'get_reports.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request):
		now = timezone.now()
		current_year = now.year
		total_user_count = User.objects.filter(is_user = 1).count()
		total_provider_count = User.objects.filter(is_worker = 1).count()
		total_payments = UserTranscation.objects.filter(end_date__isnull = True,created_at__year=current_year).aggregate(Sum('amount'))['amount__sum']
		if total_payments is None:
			total_payments = 0
		total_booking =  UserBookings.objects.all().count()
		now = timezone.now()
		new_user_count = User.objects.filter(start_date__date=now.date(),is_user = 1).count()
		new_worker_count = User.objects.filter(start_date__date=now.date(),is_worker = 1).count()
		cancelled_booking = UserBookings.objects.filter(booking_status = 'Declined').count()

		total_payments = UserTranscation.objects.filter(end_date__isnull = True,created_at__year=current_year).aggregate(Sum('amount'))['amount__sum']
		# Fetch data from the UserTranscation model
		
		data = UserTranscation.objects.filter(created_at__year=current_year)
		# Prepare data for Highcharts
		
		month_names = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
		# Create a defaultdict to store amounts for each month
		# The above code is not doing anything. It is just a variable name "amounts_by_month" followed by
		# three hash symbols "
		
		amounts_by_month = defaultdict(float)
		for entry in data:
			amounts_by_month[entry.created_at.month] += float(entry.amount)

		# Fill in zeros for months without entries
		categories = [month_names[i - 1] for i in range(1, 13)]
		series_data = [{'name': 'Earnings', 'data': [amounts_by_month[i] for i in range(1, 13)]}]

		# Fetch data from the UserBookings model
		bookings_this_year = UserBookings.objects.filter(start_date__year=2024)  # Assuming you want data for the current year
		bookings_last_year = UserBookings.objects.filter(start_date__year=2023)  # Assuming you want data for the previous year

		# Prepare data for Highcharts
		months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

		bookings_this_year_data = [bookings_this_year.filter(start_date__month=i).count() for i in range(1, 13)]
		bookings_last_year_data = [bookings_last_year.filter(start_date__month=i).count() for i in range(1, 13)]


		data = UserBookings.objects.filter(booking_status__in=['Completed', 'Declined'],start_date__year=current_year) \
        .extra({'month': "EXTRACT(month FROM start_date)"}) \
        .values('month') \
        .annotate(cancelled=Count('id', filter=models.Q(booking_status='Declined')),
                  completed=Count('id', filter=models.Q(booking_status='Completed'))) \
        .order_by('month')

		months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

		# Create series data for Highcharts
		cancelled_series = [data_dict.get('cancelled', 0) for data_dict in data]
		completed_series = [data_dict.get('completed', 0) for data_dict in data]

		# Get the total count of users
		total_users = User.objects.filter(start_date__year=current_year,end_date__isnull=True, is_user=1).count()
		active_users = User.objects.filter(start_date__year=current_year,end_date__isnull=True, is_user=1)
		users_by_month = defaultdict(int)
		for entry in active_users:
			month = entry.start_date.month
			users_by_month[month] += 1
		month_names = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
		user_counts = [users_by_month.get(i, 0) for i in range(1, 13)]
		user_series_data = [{'name': 'Users', 'data': user_counts}]


		# Get the total count of workers
		total_workers = User.objects.filter(start_date__year=current_year,end_date__isnull=True, is_worker=1).count()
		active_worker = User.objects.filter(start_date__year=current_year,end_date__isnull=True, is_worker=1)
		users_by_month = defaultdict(int)
		for entry in active_worker:
			month = entry.start_date.month
			users_by_month[month] += 1
		month_names = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
		worker_counts = [users_by_month.get(i, 0) for i in range(1, 13)]
		worker_series_data = [{'name': 'Service Providers', 'data': worker_counts}]

		context = {
			'months': months,
			'bookings_this_year_data': bookings_this_year_data,
			'bookings_last_year_data': bookings_last_year_data,
			'categories': categories,
			'series_data': series_data,
			'cancelled_series': cancelled_series,
			'completed_series': completed_series,
			'user_series_data':user_series_data,
			'worker_series_data':worker_series_data,
		}
			
		return render(request,self.template_name,locals())

class refundListing(TemplateView):
	template_name = 'refund_listing.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request):
		data_obj = AdminRefundRequest.objects.all().order_by('-id')
		from datetime import datetime
		search_post = request.GET.get('search')
		if search_post:
			data_obj = AdminRefundRequest.objects.filter(Q(booking__booking_id__icontains=search_post),end_date__isnull = True).order_by('-id')
	
		start_date_str = request.GET.get('start_date')
		if start_date_str:
			start_date = datetime.strptime(start_date_str, '%Y-%m-%d').date()
			data_obj = AdminRefundRequest.objects.filter(date_processed__date=start_date).order_by('-id')
		paginator = Paginator(data_obj, 8)
		page_number = request.GET.get('page')
		refund_obj = paginator.get_page(page_number)
		return render(request,self.template_name,locals())


class refundDetails(TemplateView):
	template_name = 'refund_details.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request,id):
		refund_obj = AdminRefundRequest.objects.filter(id = id).first()
		return render(request,self.template_name,locals())
	

class payRefundAmount(View):
	@method_decorator(login_required(login_url='/admin-login'))
	def post(self,request,id):
		refund_obj = AdminRefundRequest.objects.filter(id = id).first()
		booking_obj  =  UserBookings.objects.filter(id=refund_obj.booking.booking_id).first()
		user_obj = User.objects.filter(id = refund_obj.booking.user.id).first()
		user_wallet = UserWallet.objects.filter(user=user_obj).first()
		new_amount = user_wallet.amount + refund_obj.refund_amount
		user_wallet.amount = new_amount
		user_wallet.save()
		refund_obj.status = 'Completed'
		refund_obj.save()
		CustomerNotifications.objects.create(customer = user_obj,message = "Your refund amount for booking id : "+refund_obj.booking.booking_id +" has been processed successfully",type = "refund")
		UserTranscation.objects.create(transcation_id=generateTranscationsId(), transcation_type="refund", booking=booking_obj, user=user_obj, amount=refund_obj.refund_amount, payment_mode="wallet")

		messages.success(request, "Refund processed successfully")
		return redirect('/refund-listing')

class bookingListing(TemplateView):
	template_name = 'booking_listing.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request):
		data_obj = UserBookings.objects.all().order_by('-id')
		search_post = request.GET.get('search')
		if search_post:
			data_obj = UserBookings.objects.filter(Q(booking_id__icontains=search_post)|Q(user__first_name__icontains = search_post)|Q(user__last_name__icontains = search_post)|Q(worker__first_name__icontains = search_post) |Q(worker__last_name__icontains = search_post),end_date__isnull = True).order_by('-id')
		search_start = request.GET.get('start_date')
		time = datetime.datetime.now().strftime('%H:%M:%S')
		search_end = request.GET.get('end_date') 
		if search_start:
			data_obj = UserBookings.objects.filter(start_date__range=[search_start, search_end + ' '+ time],end_date__isnull=True).order_by('-id')
		paginator = Paginator(data_obj, 8)
		page_number = request.GET.get('page')
		book_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='/admin-login'))
	def get(self,request,id):
		booking_obj  = UserBookings.objects.filter(id = id ).first()
		return render(request,self.template_name,locals())
	

class getWorkerListing(TemplateView):
	template_name = 'worker_listing.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request):
		data_obj = User.objects.filter(is_worker = 1 ,end_date__isnull = True).order_by('-id')
		search_post = request.GET.get('search')
		if search_post:
			data_obj = User.objects.filter(Q(phone_number__icontains=search_post)|Q(email__icontains = search_post)|Q(first_name__icontains = search_post)|Q(last_name__icontains = search_post),end_date__isnull = True,is_worker = 1).order_by('-id')
		search_start = request.GET.get('start_date')
		import datetime
		time = datetime.datetime.now().strftime('%H:%M:%S')
		search_end = request.GET.get('end_date') 
		if search_start:
			data_obj = User.objects.filter(start_date__range=[search_start, search_end + ' '+ time],end_date__isnull=True,is_worker = 1).order_by('-id')
		paginator = Paginator(data_obj, 8)
		page_number = request.GET.get('page')
		cust_obj = paginator.get_page(page_number)
		return render(request,self.template_name,locals())
	
class getWorkerDetails(TemplateView):
	template_name = 'worker_details.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request,id):
		cust_obj = User.objects.filter(id=id,is_worker = 1 ,end_date__isnull = True).first()
		bank_obj  =  WorkerBankAccountDetails.objects.filter(worker_id = id).first()
		service_obj = WorkerServices.objects.filter(worker_id = cust_obj.id)
		upcoming = UserBookings.objects.filter(worker = cust_obj,booking_status = 'Accepted')
		past = UserBookings.objects.filter(worker = cust_obj,booking_status = 'Completed')
		return render(request,self.template_name,locals())
	

class editWorkerDetails(TemplateView):
	template_name = 'edit_worker_details.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request,id):
		main = Category.objects.filter(end_date__isnull = True)
		user_obj = User.objects.filter(id=id,is_worker = 1 ,end_date__isnull = True).first()
		return render(request,self.template_name,locals())
	
	def post(self,request,id):
		form = forms.editworkerform(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')
			experience = form.cleaned_data.get('experience')
			address = form.cleaned_data.get('address')
			User.objects.filter(id=id,is_worker = 1).update(first_name = first_name,last_name = last_name,email = email,phone_number = phone_number,address = address,experience=experience)
			if request.FILES.get('avatar'):
				fileUrl=uploadTheImages(request.FILES.get('avatar'))
				fileUrl='/'+fileUrl
				User.objects.filter(id=id).update(avatar=str(fileUrl))
			messages.success(request, "Updated successfully")
			return redirect('/get-worker-listing')
		else:
			return render(request,self.template_name,locals())
	

class changeWorkerStatus(View):
	@method_decorator(login_required(login_url='/admin-login'))
	def post(self,request):
		try:
			pub        = User.objects.get(id = request.POST['main_id'])
			pub.status = request.POST['status']
			pub.save()
			if pub.status == "1":
				messages.success(request, "Service provider status is activated")
				return HttpResponse(request.META.get('HTTP_REFERER'))
			else:
				messages.error(request, "Service provider 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 deleteWorker(View):
	def get(self, request,id):
		cat_obj  =  User.objects.filter(id=id,end_date__isnull = True ).first()
		cat_obj.end_date = datetime.datetime.now()
		cat_obj.save()
		messages.success(request, "Worker deleted successfully")
		return redirect('/get-worker-listing')


class featureServices(TemplateView):
	template_name = 'feature_service_list.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request):
		data_obj = FetaureService.objects.filter(end_date__isnull=True).order_by('-id')
		paginator = Paginator(data_obj, 8)
		page_number = request.GET.get('page')
		feat_obj = paginator.get_page(page_number)
		return render(request,self.template_name,locals())
	

class addFeatureServices(TemplateView):
	template_name = 'add_feature_service.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request):
		sub_obj = Category.objects.filter(end_date__isnull = True)
		return render(request,self.template_name,locals())

	def post(self,request):
		form = forms.addfeatureform(request.POST)
		if form.is_valid():
			sub_service =  form.cleaned_data.get('sub_category')
			service_obj = Category.objects.filter(id = sub_service).first()
			check_data = FetaureService.objects.filter(sub_category=sub_service).first()
			if check_data:
				messages.warning(request, "Already added")
				return redirect('/feature-services')
			FetaureService.objects.create(sub_category = service_obj)
			messages.success(request, "Added successfully")
			return redirect('/feature-services')
		else:
			return render(request,self.template_name,locals())

class deleteFeatureServices(View):
	def get(self, request,id):
		cat_obj  =  FetaureService.objects.filter(id=id,end_date__isnull = True ).first()
		cat_obj.delete()
		messages.success(request, "Deleted Successfully")
		return redirect('/feature-services')




def exportCsvBooking(request):
	queryset = UserBookings.objects.all()
	response = HttpResponse(content_type='text/csv')
	response['Content-Disposition'] = 'attachment; filename="booking.csv"'
	writer = csv.writer(response)
	writer.writerow(['Booking Id', 'Service Provider Name', 'User Name','Booking Date','Booking Time','Service Name','Subservice Name', 'Booking Status', 'Price'])

	# Write the data rows
	for item in queryset:
		writer.writerow([item.booking_id, item.worker.first_name+' '+item.worker.last_name, item.user.first_name+' '+item.user.last_name,item.booking_date,item.booking_time,item.sub_services.category.name,item.sub_services.name,item.booking_status,item.price])
	return response
	


def exportCsvUser(request):
    search_query = request.GET.get('search', '')
    start_date = request.GET.get('start_date', None)
    end_date = request.GET.get('end_date', None)

    queryset = User.objects.filter(is_user=1, end_date__isnull=True).order_by('-id')

    if search_query:
        queryset = queryset.filter(Q(phone_number__icontains=search_query) | Q(email__icontains=search_query) | Q(first_name__icontains=search_query) | Q(last_name__icontains=search_query))

    if start_date is not None and end_date is not None:
        queryset = queryset.filter(start_date__range=[start_date, end_date + ' ' + datetime.datetime.now().strftime('%H:%M:%S')])

    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="customers.csv"'
    writer = csv.writer(response)
    writer.writerow(['User Id', 'Name', 'Phone Number', 'Date of Birth', 'Email Id', 'Status', 'Created Date'])

    # Write the data rows
    for item in queryset:
        writer.writerow([item.id, item.first_name + ' ' + item.last_name, item.phone_number, item.dob, item.email, item.status, item.start_date])

    return response



def exportCsvWorker(request):
	queryset = User.objects.filter(is_worker = 1)
	response = HttpResponse(content_type='text/csv')
	response['Content-Disposition'] = 'attachment; filename="service_providers.csv"'
	writer = csv.writer(response)
	writer.writerow(['Service Provider Id', 'Name', 'Phone Number','Date of Birth','Email Id','Status','Created Date'])

	# Write the data rows
	for item in queryset:
		writer.writerow([item.id, item.first_name+' '+item.last_name, item.phone_number ,item.dob,item.email,item.status,item.start_date])
	return response


def exportCsvRefund(request):
	queryset = AdminRefundRequest.objects.all()
	response = HttpResponse(content_type='text/csv')
	response['Content-Disposition'] = 'attachment; filename="refund.csv"'
	writer = csv.writer(response)
	writer.writerow(['Booking ID', 'Customer Name', 'Worker Name','Booking Date','Booking Time','Price','Refund Status'])

	# Write the data rows
	for item in queryset:
		writer.writerow([item.booking.booking_id, item.booking.user.first_name+' '+item.booking.user.last_name, item.booking.worker.first_name +' '+ item.booking.worker.last_name ,item.booking.booking_date,item.booking.booking_time,item.refund_amount,item.status])
	return response



class getBannerListing(TemplateView):
	template_name = 'banner_listing.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self, request):
		data_obj =  BannerManagement.objects.filter(end_date__isnull=True).order_by('-id')
		paginator = Paginator(data_obj, 8)
		page_number = request.GET.get('page')
		banner_obj = paginator.get_page(page_number)
		return render(request,self.template_name,locals())
	



class addBannerHomepage(TemplateView):
	template_name = 'add_banner.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request):
		return render(request,self.template_name,locals())
	

	def post(self,request):
		form = forms.addBannerform(request.POST)
		if form.is_valid():
			banner_title = form.cleaned_data.get('banner_title')
			banner_obj = BannerManagement.objects.create(banner_title=banner_title)
			if request.FILES.get('image'):
				fileUrl=uploadTheImages(request.FILES.get('image'))
				fileUrl='/'+fileUrl
				banner_obj.image = str(fileUrl)
				banner_obj.save()
				messages.success(request, "Added successfully")
			return redirect('/get-banner-listing')
		else:
			return render(request,self.template_name,locals())



class editBannerHomepage(TemplateView):
	template_name = 'edit_banner.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self,request,id):
		banner_obj = BannerManagement.objects.filter(id = id).first()
		return render(request,self.template_name,locals())
	
	def post(self,request,id):
		form = forms.addBannerform(request.POST)
		if form.is_valid():
			banner_title = form.cleaned_data.get('banner_title')
			banner_obj = BannerManagement.objects.filter(id = id ).update(banner_title=banner_title)
			if request.FILES.get('image'):
				fileUrl=uploadTheImages(request.FILES.get('image'))
				fileUrl='/'+fileUrl
				BannerManagement.objects.filter(id = id ).update(image=fileUrl)

				messages.success(request, "Updated successfully")
			return redirect('/get-banner-listing')
		else:
			return render(request,self.template_name,locals())
		

class deleteBannerHomepage(TemplateView):
	def get(self, request,id):
		cat_obj  =  BannerManagement.objects.filter(id=id,end_date__isnull = True ).first()
		cat_obj.delete()
		messages.success(request, "Deleted Successfully")
		return redirect('/get-banner-listing')


class getConverStationListing(TemplateView):
	template_name = 'converstation_listing.html'
	@method_decorator(login_required(login_url='/admin-login'))

	def get(self, request):
		data_obj =  Conversation.objects.filter(end_date__isnull=True)
		search_post = request.GET.get('search')
		if search_post:
			data_obj = Conversation.objects.filter(Q(user__first_name__icontains=search_post)|Q(user__last_name__icontains=search_post)|Q(service_provider__first_name__icontains=search_post)|Q(service_provider__last_name__icontains=search_post)|Q(twilio_channel_sid__icontains=search_post),end_date__isnull = True).order_by('-id')
		paginator = Paginator(data_obj, 8)
		page_number = request.GET.get('page')
		chat_obj = paginator.get_page(page_number)
		return render(request,self.template_name,locals())



def exportConvertsation(request):
	queryset = Conversation.objects.all()
	response = HttpResponse(content_type='text/csv')
	response['Content-Disposition'] = 'attachment; filename="refund.csv"'
	writer = csv.writer(response)
	writer.writerow(['Customer Name', 'Service Provider Name', 'Twilio Channel SID','User Twilio ID','Service Provider Twilio ID','Created at'])

	# Write the data rows
	for item in queryset:
		writer.writerow([item.user.first_name+' '+item.user.last_name, item.service_provider.first_name+' '+item.service_provider.last_name, item.twilio_channel_sid , item.user_twilio_id ,item.service_provider_twilio_id,item.created_at])
	return response


class approveWorkerAccount(View):
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self, request,id):
		cat_obj  =  User.objects.filter(id=id,end_date__isnull = True ).update(is_worker_approved = 1)
		work_obj  =  User.objects.filter(id=id,end_date__isnull = True ).first()
		html_message = render_to_string('approve_worker_account.html', {'email':work_obj.email})
		subject = "Account Approved Successfully"
		plain_message = html_message
		from_email = 'support@olfix.co.uk'
		to = work_obj.email
		mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message)
		messages.success(request, "Approved Successfully")
		return redirect('/get-worker-listing')
	

class disapproveWorkerAccount(TemplateView):
	template_name = 'disapporve_reason.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self, request,id):
		worker_id = id
		return render(request,self.template_name,locals())
	
	def post(self, request,id):
		form = forms.DisapproveReasonForm(request.POST)
		if form.is_valid():
			reason = form.cleaned_data.get('reason')
			cat_obj  =  User.objects.filter(id=id,end_date__isnull = True ).update(is_worker_approved = 2)
			work_obj  =  User.objects.filter(id=id,end_date__isnull = True ).first()
			html_message = render_to_string('disapprove_worker_account.html', {'email':work_obj.email,'reason':reason})
			subject = "Account Disapproved Successfully"
			plain_message = html_message
			from_email = 'support@olfix.co.uk'
			to = work_obj.email
			mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message)
			messages.success(request, "Disapproved Successfully")
			return redirect('/get-worker-listing')
		else:
			return render(request,self.template_name,locals())


class getRatingsReviewList(TemplateView):
	template_name = 'rating_review_list.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self, request):
		data_obj =  ServiceProviderRatingReviews.objects.filter(end_date__isnull=True)
		paginator = Paginator(data_obj, 8)
		page_number = request.GET.get('page')
		rating_obj = paginator.get_page(page_number)
		return render(request,self.template_name,locals())




class getRatingsReviewDetails(TemplateView):
	template_name = 'rating_review_details.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self, request,id):
		rating_obj =  ServiceProviderRatingReviews.objects.filter(id=id,end_date__isnull=True).first()
		return render(request,self.template_name,locals())




class deleteRatingReview(TemplateView):
	def get(self, request,id):
		cat_obj  =  ServiceProviderRatingReviews.objects.filter(id=id,end_date__isnull = True ).first()
		cat_obj.delete()
		messages.success(request, "Deleted Successfully")
		return redirect('/get-ratings-reviews-list')
	


def exportCSVRatingReview(request):
	queryset = ServiceProviderRatingReviews.objects.all()
	response = HttpResponse(content_type='text/csv')
	response['Content-Disposition'] = 'attachment; filename="refund.csv"'
	writer = csv.writer(response)
	writer.writerow(['Customer Name', 'Service Provider Name', 'Rating','Review','Created at'])

	# Write the data rows
	for item in queryset:
		writer.writerow([item.user.first_name+' '+item.user.last_name, item.service_provider.first_name+' '+item.service_provider.last_name, item.rating , item.review ,item.start_date])
	return response



class payoutListing(TemplateView):
	template_name = 'payout_listing.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self, request):
		data_obj =  ServiceProviderPayoutTranscation.objects.all().order_by('-id')
		paginator = Paginator(data_obj, 8)
		page_number = request.GET.get('page')
		pay_obj = paginator.get_page(page_number)
		return render(request,self.template_name,locals())
	
from django.shortcuts import get_object_or_404

def update_transaction_status(request):
    transaction_id = request.POST.get('transaction_id')
    new_status = request.POST.get('new_status')
    pay = get_object_or_404(ServiceProviderPayoutTranscation, id=transaction_id)
    pay.transcation_status = new_status
    pay.save()

    return JsonResponse({'success': True})



class otherSettings(TemplateView):
	template_name = 'other_settings.html'
	@method_decorator(login_required(login_url='/admin-login'))
	def get(self, request):
		other_obj =  OtherSettings.objects.all().first()
		return render(request,self.template_name,locals())
	def post(self,request):
		form = forms.addothersettingform(request.POST)
		if form.is_valid():
			platform_fee =  form.cleaned_data.get('platform_fees')
			admin_commission =  form.cleaned_data.get('admin_commission')
			check_data = OtherSettings.objects.all().first()
			if check_data:
				check_data.platform_fee = platform_fee
				check_data.admin_commission = admin_commission
				check_data.save()
			else:
				OtherSettings.objects.create(platform_fee = platform_fee,admin_commission=admin_commission)
			messages.success(request, "Updated Successfully")
			return redirect('/other-settings')
		else:
			return render(request,self.template_name,locals()) 
		
