from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
import requests
from .models import *
import random
from datetime import datetime
from django.conf import settings
from passlib.hash import django_pbkdf2_sha256 as handler
from admin_api.functions import *
from django.contrib.auth import authenticate
import math, random, pytz, string
from django.template.loader import render_to_string
from django.core import mail
from django.core.mail import EmailMultiAlternatives
from django.contrib.auth.models import User
from rest_framework_simplejwt.tokens import RefreshToken
import re
from admin_api.models import Categories
from admin_api.models import *
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from customer_api.models import *
from rest_framework.authentication import get_authorization_header
import jwt
from django.db.models import Q
from subscription_api.models import *
from django.db.models import Count
import ast
from customer_api.authentication import authenticated
from rest_framework.permissions import IsAuthenticated
from django.utils.timezone import now
# Create your views here.
from rest_framework import serializers
from django.db.models import Sum


class getPropertyProject(APIView):
	def get(self,request):
		try:
			try:
				uid = authenticated(request)
			except Exception as e:
				uid = None  # Allow unauthenticated users
			customerObj = Customer.objects.filter(user=uid).first()
			sort_data = self.request.query_params.get('sort_data')
			filter_data =   self.request.query_params.get('filter_data')
			# purchase_price_start =  self.request.query_params.get('purchase_price_start')
			# purchase_price_end =  self.request.query_params.get('purchase_price_end')
			location = self.request.query_params.get('location')
			property_id=request.GET.get("id")
			# bedroom_min = self.request.query_params.get('bedroom_min')
			# bedroom_max = self.request.query_params.get('bedroom_max')
			return_on_investment_start =  self.request.query_params.get('return_on_investment_start')
			return_on_investment_end =  self.request.query_params.get('return_on_investment_end')

			cashflow_pcm_start =  self.request.query_params.get('cashflow_pcm_start')
			cashflow_pcm_end =  self.request.query_params.get('cashflow_pcm_end')

			finder_fees_start =  self.request.query_params.get('finder_fees_start')
			finder_fees_end =  self.request.query_params.get('finder_fees_end')
			sort_price = request.GET.get('sort_price')
			sort_upload_date = request.GET.get('sort_upload_date')
			subscription_tyre = request.GET.get('subscription_tyre')
			# The above code is not doing anything. It consists of a single line with the word "category"
			# followed by three hash symbols, which are used to create comments in Python.
			category = request.GET.get('category')
			if filter_data == 'true':
				lookups = Q()
				# if purchase_price_end:
				# 	lookups.add(Q(price__range=(purchase_price_start,purchase_price_end)), Q.AND)
				if location:
					lookups.add(Q(town__icontains=location), Q.AND)
				# if bedroom_min and bedroom_max:
				# 	lookups.add(Q(bedroom__range=(bedroom_min,bedroom_max)), Q.AND)
				if return_on_investment_end:
					lookups.add(Q(return_on_investment__range=(return_on_investment_start,return_on_investment_end)), Q.AND)
				if cashflow_pcm_end:
					lookups.add(Q(cashflow_pcm__range=(cashflow_pcm_start,cashflow_pcm_end)), Q.AND)
				# if finder_fees_start:
				# 	lookups.add(Q(finder_fees__range=(finder_fees_start,finder_fees_end)), Q.AND)
				if category:
					lookups.add(Q(category__icontains=category), Q.AND)


				if sort_data == "Newest":
					property_obj = PropertyProject.objects.filter(lookups,end_date__isnull = True,status= 1).order_by('-id').exclude(id=property_id)
				elif sort_data == "oldest":
					property_obj = PropertyProject.objects.filter(lookups,end_date__isnull = True,status= 1).order_by('id').exclude(id=property_id)
				else:
					property_obj = PropertyProject.objects.filter(lookups,end_date__isnull = True,status= 1).order_by('-id').exclude(id=property_id)
			else:
				property_obj = PropertyProject.objects.filter(end_date__isnull = True,status= 1).order_by('-id').exclude(id=property_id)[:10]

			allData=[]
			for property_obj in property_obj:
				favourite_obj = PropertyProjectFavourite.objects.filter(property=property_obj.id,customerId=customerObj).first()
				if favourite_obj:
					favourite = True
				else:
					favourite = False

				if property_obj.status == 0:
					status_info = "Pending"
				elif property_obj.status == 1:
					status_info = "Approved"
				else:
					status_info = "Disapproved"
				# cost_to_consider_new = float(property_obj.cost_to_consider)
				alldata = {
				'id': property_obj.id,
				'customer_id':property_obj.customerId.id,
				'fullname': property_obj.customerId.firstName+' '+ property_obj.customerId.lastName,
				'spend_too_much_time':property_obj.spend_too_much_time,
				'most_useless_skill':property_obj.most_useless_skill,
				'fun_act':property_obj.fun_act,
				'biography':property_obj.biography,
				'short_title':property_obj.short_title,
				'property_overview':property_obj.property_overview,
				'property_description':property_obj.property_description,
				'image_data':ast.literal_eval(property_obj.image_data.strip()) if property_obj.image_data and property_obj.image_data.strip() else [],
				'videos':property_obj.videos,
				'property_document':property_obj.property_document,
				'category':property_obj.category,
				'property_name':property_obj.property_name,
				'property_dimension':property_obj.property_dimension,
				'country':property_obj.country,
				'state':property_obj.state,
				'city':property_obj.city,
				'postal_code':property_obj.postal_code,
				'landmark':property_obj.landmark,
				'house_number':property_obj.house_number,
				'location':property_obj.location,
				'latitude':property_obj.latitude,
				'longitude':property_obj.longitude,
				'facility':ast.literal_eval(property_obj.facility.strip()) if property_obj.facility and property_obj.facility.strip() else [],
				'benefits':ast.literal_eval(property_obj.benefits.strip()) if property_obj.benefits and property_obj.benefits.strip() else [],
				'return_on_investment':property_obj.return_on_investment,
				'finder_fee':property_obj.finder_fee,
				'gross_income':property_obj.gross_income,
				'price':property_obj.price,
				'cashflow_pcm':property_obj.cashflow_pcm,
				'total_termination_fee':property_obj.total_termination_fee,
				'purchase_price':property_obj.purchase_price,
				'potential_cashflow_pcm':property_obj.potential_cashflow_pcm,
				'investment_finder_fee':property_obj.investment_finder_fee,
				'investment_return_on_investment_fee':property_obj.investment_return_on_investment_fee,
				'rental':property_obj.rental,
				'the_vision':property_obj.the_vision,
				'cost_to_consider':property_obj.cost_to_consider,
				'capital_required':property_obj.capital_required,
				'cashflow_forecast':property_obj.cashflow_forecast,
				'investment_finder_fee':property_obj.investment_finder_fee,
				'rent_to_landlord':property_obj.rent_to_landlord,
				'bill_utilities':property_obj.bill_utilities,
				'status':status_info,
				'favourite':favourite,
				}
				
				allData.append(alldata)
				if filter_data == 'true':
					if subscription_tyre:
						allData = [data for data in allData if data['subscription_type'] == int(subscription_tyre)]
					if sort_price == 'ascending':
						allData = sorted(allData, key=lambda x: x['filter_price'])
					elif sort_price == 'desending':
						allData = sorted(allData, key=lambda x: x['filter_price'], reverse=True)
					if sort_upload_date == "oldest":
						allData = sorted(allData, key=lambda x: x['created_date'])
					elif sort_upload_date == "latest":
						allData = sorted(allData, key=lambda x: x['created_date'], reverse=True)

			return Response({'status_code':status.HTTP_200_OK,'status_message':'Fetched successfully','data':allData},status=status.HTTP_200_OK)
		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class getPropertyProjectDetails(APIView):
	def get(self,request):
		try:
			property_id = self.request.query_params.get('id')
			if not property_id:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Property Id is required'},status=status.HTTP_400_BAD_REQUEST)
			property_obj = PropertyProject.objects.filter(id=property_id).first()
			if not property_obj:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Property project not found'},status=status.HTTP_400_BAD_REQUEST)
			if property_obj.status == 0:
				status_info = "Pending"
			elif property_obj.status == 1:
				status_info = "Approved"
			else:
				status_info = "Disapproved"

			facilities_list = ast.literal_eval(property_obj.facility)

			# Fetch each facility name and icon from the Facilities model
			facility_details = []
			for facility_name in facilities_list:
				facility = Facilities.objects.filter(name=facility_name).first()
				if facility:
					facility_details.append({
						'name': facility.name,
						'icon': facility.icon
					})
				else:
					facility_details.append({
						'name': facility_name,
						'icon': None
					})

			alldata={

				'id': property_obj.id,
				'customer_id':property_obj.customerId.id,
				'fullname': property_obj.customerId.firstName+' '+ property_obj.customerId.lastName,
				'spend_too_much_time':property_obj.spend_too_much_time,
				'most_useless_skill':property_obj.most_useless_skill,
				'fun_act':property_obj.fun_act,
				'biography':property_obj.biography,
				'short_title':property_obj.short_title,
				'property_overview':property_obj.property_overview,
				'property_description':property_obj.property_description,
				'image_data':ast.literal_eval(property_obj.image_data.strip()) if property_obj.image_data and property_obj.image_data.strip() else [],
				'videos':property_obj.videos,
				'property_document':property_obj.property_document,
				'category':property_obj.category,
				'property_name':property_obj.property_name,
				'property_dimension':property_obj.property_dimension,
				'country':property_obj.country,
				'state':property_obj.state,
				'city':property_obj.city,
				'postal_code':property_obj.postal_code,
				'landmark':property_obj.landmark,
				'house_number':property_obj.house_number,
				'location':property_obj.location,
				'latitude':property_obj.latitude,
				'longitude':property_obj.longitude,
				'facility':ast.literal_eval(property_obj.facility.strip()) if property_obj.facility and property_obj.facility.strip() else [],
				'benefits':ast.literal_eval(property_obj.benefits.strip()) if property_obj.benefits and property_obj.benefits.strip() else [],
				'return_on_investment':property_obj.return_on_investment,
				'finder_fee':property_obj.finder_fee,
				'gross_income':property_obj.gross_income,
				'price':property_obj.price,
				'cashflow_pcm':property_obj.cashflow_pcm,
				'total_termination_fee':property_obj.total_termination_fee,
				'purchase_price':property_obj.purchase_price,
				'potential_cashflow_pcm':property_obj.potential_cashflow_pcm,
				'investment_finder_fee':property_obj.investment_finder_fee,
				'investment_return_on_investment_fee':property_obj.investment_return_on_investment_fee,
				'rental':property_obj.rental,
				'the_vision':property_obj.the_vision,
				'cost_to_consider':property_obj.cost_to_consider,
				'capital_required':property_obj.capital_required,
				'cashflow_forecast':property_obj.cashflow_forecast,
				'investment_finder_fee':property_obj.investment_finder_fee,
				'rent_to_landlord':property_obj.rent_to_landlord,
				'bill_utilities':property_obj.bill_utilities,
				'status':status_info,


			}
			return Response({'status_code':status.HTTP_200_OK,'message':'Property project details fetched successfully','data':alldata},status=status.HTTP_200_OK)
		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class favUnfavPropertyProject(APIView):
	def post(self,request):
		try:
			token = get_authorization_header(request)
			if token is None or token == "null" or token.strip() == "":
				raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
			decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
			user_id = decoded['user_id']
			customerObj=Customer.objects.filter(user=user_id).first()
			property_project_id = request.data.get('property_project_id')
			if not property_project_id:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Property project id is required'},status=status.HTTP_400_BAD_REQUEST)
			pro_obj = PropertyProject.objects.filter(id=property_project_id).first()
			if not pro_obj:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No property project found'},status=status.HTTP_400_BAD_REQUEST)
			favourite_post, created = PropertyProjectFavourite.objects.get_or_create(property=pro_obj,customerId=customerObj,is_favourite=1)
			if not created:
				favourite_post.delete()
				return Response({'status_code':status.HTTP_200_OK,'status_message':'Removed from favourite list'},status=status.HTTP_200_OK)
			else:
				favourite_post.save()
				return Response({'status_code':status.HTTP_200_OK,'status_message':'Added to favourite list.'},status=status.HTTP_200_OK)
		except Exception as e:
			return Response({"status":status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class getBussinessForSale(APIView):
	def get(self,request):
		try:
			token = get_authorization_header(request)
			if token:
				decoded = jwt.decode(token, settings.SECRET_KEY)
				user_id = decoded['user_id']
				customerObj=Customer.objects.filter(user=user_id).first()
			else:
				customerObj= 0
			filter_data = self.request.query_params.get('filter_data')
			sort_data = self.request.query_params.get('sort_data')
			suggested_price_start = self.request.query_params.get('suggested_price_start')
			suggested_price_end = self.request.query_params.get('suggested_price_end')
			total_turnover_start = self.request.query_params.get('total_turnover_start')
			total_turnover_end = self.request.query_params.get('total_turnover_end')
			operating_profit_start = self.request.query_params.get('operating_profit_start')
			operating_profit_end = self.request.query_params.get('operating_profit_end')
			sort_price = request.GET.get('sort_price')
			sort_upload_date = request.GET.get('sort_upload_date')
			subscription_tyre = request.GET.get('subscription_tyre')
			if filter_data == 'true':
				lookups = Q()
				if suggested_price_end:
					lookups.add(Q(cost__range=(suggested_price_start,suggested_price_end)), Q.AND)
				if total_turnover_end:
					lookups.add(Q(total_turnover__range=(total_turnover_start,total_turnover_end)), Q.AND)
				if operating_profit_end:
					lookups.add(Q(other_operating_cost__range=(operating_profit_start,operating_profit_end)), Q.AND)


				if sort_data == "Newest":
					bussiness_obj = BussinessForSale.objects.filter(lookups).order_by('-id')
				elif sort_data == "oldest":
					bussiness_obj = BussinessForSale.objects.filter(lookups).order_by('id')
				else:
					bussiness_obj = BussinessForSale.objects.filter(lookups).order_by('-id')

			else:
				bussiness_obj = BussinessForSale.objects.filter(end_date__isnull = True).order_by('-subscription_type')
			allData=[]
			for bussiness in bussiness_obj:
				favourite_obj = BussinessForSaleFavourite.objects.filter(bussiness=bussiness.id,customerId=customerObj).first()
				if favourite_obj:
					favourite = True
				else:
					favourite = False
				alldata = {
						'id': bussiness.id,
						'customer_name' : bussiness.customerId.firstName +' '+ bussiness.customerId.lastName,
						'company_name': bussiness.company_name,
						'short_title': bussiness.short_title,
						'image_data': ast.literal_eval(bussiness.image_data),
						'videos': bussiness.videos,
						'videos_thumbnail': bussiness.videos_thumbnail,
						'company_name': bussiness.company_name,
						'description': bussiness.description,
						'total_turnover': bussiness.total_turnover,
						'rent': bussiness.rent,
						'established_year': bussiness.established_year,
						'premises': bussiness.premises,
						'years_of_work': bussiness.years_of_work,
						'operation_concept': bussiness.operation_concept,
						'operation_opening_hours': bussiness.operation_opening_hours,
						'turnover_last_year': bussiness.turnover_last_year,
						'salary_percentage': bussiness.salary_percentage,
						'other_operating_cost': bussiness.other_operating_cost,
						'cost': bussiness.cost,
						'reason_for_sale':bussiness.reason_for_sale,
						'website_link':bussiness.website_link,
						'number_of_employes':bussiness.number_of_employes,
						'other_operating_cost':bussiness.other_operating_cost,
						'area':bussiness.area,
						'term_of_lease': bussiness.term_of_lease,
						'document':ast.literal_eval(bussiness.document),
						'details': bussiness.details,
						'service':bussiness.service,
						'operations':bussiness.operations,
						'market_initatives':bussiness.market_initatives,
						'advantage_and_oppurtunity':bussiness.advantage_and_oppurtunity,
						'valuation':bussiness.valuation,
						'owner_name':bussiness.owner_name,
						'phone':bussiness.phone,
						'telephone':bussiness.telephone,
						'email':bussiness.email,
						'company':bussiness.company,
						'public_order':bussiness.public_order,
						'avaiable_attachment':bussiness.avaiable_attachment,
						'location':bussiness.location,
						'latitude':bussiness.latitude,
						'longitude':bussiness.longitude,
						'is_favourite':favourite,

				}
				allData.append(alldata)
				if filter_data == 'true':
					if subscription_tyre:
						allData = [data for data in allData if data['subscription_type'] == int(subscription_tyre)]
					if sort_price == 'ascending':
						allData = sorted(allData, key=lambda x: x['filter_price'])
					elif sort_price == 'desending':
						allData = sorted(allData, key=lambda x: x['filter_price'], reverse=True)
					if sort_upload_date == "oldest":
						allData = sorted(allData, key=lambda x: x['created_date'])
					elif sort_upload_date == "latest":
						allData = sorted(allData, key=lambda x: x['created_date'], reverse=True)
			return Response({'status_code':status.HTTP_200_OK,'status_message':'Fetched successfully','data':allData},status=status.HTTP_200_OK)
		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class getBussinessForSaleDetails(APIView):
	def get(self,request):
		try:
			bussiness_id = self.request.query_params.get('id')
			if not bussiness_id:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Bussiness Id is required'},status=status.HTTP_400_BAD_REQUEST)
			bussiness_obj = BussinessForSale.objects.filter(id=bussiness_id).first()
			if not bussiness_obj:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No bussiness for sale found'},status=status.HTTP_400_BAD_REQUEST)
			print(bussiness_obj.id, '   bussiness_obj.id')
			investments = inquirePropertyProject.objects.filter(
				property_type='BusinessSale',
				bussiness_for_sale_id=bussiness_obj.id,
				contract_status='Deal-Completed'
			).aggregate(total_investment=Sum('investment_amount'))
			# qs = inquirePropertyProject.objects.filter(property_type='BusinessSale')
			# qs = inquirePropertyProject.objects.filter(bussiness_for_sale_id=bussiness_obj.id)
			# print(qs.count(),'---------------')
			total_investment = investments['total_investment'] or 0.0
			# print(total_investment,'-----totak_investment bussiness_for_sale_id')

			try:
				max_drawing = float(bussiness_obj.cost)
			except (ValueError, TypeError):
				max_drawing = 0.0

			if max_drawing > 0:
				percentage_invested = (total_investment / max_drawing) * 100
			else:
				percentage_invested = 0.0
			can_stop_investment = total_investment > 0.0
			if can_stop_investment:
				five_percent_of_investment = total_investment * 0.05
			else:
				five_percent_of_investment = 0.0
			alldata = {
				'id': bussiness_obj.id,
				'customer_name' : bussiness_obj.customerId.firstName +' '+ bussiness_obj.customerId.lastName,
				'customer_id' : bussiness_obj.customerId.id,
				'customerPhoneNumber' : bussiness_obj.customerId.phoneNumber,
				'customerImage' : bussiness_obj.customerId.profileImage,
				'company_name': bussiness_obj.company_name,
				'short_title': bussiness_obj.short_title,
				'image_data': ast.literal_eval(bussiness_obj.image_data),
				'videos': bussiness_obj.videos,
				'videos_thumbnail': bussiness_obj.videos_thumbnail,
				'company_name': bussiness_obj.company_name,
				'description': bussiness_obj.description,
				'total_turnover': bussiness_obj.total_turnover,
				'phone_number':bussiness_obj.phone,
				'rent': bussiness_obj.rent,
				'established_year': bussiness_obj.established_year,
				'premises': bussiness_obj.premises,
				'years_of_work': bussiness_obj.years_of_work,
				'operation_concept': bussiness_obj.operation_concept,
				'operation_opening_hours': bussiness_obj.operation_opening_hours,
				'turnover_last_year': bussiness_obj.turnover_last_year,
				'salary_percentage': bussiness_obj.salary_percentage,
				'other_operating_cost': bussiness_obj.other_operating_cost,
				'cost': bussiness_obj.cost,
				'total_investment': total_investment,
				'percentage_invested': round(percentage_invested, 2),
				'can_stop_investment': can_stop_investment,
				'payment_done': bussiness_obj.payment_done,
				'admin_cut':five_percent_of_investment,
				'reason_for_sale':bussiness_obj.reason_for_sale,
				'website_link':bussiness_obj.website_link,
				'number_of_employes':bussiness_obj.number_of_employes,
				'other_operating_cost':bussiness_obj.other_operating_cost,
				'area':bussiness_obj.area,
				'term_of_lease': bussiness_obj.term_of_lease,
				'document':ast.literal_eval(bussiness_obj.document),
				'details': bussiness_obj.details,
				'service':bussiness_obj.service,
				'operations':bussiness_obj.operations,
				'market_initatives':bussiness_obj.market_initatives,
				'advantage_and_oppurtunity':bussiness_obj.advantage_and_oppurtunity,
				'valuation':bussiness_obj.valuation,
				'owner_name':bussiness_obj.owner_name,
				'phone':bussiness_obj.phone,
				'telephone':bussiness_obj.telephone,
				'email':bussiness_obj.email,
				'company':bussiness_obj.company,
				'public_order':bussiness_obj.public_order,
				'avaiable_attachment':bussiness_obj.avaiable_attachment,
				'location':bussiness_obj.location,
				'latitude':bussiness_obj.latitude,
				'longitude':bussiness_obj.longitude,
				'is_draft': bussiness_obj.is_draft,
				'country': bussiness_obj.country,
				'state': bussiness_obj.state,
				'city': bussiness_obj.city,
				'floor': bussiness_obj.floor,
				'postal_code': bussiness_obj.postal_code,
				'landmark': bussiness_obj.landmark,
				'shareholder_name': bussiness_obj.shareholder_name,
				'shareholder_share': bussiness_obj.shareholder_share,
				'shareholder_description': bussiness_obj.shareholder_description,

			}
			return Response({'status_code':status.HTTP_200_OK,'status_message':'Fetched successfully','data':alldata},status=status.HTTP_200_OK)
		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)




class inquireBussinessSale(APIView):
	def post(self,request):
		try:
			bussiness_id = request.data.get('bussiness_id')
			if not bussiness_id:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Bussiness Id is required'},status=status.HTTP_400_BAD_REQUEST)

			bussiness_obj = BussinessForSale.objects.filter(id=bussiness_id,status=1).first()
			if not bussiness_obj:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No bussiness sale found for this id.'},status=status.HTTP_400_BAD_REQUEST)

			name = request.data.get('name')
			email = request.data.get('email')
			telephone = request.data.get('telephone')
			message = request.data.get('message')

			if not email:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Email is required'},status=status.HTTP_400_BAD_REQUEST)
			if not name:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Name is required'},status=status.HTTP_400_BAD_REQUEST)
			if not telephone:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Telephone is required'},status=status.HTTP_400_BAD_REQUEST)
			if not message:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Message is required'},status=status.HTTP_400_BAD_REQUEST)

			subject = "Bussiness sale inquire"
			message_send = EmailMultiAlternatives(subject=subject, from_email=settings.EMAIL_HOST_USER, to=['admin123@yopmail.com'],body=f"{telephone} wants to inquire about the {bussiness_obj.company_name} bussiness sale.")
			message_send.send(fail_silently=False)
			return Response({'status_code':status.HTTP_200_OK,'status_message':'Send successfully'},status=status.HTTP_200_OK)

		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class getHousingForRent(APIView):
	def get(self,request):
		try:
			token = get_authorization_header(request)
			if token:
				decoded = jwt.decode(token, settings.SECRET_KEY)
				user_id = decoded['user_id']
				customerObj=Customer.objects.filter(user=user_id).first()
			else:
				customerObj= 0
			# filter_data = self.request.query_params.get('filter_data')
			# wanted_from = self.request.query_params.get('wanted_from')
			# property_type = self.request.query_params.get('property_type')
			# max_month_price = self.request.query_params.get('max_month_price')
			# sort_price = request.GET.get('sort_price')
			# sort_upload_date = request.GET.get('sort_upload_date')
			# subscription_tyre = request.GET.get('subscription_tyre')
			# if filter_data == 'true':
			# 	lookups = Q()
			# 	if wanted_from:
			# 		lookups.add(Q(wanted_from=wanted_from), Q.AND)
			# 	if property_type:
			# 		lookups.add(Q(property_type=property_type), Q.AND)
			# 	if max_month_price:
			# 		lookups.add(Q(max_month_price=max_month_price), Q.AND)
			# 	rent_obj = HouseWantedForRent.objects.filter(lookups,status=1)
			# else:
			rent_obj = HouseWantedForRent.objects.filter(end_date__isnull = True).order_by('-subscription_type')
			allData =[]
			for rent in rent_obj:
				favourite_obj = HouseRentFavourite.objects.filter(house_rent=rent.id,customerId=customerObj).first()
				if favourite_obj:
					favourite = True
				else:
					favourite = False
				alldata = {
					'id':rent.id,
					'short_title':rent.short_title,
					'full_name':rent.first_name+' '+rent.last_name,
					'image':rent.image,
					'gender':rent.gender,
					'address':rent.address,
					'nationality':rent.nationality,
					'max_month_price':rent.max_month_price,
					# 'filter_price':rent.max_month_price,
					'rental_period':rent.rental_period,
					'desired_start_date':rent.desired_start_date,
					'pet':rent.pet,
					'location':rent.location,
					'subscription_type':rent.subscription_type,
					'created_date':rent.start_date,
					'is_favourite':favourite
				}
				allData.append(alldata)
				# if filter_data == 'true':
				# 	if subscription_tyre:
				# 		allData = [data for data in allData if data['subscription_type'] == int(subscription_tyre)]
				# 	if sort_price == 'ascending':
				# 		allData = sorted(allData, key=lambda x: x['filter_price'])
				# 	elif sort_price == 'desending':
				# 		allData = sorted(allData, key=lambda x: x['filter_price'], reverse=True)
				# 	if sort_upload_date == "oldest":
				# 		allData = sorted(allData, key=lambda x: x['created_date'])
				# 	elif sort_upload_date == "latest":
				# 		allData = sorted(allData, key=lambda x: x['created_date'], reverse=True)
			return Response({'status_code':status.HTTP_200_OK,'status_message':'Fetched successfully','data':allData},status=status.HTTP_200_OK)
		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class getHousingForRentDetails(APIView):
	def get(self,request):
		try:
			rent_id =  self.request.query_params.get('rent_id')
			if not rent_id:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Rent Id is required'},status=status.HTTP_400_BAD_REQUEST)
			rent_obj = HouseWantedForRent.objects.filter(id=rent_id).first()
			if not rent_obj:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No housing wanted for rent found'},status=status.HTTP_400_BAD_REQUEST)
			alldata={
					'id': rent_obj.id,
				'short_title':rent_obj.short_title,
				'customer_id':rent_obj.customerId.id,
				'fullname': rent_obj.first_name+' '+ rent_obj.last_name,

				'profile_visiblity':rent_obj.profile_visiblity,
				'profile_hidden':rent_obj.profile_hidden,
				'image': ast.literal_eval(rent_obj.image),
				'first_name': rent_obj.first_name,
				'last_name': rent_obj.last_name,
				'gender': rent_obj.gender,
				'dob': rent_obj.dob,
				'nationality': rent_obj.nationality,
				'phone_number':rent_obj.phone_number,
				'email': rent_obj.email,
				'quantity': rent_obj.quantity,
				'rental_period': rent_obj.rental_period,
				'max_rent': rent_obj.max_rent,
				'from_date': rent_obj.from_date,
				'housing_type':rent_obj.housing_type,
				'number_of_people':rent_obj.number_of_people,
				'max_month_price': rent_obj.max_month_price,
				'desired_start_date':rent_obj.desired_start_date,
				'desired_area': rent_obj.desired_area,
				'latitude':rent_obj.latitude,
				'longitude':rent_obj.longitude,
				'location':rent_obj.location,
				'about':rent_obj.about,
				'education':rent_obj.education,
				'martial_status':rent_obj.martial_status,
				'cleanliness':rent_obj.cleanliness,
				'party_habits':rent_obj.party_habits,
				'work':rent_obj.work,
				'interest':rent_obj.interest,
				'subscription_type':rent_obj.subscription_type,
				'is_draft':rent_obj.is_draft,
				'work':rent_obj.work,
		  		'country':rent_obj.country,
				'state':rent_obj.state,
				'city':rent_obj.city,
				'postal_code':rent_obj.postal_code,
				'landmark':rent_obj.landmark,
				'floor':rent_obj.floor,
				'description':rent_obj.description,



			}

			return Response({'status_code':status.HTTP_200_OK,'status_message':'Fetched successfully','data':alldata},status=status.HTTP_200_OK)
		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class sentMessageForRent(APIView):
	def post(self,request):
		try:
			rent_id = request.data.get('rent_id')
			if not rent_id:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Rent Id is required'},status=status.HTTP_400_BAD_REQUEST)
			rent_obj = HouseWantedForRent.objects.filter(id=rent_id,status=1).first()
			if not rent_obj:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No result found for this rent id'},status=status.HTTP_400_BAD_REQUEST)
			name = request.data.get('name')
			telephone = request.data.get('telephone')
			email = request.data.get('email')
			message = request.data.get('message')

			if not name: return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Name is required'},status=status.HTTP_400_BAD_REQUEST)
			if not telephone: return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'telephone is required'},status=status.HTTP_400_BAD_REQUEST)
			if not email: return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'email is required'},status=status.HTTP_400_BAD_REQUEST)
			if not message: return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'message is required'},status=status.HTTP_400_BAD_REQUEST)

			subject = "House wanted for Rent"
			message_send = EmailMultiAlternatives(subject=subject, from_email=settings.EMAIL_HOST_USER, to=[rent_obj.email],body=f"Hello this side {name}.Please contact us at {telephone} or {email}. Message:{message}")
			message_send.send(fail_silently=False)
			return Response({'status_code':status.HTTP_200_OK,'status_message':'Send successfully'},status=status.HTTP_200_OK)
		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class favouriteUnfavouriteHouseRent(APIView):
	def post(self,request):
		try:
			token = get_authorization_header(request)
			if token is None or token == "null" or token.strip() == "":
				raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
			decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
			user_id = decoded['user_id']
			customerObj=Customer.objects.filter(user=user_id).first()
			house_rent_id = request.data.get('house_rent_id')
			if not house_rent_id:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'House Rent ID is required'},status=status.HTTP_400_BAD_REQUEST)
			rent_obj = HouseWantedForRent.objects.filter(id=house_rent_id).first()
			if not rent_obj:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No product found'},status=status.HTTP_400_BAD_REQUEST)
			favourite_post, created = HouseRentFavourite.objects.get_or_create(house_rent=rent_obj,customerId=customerObj,is_favourite=1)
			if not created:
				favourite_post.delete()
				return Response({'status_code':status.HTTP_200_OK,'status_message':'Removed from favourite list'})
			else:
				favourite_post.save()
				return Response({'status_code':status.HTTP_200_OK,'status_message':'Added to favourite list.'})
		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class favouriteUnfavouriteCompanySeekingEquity(APIView):
	def post(self,request):
		# try:
		token = get_authorization_header(request)
		if token is None or token == "null" or token.strip() == "":
			raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
		decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
		user_id = decoded['user_id']
		# return Response({'status_code':status.HTTP_200_OK,'status_message':'Removed from favourite list','id':user_id})
		customerObj=Customer.objects.filter(user=user_id).first()
		customer_seeking_id = request.data.get('company_seeking_id')
		if not customer_seeking_id:
			return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Seeking ID is required'},status=status.HTTP_400_BAD_REQUEST)
		customer_seeking_obj = CompanySeekingEquity.objects.filter(id=customer_seeking_id).first()
		if not customer_seeking_obj:
			return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No Customer seeking  found'},status=status.HTTP_400_BAD_REQUEST)
		favourite_post, created = CompanySeekingEquityFavourite.objects.get_or_create(company_seek=customer_seeking_obj,customerId=customerObj,is_favourite=1)
		if not created:
			favourite_post.delete()
			return Response({'status_code':status.HTTP_200_OK,'status_message':'Removed from favourite list'})
		else:
			favourite_post.save()
			return Response({'status_code':status.HTTP_200_OK,'status_message':'Added to favourite list.'})
		# except Exception as e:
		# 	return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class getInvestmentMyCompany(APIView):
	def get(self,request):
		try:
			token = get_authorization_header(request)
			if token:
				decoded = jwt.decode(token, settings.SECRET_KEY)
				user_id = decoded['user_id']
				customerObj=Customer.objects.filter(user=user_id).first()
			else:
				customerObj= 0
			filter_data = self.request.query_params.get('filter_data')
			sort_price = request.GET.get('sort_price')
			sort_upload_date = request.GET.get('sort_upload_date')
			subscription_tyre = request.GET.get('subscription_tyre')

			investment_obj = InvestmentMyCompany.objects.filter(status=True,end_date__isnull = True)
			allData=[]
			for investment in investment_obj:
				favourite_obj = InvestmentMyCompanyFavourite.objects.filter(invest_company=investment.id,customerId=customerObj).first()
				if favourite_obj:
					favourite = True
				else:
					favourite = False
				alldata={
					'id':investment.id,
					'image_data':investment.image_data,
					'company_name': investment.property_name,
					'the_valuation': investment.the_valuation,
					'shares_for_sale': investment.shares_for_sale,
					'price_per_share':investment.price_per_share,
					'remaninig_shares': investment.remaninig_shares,
					'minimum_drawing': investment.minimum_drawing,
					'max_drawing': investment.max_drawing,
					'is_favourite':favourite,
					'subscription_type':investment.subscription_type,
					'created_date':investment.start_date,
					'filter_price':investment.nominal_share_price,
				}
				allData.append(alldata)
			if filter_data == 'true':
					if subscription_tyre:
						allData = [data for data in allData if data['subscription_type'] == int(subscription_tyre)]
					if sort_price == 'ascending':
						allData = sorted(allData, key=lambda x: x['filter_price'])
					elif sort_price == 'desending':
						allData = sorted(allData, key=lambda x: x['filter_price'], reverse=True)
					if sort_upload_date == "oldest":
						allData = sorted(allData, key=lambda x: x['created_date'])
					elif sort_upload_date == "latest":
						allData = sorted(allData, key=lambda x: x['created_date'], reverse=True)

			return Response({'status_code':status.HTTP_200_OK,'status_message':'Fetched successfully','data':allData},status=status.HTTP_200_OK)
		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class getInvestmentMyCompanyDetails(APIView):
	def get(self,request):
		try:
			investment_id = self.request.query_params.get('investment_id')
			if not investment_id:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Investment Id is required'},status=status.HTTP_400_BAD_REQUEST)
			investment_obj = InvestmentMyCompany.objects.filter(id=investment_id).first()
			if not investment_obj:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Investment my company not found'},status=status.HTTP_400_BAD_REQUEST)
			alldata = {

				'id': investment_obj.id,
				'company_logo':investment_obj.company_logo,
				'company_video':investment_obj.company_video,
				'customer_id':investment_obj.customerId.id,
				'fullname': investment_obj.customerId.firstName+' '+ investment_obj.customerId.lastName,
				'property_name' :investment_obj.property_name,
				'documents_data':investment_obj.documents_data,
				'property_type' :investment_obj.property_type,
				'company_established' :investment_obj.company_established,
				'company_email' :investment_obj.company_email,
				'company_phonenumber':investment_obj.company_phonenumber,
				'company_address' :investment_obj.company_address,
				'shareholders' :investment_obj.shareholders,
				'share' :investment_obj.share,
				'description' :investment_obj.description,
				'the_valuation' :investment_obj.the_valuation,
				'shares_for_sale' :investment_obj.shares_for_sale,
				'price_per_share' :investment_obj.price_per_share,
				'postal_code' :investment_obj.postal_code,
				'bank_acc_created' :investment_obj.bank_acc_created,
				'issue_account_no' :investment_obj.issue_account_no,
				'post_number' :investment_obj.post_number,
				'self_report' :investment_obj.self_report,
				'minimum_drawing' :investment_obj.minimum_drawing,
				'max_drawing' :investment_obj.max_drawing,
				'remaninig_shares' :investment_obj.remaninig_shares,
				'no_share_bfr_issue' :investment_obj.no_share_bfr_issue,
				'nominal_share_price' :investment_obj.nominal_share_price,
				'company_website' :investment_obj.company_website,
				'subscription_type' :investment_obj.subscription_type,
				'status' :investment_obj.status,
				'is_draft' :investment_obj.is_draft,
				'agency' :investment_obj.agency,
				"location": investment_obj.location,
				'latitude': investment_obj.latitude,
				'longitude': investment_obj.longitude,
				'status': investment_obj.status,

			}
			return Response({'status_code':status.HTTP_200_OK,'status_message':'Fetched successfully','data':alldata},status=status.HTTP_200_OK)
		except Exception as e:
			return Response({'status_code':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)




class buyShareInvestmentCompany(APIView):
	def get(self,request):
		try:
			token = get_authorization_header(request)
			if token is None or token == "null" or token.strip() == "":
				raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
			decoded = jwt.decode(token, settings.SECRET_KEY)
			user_id = decoded['user_id']
			customerObj=Customer.objects.filter(user=user_id).first()
			investment_company_id = self.request.query_params.get('investment_company_id')
			if not investment_company_id:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Investment Id is required'},status=status.HTTP_400_BAD_REQUEST)
			investment_obj = InvestmentMyCompany.objects.filter(id=investment_company_id).first()
			if not investment_obj:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Investment for company not found.'},status=status.HTTP_400_BAD_REQUEST)
			all_data = {
				'price_per_share':investment_obj.price_per_share,
				'minimum_drawing':investment_obj.minimum_drawing,
				'max_drawing':investment_obj.max_drawing,
				'share_for_sale':investment_obj.shares_for_sale,
			}
			return Response({'status_code':status.HTTP_200_OK,'status_message':'Fetched successfully','data':all_data},status=status.HTTP_200_OK)
		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

	def post(self,request):
		try:
			token = get_authorization_header(request)
			if token is None or token == "null" or token.strip() == "":
				raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
			decoded = jwt.decode(token, settings.SECRET_KEY)
			user_id = decoded['user_id']
			customerObj=Customer.objects.filter(user=user_id).first()
			investment_company_id = self.request.query_params.get('investment_company_id')
			if not investment_company_id:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Investment Id is required'},status=status.HTTP_400_BAD_REQUEST)
			investment_obj = InvestmentMyCompany.objects.filter(id=investment_company_id).first()
			if not investment_obj:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Investment for company not found.'},status=status.HTTP_400_BAD_REQUEST)
			total_share = request.data.get('total_share')
			if not total_share:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'total share is required'},status=status.HTTP_400_BAD_REQUEST)
			amount = request.data.get('amount')
			if not amount:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'amount is required'},status=status.HTTP_400_BAD_REQUEST)
			MyInvestmentsForCompany.objects.create(invested_company=investment_obj,customerId=customerObj,total_share=total_share,amount=amount)
			investment_obj.remaninig_shares -= int(total_share)
			investment_obj.save()
			url = 'https://api.escrow.com/2017-09-01/transaction'
			auth = ('developer@esferasoft.com', '16359_RCbQaGY8fVyZkgFGgW9HZ6blFl7wVpCTQ5Sq05HdNX2mvjWJyIsBdfmQ3b2cbbR0')
			payload = {
				"parties": [
					{
						"role": "buyer",
						"customer": 'developer@esferasoft.com'
					},
					{
						"role": "seller",
						"customer": 'amit@yopmail.com'
					}
				],
				"currency": "usd",
				"description": "Buy share for investment my company",
				"items": [
					{
						"title": "Buy share investment company",
						"description": "Buy share investment company",
						"type": "general_merchandise",
						"inspection_period": 259200,
						"quantity": 1,
						"schedule": [
							{
								"amount":  int(amount),
								"payer_customer":'developer@esferasoft.com',
								"beneficiary_customer": 'amit@yopmail.com'
							}
						],
					}
				]
			}

			response = requests.post(url, auth=auth, json=payload)
			if response.status_code == 201:
				return Response({'status_code':status.HTTP_200_OK,'status_message':'Success','data':response},status=status.HTTP_200_OK)
			else:
				return Response({'status_code':response.status_code,'status_message':'Something went wrong.Please try after sometime.'},status=response.status_code)

		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)



class getFavouriteUnfavouriteCompanyDetails(APIView):
	def post(self,request):
		try:
			token = get_authorization_header(request)
			if token is None or token == "null" or token.strip() == "":
				raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
			decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
			user_id = decoded['user_id']
			customerObj=Customer.objects.filter(user=user_id).first()
			invest_id = request.data.get('invest_id')
			if not invest_id:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Investment Id is required'},status=status.HTTP_400_BAD_REQUEST)
			invest_obj = InvestmentMyCompany.objects.filter(id=invest_id).first()
			if not invest_obj:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No investment my company found'},status=status.HTTP_400_BAD_REQUEST)
			favourite_post, created = InvestmentMyCompanyFavourite.objects.get_or_create(invest_company=invest_obj,customerId=customerObj,is_favourite=1)
			if not created:
				favourite_post.delete()
				return Response({'status_code':status.HTTP_200_OK,'status_message':'Removed from favourite list'},status=status.HTTP_200_OK)
			else:
				favourite_post.save()
				return Response({'status_code':status.HTTP_200_OK,'status_message':'Added to favourite list.'},status=status.HTTP_200_OK)
		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class inquireInvestmentCompany(APIView):
	def post(self,request):
		try:
			investment_id = request.data.get('investment_id')
			if not investment_id:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Investment Id is required'},status=status.HTTP_400_BAD_REQUEST)

			investment_obj = InvestmentMyCompany.objects.filter(id=investment_id,status=1).first()
			if not investment_obj:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No investment for company found for this id.'},status=status.HTTP_400_BAD_REQUEST)

			name = request.data.get('name')
			email = request.data.get('email')
			telephone = request.data.get('telephone')
			message = request.data.get('message')

			if not email:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Email is required'},status=status.HTTP_400_BAD_REQUEST)
			if not name:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Name is required'},status=status.HTTP_400_BAD_REQUEST)
			if not telephone:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Telephone is required'},status=status.HTTP_400_BAD_REQUEST)
			if not message:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Message is required'},status=status.HTTP_400_BAD_REQUEST)

			subject = "Investment for company inquire "
			message_send = EmailMultiAlternatives(subject=subject, from_email=settings.EMAIL_HOST_USER, to=['admin123@yopmail.com'],body=f"{telephone} wants to inquire about the {investment_obj.company_name} investment for company.")
			message_send.send(fail_silently=False)
			return Response({'status_code':status.HTTP_200_OK,'status_message':'Send successfully'},status=status.HTTP_200_OK)

		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class getInvestmentForProject(APIView):
	def get(self,request):
		try:
			token = get_authorization_header(request)
			if token:
				decoded = jwt.decode(token, settings.SECRET_KEY)
				user_id = decoded['user_id']
				customerObj=Customer.objects.filter(user=user_id).first()
			else:
				customerObj= 0

			filter_data = self.request.query_params.get('filter_data')
			sort_price = request.GET.get('sort_price')
			sort_upload_date = request.GET.get('sort_upload_date')
			subscription_tyre = request.GET.get('subscription_tyre')

			investment_obj = InvestmentMyProject.objects.filter(end_date__isnull = True)
			allData = []
			for investment in investment_obj:
				favourite_obj = InvestmentMyProjectFavourite.objects.filter(invest_project=investment.id,customerId=customerObj).first()
				if favourite_obj:
					favourite = True
				else:
					favourite = False
				alldata = {
					'id': investment.id,
					'customer_id':investment.customerId.id,
					'fullname': investment.customerId.firstName+' '+ investment.customerId.lastName,
					'property_name':investment.property_name,
					'image_data':investment.image_data,
					'videos':investment.videos,
					'documents_data':investment.documents_data,
					'property_type':investment.property_type,
					'assest_equality':investment.assest_equality,
					'investment_highlight':investment.investment_highlight,
					'equity_price':investment.equity_price,
					'lp_equity_percent':investment.lp_equity_percent,
					'gp_equity_percent':investment.gp_equity_percent,
					'debt_percent':investment.debt_percent,
					'property_at_glance_title':investment.property_at_glance_title,
					'description':investment.description,
					'bussiness_plan':investment.bussiness_plan,
					'minimum_investment':investment.minimum_investment,
					'investment_strategy':investment.investment_strategy,
					'expected_attitude_price':investment.expected_attitude_price,
					'financed':investment.financed,
					'target_return_on_cost':investment.target_return_on_cost,
					'target_irr':investment.target_irr,
					'lp_equity_percent':investment.lp_equity_percent,
					'offered_by':investment.offered_by,
					'estimated_first_distribution':investment.estimated_first_distribution,
					'type_of_investment':investment.type_of_investment,
					'phone_number':investment.phone_number,
					'measure_for_multiplier':investment.measure_for_multiplier,
					'address':investment.address,
					'location_details':investment.location_details,
					'property_summary':investment.property_summary,
					'property_details':investment.property_details,
					'overview':investment.overview,
					'debt_assumption':investment.debt_assumption,
					'location':investment.location,
					'latitude':investment.latitude,
					'longitude':investment.longitude,
					'is_favourite':favourite,
					'filter_price':investment.minimum_investment,
					'subscription_type':investment.subscription_type,
					'created_date':investment.start_date,
				}
				allData.append(alldata)
				if filter_data == 'true':
					if subscription_tyre:
						allData = [data for data in allData if data['subscription_type'] == int(subscription_tyre)]
					if sort_price == 'ascending':
						allData = sorted(allData, key=lambda x: x['filter_price'])
					elif sort_price == 'desending':
						allData = sorted(allData, key=lambda x: x['filter_price'], reverse=True)
					if sort_upload_date == "oldest":
						allData = sorted(allData, key=lambda x: x['created_date'])
					elif sort_upload_date == "latest":
						allData = sorted(allData, key=lambda x: x['created_date'], reverse=True)
			return Response({'status_code':status.HTTP_200_OK,'status_message':'Fetched successfully','data':allData},status=status.HTTP_200_OK)
		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class getInvestmentForProjectDetails(APIView):
	def get(self,request):
		try:
			investment_id = self.request.query_params.get('id')
			if not investment_id:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Investment Id is required'},status=status.HTTP_400_BAD_REQUEST)
			investment_obj = InvestmentMyProject.objects.filter(id=investment_id).first()
			if not investment_obj:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Investment project not found'},status=status.HTTP_400_BAD_REQUEST)
			alldata = {
					'id': investment_obj.id,
					'customer_id':investment_obj.customerId.id,
					'fullname': investment_obj.customerId.firstName+' '+ investment_obj.customerId.lastName,
					'property_name':investment_obj.property_name,
					'image_data':investment_obj.image_data,
					'videos':investment_obj.videos,
					'documents_data':investment_obj.documents_data,
					'property_type':investment_obj.property_type,
					'assest_equality':investment_obj.assest_equality,
					'investment_highlight':investment_obj.investment_highlight,
					'equity_price':investment_obj.equity_price,
					'lp_equity_percent':investment_obj.lp_equity_percent,
					'gp_equity_percent':investment_obj.gp_equity_percent,
					'debt_percent':investment_obj.debt_percent,
					'property_at_glance_title':investment_obj.property_at_glance_title,
					'description':investment_obj.description,
					'bussiness_plan':investment_obj.bussiness_plan,
					'minimum_investment':investment_obj.minimum_investment,
					'investment_strategy':investment_obj.investment_strategy,
					'expected_attitude_price':investment_obj.expected_attitude_price,
					'financed':investment_obj.financed,
					'target_return_on_cost':investment_obj.target_return_on_cost,
					'target_irr':investment_obj.target_irr,
					'lp_equity_percent':investment_obj.lp_equity_percent,
					'offered_by':investment_obj.offered_by,
					'estimated_first_distribution':investment_obj.estimated_first_distribution,
					'type_of_investment':investment_obj.type_of_investment,
					'phone_number':investment_obj.phone_number,
					'measure_for_multiplier':investment_obj.measure_for_multiplier,
					'address':investment_obj.address,
					'location_details':investment_obj.location_details,
					'property_summary':investment_obj.property_summary,
					'property_details':investment_obj.property_details,
					'overview':investment_obj.overview,
					'debt_assumption':investment_obj.debt_assumption,
					'location':investment_obj.location,
					'latitude':investment_obj.latitude,
					'longitude':investment_obj.longitude,
					'filter_price':investment_obj.minimum_investment,
					'subscription_type':investment_obj.subscription_type,
					'created_date':investment_obj.start_date,
			}
			return Response({'status_code':status.HTTP_200_OK,'status_message':'Fetched successfully','data':alldata},status=status.HTTP_200_OK)
		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class getFavouriteUnfavouriteProjectDetails(APIView):
	def post(self,request):
		try:
			token = get_authorization_header(request)
			if token is None or token == "null" or token.strip() == "":
				raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
			decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
			user_id = decoded['user_id']
			customerObj=Customer.objects.filter(user=user_id).first()
			invest_id = request.data.get('invest_id')
			if not invest_id:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Investment Id is required'},status=status.HTTP_400_BAD_REQUEST)
			prop_obj = InvestmentMyProject.objects.filter(id=invest_id).first()
			if not prop_obj:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No Investment project found'},status=status.HTTP_400_BAD_REQUEST)
			favourite_post, created = InvestmentMyProjectFavourite.objects.get_or_create(invest_project=prop_obj,customerId=customerObj,is_favourite=1)
			if not created:
				favourite_post.delete()
				return Response({'status_code':status.HTTP_200_OK,'status_message':'Removed from favourite list'},status=status.HTTP_200_OK)
			else:
				favourite_post.save()
				return Response({'status_code':status.HTTP_200_OK,'status_message':'Added to favourite list.'},status=status.HTTP_200_OK)
		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class inquireInvestmentProjectDetails(APIView):
	def post(self,request):
		try:
			investment_id = request.data.get('investment_id')
			if not investment_id:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Investment Id is required'},status=status.HTTP_400_BAD_REQUEST)

			investment_obj = InvestmentMyProject.objects.filter(id=investment_id,status=1).first()
			if not investment_obj:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No investment for project found for this id.'},status=status.HTTP_400_BAD_REQUEST)

			name = request.data.get('name')
			email = request.data.get('email')
			telephone = request.data.get('telephone')
			message = request.data.get('message')

			if not email:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Email is required'},status=status.HTTP_400_BAD_REQUEST)
			if not name:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Name is required'},status=status.HTTP_400_BAD_REQUEST)
			if not telephone:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Telephone is required'},status=status.HTTP_400_BAD_REQUEST)
			if not message:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Message is required'},status=status.HTTP_400_BAD_REQUEST)

			subject = "Investment for project inquire "
			message_send = EmailMultiAlternatives(subject=subject, from_email=settings.EMAIL_HOST_USER, to=['admin123@yopmail.com'],body=f"{telephone} wants to inquire about the {investment_obj.property_name} investment for property.")
			message_send.send(fail_silently=False)
			return Response({'status_code':status.HTTP_200_OK,'status_message':'Send successfully'},status=status.HTTP_200_OK)

		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class rentPropertyList(APIView):
	def get(self,request):
		try:
			try:
				uid = authenticated(request)
			except Exception as e:
				uid = 0  # Allow unauthenticated users
			customerObj = Customer.objects.filter(user=uid).first()

			property_id=request.GET.get('id')
			allData = []
			rentObj = RentProperty.objects.filter(end_date__isnull = True,status=1).order_by('-id').exclude(id=property_id)[:10]
			for rent in rentObj:
				# facilities_list = ast.literal_eval(rent.facilites)
				# facility_details = []
				# for facility_name in facilities_list:
				# 	facility = Facilities.objects.filter(name=facility_name).first()
				# 	if facility:
				# 		facility_details.append({
				# 			'name': facility.name,
				# 			'icon': facility.icon
				# 		})
				# 	else:
				# 		facility_details.append({
				# 			'name': facility_name,
				# 			'icon': None
				# 		})
				favourite_obj = RentPropertyFavourite.objects.filter(rent=rent.id,customerId=customerObj).first()
				if favourite_obj:
					favourite = True
				else:
					favourite = False
				alldata = {
					'id':rent.id,
					'title':rent.title,
					'category': rent.category,
					'sub_category': rent.subCategory,
					'image_data': ast.literal_eval(rent.image_data.strip()) if rent.image_data and rent.image_data.strip() else [],
					'video':rent.video,
					'floor': rent.floor,
					'rooms': rent.rooms,
					'bedrooms': rent.bedrooms,
					'size': rent.size,
					# 'facilites': ast.literal_eval(rent.facilites.strip()) if rent.facilites and rent.facilites.strip() else [],
					'country' : rent.country,
					'state' : rent.state,
					'city' :rent.city,
					'postal_code' : rent.postal_code,
					'house_number' : rent.house_number,
					'rental_period': rent.rental_period,
					'avaiable_from_date': rent.avaiable_from_date,
					'monthly_rent': rent.monthly_rent,
					'monthly_rent_includes': rent.monthly_rent_includes,
					'security': rent.security,
					'security_amount': rent.security_amount,
					'heading': rent.heading,
					'description': rent.description,
					'display_information': rent.display_information,
					'name_of_ad': rent.name_of_ad,
					'visibilty': rent.visibilty,
					'location': rent.location,
					'latitude': rent.latitude,
					'longitude':rent.longitude,
					'subscription_type':rent.subscription_type,
					'created_date':rent.created_at,
					'favourite':favourite,
				}
				allData.append(alldata)
			return Response({'status':status.HTTP_200_OK,'message':'Success','data':allData},status=status.HTTP_200_OK)
		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class rentPropertyDetails(APIView):
	def get(self,request):
		try:
			rent_id = request.query_params.get('id')
			if not rent_id:
				return Response({'status':status.HTTP_400_BAD_REQUEST,'message':'Rent id is required'},status=status.HTTP_400_BAD_REQUEST)
			rentObj = RentProperty.objects.filter(id=rent_id).first()
			if not rentObj:
				return Response({'status':status.HTTP_400_BAD_REQUEST,'message':'No rent and sale found'},status=status.HTTP_400_BAD_REQUEST)
			facilities_list = ast.literal_eval(rentObj.facilites)
			facility_details = []
			for facility_name in facilities_list:
				facility = Facilities.objects.filter(name=facility_name).first()
				if facility:
					facility_details.append({
						'name': facility.name,
						'icon': facility.icon
					})
				else:
					facility_details.append({
						'name': facility_name,
						'icon': None
					})


			alldata = {
					'id':rentObj.id,
	 				'customer_id' : rentObj.customerId.id,
	 				'customer_name' : rentObj.customerId.firstName +' '+ rentObj.customerId.lastName,
	 				'customer_phone_number' : rentObj.customerId.phoneNumber,
	 				'customer_images' : rentObj.customerId.profileImage,

					'title':rentObj.title,
					'category': rentObj.category,
					'sub_category': rentObj.subCategory,
					'image_data': ast.literal_eval(rentObj.image_data.strip()) if rentObj.image_data and rentObj.image_data.strip() else [],
					'video':rentObj.video,
	 				'videos_thumbnail':rentObj.videos_thumbnail,
					'floor': rentObj.floor,
					'rooms': rentObj.rooms,
					'bedrooms': rentObj.bedrooms,
					'size': rentObj.size,
					'facilites':  ast.literal_eval(rentObj.facilites.strip()) if rentObj.facilites and rentObj.facilites.strip() else [],
					'deposit': rentObj.deposit,
					'country' : rentObj.country,
					'state' : rentObj.state,
					'city' :rentObj.city,
					'postal_code' : rentObj.postal_code,
					'house_number' : rentObj.house_number,
					'landmark' : rentObj.landmark,
	 				'benefits': ast.literal_eval(rentObj.benefits.strip()) if rentObj.benefits and rentObj.benefits.strip() else [],

					'rental_period': rentObj.rental_period,
					'avaiable_from_date': rentObj.avaiable_from_date,
					'monthly_rent': rentObj.monthly_rent,
					'monthly_rent_includes': ast.literal_eval(rentObj.monthly_rent_includes.strip()) if rentObj.monthly_rent_includes and rentObj.monthly_rent_includes.strip() else [],
					'security': ast.literal_eval(rentObj.security.strip()) if rentObj.security and rentObj.security.strip() else [],
					'security_amount': rentObj.security_amount,
					'heading': rentObj.heading,
					'description': rentObj.description,
					'display_information': rentObj.display_information,
					'name_of_ad': rentObj.name_of_ad,
					'visibilty': rentObj.visibilty,
					'location': rentObj.location,
					'latitude': rentObj.latitude,
					'longitude':rentObj.longitude,
					'subscription_type':rentObj.subscription_type,
					'property_overview': rentObj.property_overview,
					'type_property': rentObj.type_property,
					'description_home': rentObj.description_home,
					'spend_time': rentObj.spend_time,
					'useless_skill': rentObj.useless_skill,
					'fun_act': rentObj.fun_act,
					'biography': rentObj.biography,
					'primary_room': rentObj.primary_room,
					'housing_type': rentObj.housing_type,
					'key_info_bedroom': rentObj.key_info_bedroom,
					'story': rentObj.story,



			}
			return Response({'status':status.HTTP_200_OK,'message':'Success','data':alldata},status=status.HTTP_200_OK)
		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class favouriteUnfavouriteRentProperty(APIView):
	def post(self,request):
		try:
			token = get_authorization_header(request)
			if token is None or token == "null" or token.strip() == "":
				raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
			decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
			user_id = decoded['user_id']
			customerObj=Customer.objects.filter(user=user_id).first()
			rent_id = request.data.get('rent_id')
			if not rent_id:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Rent Id is required'},status=status.HTTP_400_BAD_REQUEST)
			rent_obj = RentProperty.objects.filter(id=rent_id).first()
			if not rent_obj:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No rent property found.'},status=status.HTTP_400_BAD_REQUEST)
			favourite_post, created = RentPropertyFavourite.objects.get_or_create(rent=rent_obj,customerId=customerObj,is_favourite=1)
			if not created:
				favourite_post.delete()
				return Response({'status_code':status.HTTP_200_OK,'status_message':'Removed from favourite list'},status=status.HTTP_200_OK)
			else:
				favourite_post.save()
				return Response({'status_code':status.HTTP_200_OK,'status_message':'Added to favourite list.'},status=status.HTTP_200_OK)
		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)



class saleProperty(APIView):
	def get(self,request):
		try:

			allData = []
			# start
			min_price =  self.request.query_params.get('min_price')
			max_price =  self.request.query_params.get('max_price')
			location = self.request.query_params.get('location')
			bedroom_min = self.request.query_params.get('bedroom_min')
			bedroom_max = self.request.query_params.get('bedroom_max')
			amenities = self.request.query_params.get('amenities')
			latitude = self.request.query_params.get('latitude')
			longitude = self.request.query_params.get('longitude')
			filter_data =  self.request.query_params.get('filter_data')
			sort_price = self.request.query_params.get('sort_price')
			sort_upload_date = self.request.query_params.get('sort_upload_date')
			subscription_tyre = self.request.query_params.get('subscription_tyre')
			category = self.request.query_params.get('category')
			# country_filter = self.request.query_params.get('countryFilter')
			# state_filter = self.request.query_params.get('stateFilter')
			# city_filter = self.request.query_params.get('cityFilter')
			# stateData = []
			# cityData = []


			lookups = Q()
			if min_price and max_price:
				lookups.add(Q(price__range=(min_price,max_price)), Q.AND)
			if location:
				lookups.add(Q(location__icontains=location), Q.AND)
			if bedroom_min and bedroom_max:
				lookups.add(Q(bedrooms__range=(bedroom_min,bedroom_max)), Q.AND)
			if amenities:
				lookups.add(Q(amenities__contains = amenities), Q.AND)
			if category:
				lookups.add(Q(subCategory__icontains = category), Q.AND)
			# if country_filter:
			# 	lookups.add(Q(country__icontains = country_filter), Q.AND)

			# 	states_with_property_counts = SaleProperty.objects.filter(lookups,status=1,end_date__isnull = True).values('state').annotate(total_properties_state=Count('id'))
			# 	for state_info in states_with_property_counts:
			# 		state_date = {
			# 			'state':state_info['state'],
			# 			'total_properties':state_info['total_properties_state']
			# 			}
			# 		stateData.append(state_date)

			# if state_filter:
			# 	lookups.add(Q(state__icontains = state_filter), Q.AND)

			# 	city_with_property_counts = SaleProperty.objects.filter(lookups,status=1,end_date__isnull = True).values('city').annotate(total_properties=Count('id'))
			# 	for city_info in city_with_property_counts:
			# 		city_data = {
			# 			'city':city_info['city'],
			# 			'total_properties':city_info['total_properties']
			# 			}
			# 		cityData.append(city_data)


			# if city_filter:
			# 	lookups.add(Q(city__icontains = city_filter), Q.AND)


			if latitude and longitude:
					lat = float(latitude)
					long = float(longitude)
					kmrange = 20
					lookups.add(Q(latitude__gte= (lat - kmrange/111.1),latitude__lte=(lat + kmrange/111.1),longitude__gte=(long - kmrange/111.1),longitude__lte=(long + kmrange/111.1)),Q.AND)

			# countryData = []
			# country_with_property_counts = SaleProperty.objects.filter(lookups,status=1,end_date__isnull = True).values('country').annotate(total_properties_country=Count('id'))
			# for country_info in country_with_property_counts:
			# 	country_data = {
			# 		'country':country_info['country'],
			# 		'total_properties':country_info['total_properties_country']
			# 		}
			# 	countryData.append(country_data)

			rentAndsale = SaleProperty.objects.filter(lookups,end_date__isnull = True).order_by('-subscription_type')
			for rentAndsale in rentAndsale:

				if rentAndsale.status == 0:
					status_info = "Pending"
				elif rentAndsale.status == 1:
					status_info = "Approved"
				else:
					status_info = "Disapproved"

				facilities_list = ast.literal_eval(rentAndsale.facilities)
				facility_details = []
				for facility_name in facilities_list:
					facility = Facilities.objects.filter(name=facility_name).first()
					if facility:
						facility_details.append({
							'name': facility.name,
							'icon': facility.icon
						})
					else:
						facility_details.append({
							'name': facility_name,
							'icon': None
						})

				alldata = {
					'id':rentAndsale.id,
					'title':rentAndsale.title,
					'main_category': rentAndsale.main_category,
					'sub_category': rentAndsale.subCategory,
					'image_data' : ast.literal_eval(rentAndsale.image_data.strip()) if rentAndsale.image_data and rentAndsale.image_data.strip() else [],
					'video': rentAndsale.video,
					'videos_thumbnail': rentAndsale.videos_thumbnail,

					'property_name': rentAndsale.property_name,
					'house_number': rentAndsale.house_number,
					'country': rentAndsale.country,
					'state': rentAndsale.state,
					'city': rentAndsale.city,
					'benefits':ast.literal_eval(rentAndsale.benfits.strip()) if rentAndsale.benfits and rentAndsale.benfits.strip() else [],

					'postal_code': rentAndsale.postal_code,
					'youtubeUrl': rentAndsale.youtubeUrl,
					'phoneNumber': rentAndsale.phoneNumber,
					'price': rentAndsale.price,
					'property_demension': rentAndsale.property_demension,
					'vision': rentAndsale.vision,
					'rental': rentAndsale.rental,
					'descriptioon': rentAndsale.descriptioon,
					'closingFee': rentAndsale.closingFee,
					'bedrooms': rentAndsale.bedrooms,
					'bathrooms': rentAndsale.bathrooms,
					'readyBy': rentAndsale.readyBy,
					'propertyReferenceId': rentAndsale.propertyReferenceId,
					'maintenanceFee': rentAndsale.maintenanceFee,

					'finance_rental':rentAndsale.finance_rental,
					'finance_total_closing_fee':rentAndsale.finance_total_closing_fee,
					'finance_maintaince_fee':rentAndsale.finance_maintaince_fee,
					'finance_bill_utilites':rentAndsale.finance_bill_utilites,

					'cashflow_forecast': rentAndsale.cashflow_forecast,
					'disclaimer':rentAndsale.disclaimer,
					'property_information':rentAndsale.property_information,
					'required_capital':rentAndsale.required_capital,
					'residental_property_details':rentAndsale.residental_property_details,
					'facility': ast.literal_eval(rentAndsale.facilities.strip()) if rentAndsale.facilities and rentAndsale.facilities.strip() else [],
					'location':rentAndsale.location,
					'latitude':rentAndsale.latitude,
					'longitude':rentAndsale.longitude,
					'subscription_type':rentAndsale.subscription_type,
					'is_draft':rentAndsale.is_draft,
					# 'is_favourite':favourite,
					'status':status_info,

				}
				allData.append(alldata)
				if filter_data == 'true':
					if subscription_tyre:
						allData = [data for data in allData if data['subscription_type'] == int(subscription_tyre)]
					if sort_price == 'ascending':
						allData = sorted(allData, key=lambda x: x['filter_price'])
					elif sort_price == 'desending':
						allData = sorted(allData, key=lambda x: x['filter_price'], reverse=True)
					if sort_upload_date == "oldest":
						allData = sorted(allData, key=lambda x: x['created_date'])
					elif sort_upload_date == "latest":
						allData = sorted(allData, key=lambda x: x['created_date'], reverse=True)
			return Response({'status':status.HTTP_200_OK,'message':'Success','data':allData},status=status.HTTP_200_OK)
		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class salePropertyDetails(APIView):

	def get(self,request):
		try:
			token = get_authorization_header(request)
			if token:
				decoded = jwt.decode(token, settings.SECRET_KEY)
				user_id = decoded['user_id']
				customerObj=Customer.objects.filter(user=user_id).first()
			else:
				customerObj= 0
			property_id = request.query_params.get('id')
			if not property_id:
				return Response({'message':'property_id is required'},status=status.HTTP_400_BAD_REQUEST)
			rentAndsale = SaleProperty.objects.filter(id=property_id).first()
			if not rentAndsale:
				return Response({'message':'No sale property found'},status=status.HTTP_400_BAD_REQUEST)

			favourite_obj = SalePropertyFavourite.objects.filter(sale=rentAndsale.id,customerId=customerObj).first()
			if favourite_obj:
				favourite = True
			else:
				favourite = False

			if rentAndsale.status == 0:
				status_info = "Pending"
			elif rentAndsale.status == 1:
				status_info = "Approved"
			else:
				status_info = "Disapproved"



			facilities_list = ast.literal_eval(rentAndsale.facilities)
			facility_details = []
			for facility_name in facilities_list:
				facility = Facilities.objects.filter(name=facility_name).first()
				if facility:
					facility_details.append({
						'name': facility.name,
						'icon': facility.icon
					})
				else:
					facility_details.append({
						'name': facility_name,
						'icon': None
					})

			all_data = {
					'id':rentAndsale.id,
					'customer_id':rentAndsale.customerId.id,
					'customerPhoneNumber ':rentAndsale.customerId.phoneNumber,
					'customerName ':rentAndsale.customerId.firstName+' '+ rentAndsale.customerId.lastName,
					'customerImage ':rentAndsale.customerId.profileImage,
					'fullname': rentAndsale.customerId.firstName+' '+ rentAndsale.customerId.lastName,
					'customer_image':rentAndsale.customerId.profileImage,
					'title':rentAndsale.title,
					'main_category': rentAndsale.main_category,
					'sub_category': rentAndsale.subCategory,
					'image_data' : ast.literal_eval(rentAndsale.image_data.strip()) if rentAndsale.image_data and rentAndsale.image_data.strip() else [],
					'video': rentAndsale.video,
					'videos_thumbnail': rentAndsale.videos_thumbnail,
					# 'phone_number': rentAndsale.phoneNumber,

					'property_name': rentAndsale.property_name,
					'house_number': rentAndsale.house_number,
					'country': rentAndsale.country,
					'state': rentAndsale.state,
					'city': rentAndsale.city,
					'benefits':ast.literal_eval(rentAndsale.benfits.strip()) if rentAndsale.benfits and rentAndsale.benfits.strip() else [],

					'postal_code': rentAndsale.postal_code,
					'youtubeUrl': rentAndsale.youtubeUrl,
					'phoneNumber': rentAndsale.phoneNumber,
					'price': rentAndsale.price,
					'property_demension': rentAndsale.property_demension,
					'vision': rentAndsale.vision,
					'rental': rentAndsale.rental,
					'descriptioon': rentAndsale.descriptioon,
					'closingFee': rentAndsale.closingFee,
					'bedrooms': rentAndsale.bedrooms,
					'bathrooms': rentAndsale.bathrooms,
					'readyBy': rentAndsale.readyBy,
					'propertyReferenceId': rentAndsale.propertyReferenceId,
					'maintenanceFee': rentAndsale.maintenanceFee,

					'finance_rental':rentAndsale.finance_rental,
					'finance_total_closing_fee':rentAndsale.finance_total_closing_fee,
					'finance_maintaince_fee':rentAndsale.finance_maintaince_fee,
					'finance_bill_utilites':rentAndsale.finance_bill_utilites,

					'cashflow_forecast': rentAndsale.cashflow_forecast,
					'disclaimer':rentAndsale.disclaimer,
					'property_information':rentAndsale.property_information,
					'required_capital':rentAndsale.required_capital,
					'residental_property_details':rentAndsale.residental_property_details,
					'facility':ast.literal_eval(rentAndsale.facilities.strip()) if rentAndsale.facilities and rentAndsale.facilities.strip() else [],
					'location':rentAndsale.location,
					'latitude':rentAndsale.latitude,
					'longitude':rentAndsale.longitude,
					'subscription_type':rentAndsale.subscription_type,
					'is_draft':rentAndsale.is_draft,
					'is_favourite':favourite,
					'status':status_info,
			}
			return Response({'status_code':status.HTTP_200_OK,'message':'sale property details fetched successfully','data':all_data},status=status.HTTP_200_OK)
		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class favouriteUnfavouriteSaleProperty(APIView):
	def post(self,request):
		try:
			token = get_authorization_header(request)
			if token is None or token == "null" or token.strip() == "":
				raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
			decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
			user_id = decoded['user_id']
			customerObj=Customer.objects.filter(user=user_id).first()
			sale_id = request.data.get('sale_id')
			if not sale_id:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Sale Id is required'},status=status.HTTP_400_BAD_REQUEST)
			sale_obj = SaleProperty.objects.filter(id=sale_id).first()
			if not sale_obj:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No sale property found.'},status=status.HTTP_400_BAD_REQUEST)
			favourite_post, created = SalePropertyFavourite.objects.get_or_create(sale=sale_obj,customerId=customerObj,is_favourite=1)
			if not created:
				favourite_post.delete()
				return Response({'status_code':status.HTTP_200_OK,'status_message':'Removed from favourite list'},status=status.HTTP_200_OK)
			else:
				favourite_post.save()
				return Response({'status_code':status.HTTP_200_OK,'status_message':'Added to favourite list.'},status=status.HTTP_200_OK)
		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class bussinessForSaleDetail(APIView):
	def get(self):
		try:
			bussiness_id = self.request.query_params.get('id')
			if not bussiness_id:
				return Response({'status':status.HTTP_400_BAD_REQUEST,'message':'Bussiness sale Id is required'},status=status.HTTP_400_BAD_REQUEST)
			bussiness_obj = BussinessForSale.objects.filter(id=bussiness_id).first()
			if not bussiness_obj:
				return Response({'status':status.HTTP_400_BAD_REQUEST,'message':'No bussiness sale found'},status=status.HTTP_400_BAD_REQUEST)
			alldata = {
					'id': bussiness_obj.id,
				'customer_name' : bussiness_obj.customerId.firstName +' '+ bussiness_obj.customerId.lastName,
				'customerPhoneNumber' : bussiness_obj.phoneNumber,
				'company_name': bussiness_obj.company_name,
				'short_title': bussiness_obj.short_title,
				'image_data': ast.literal_eval(bussiness_obj.image_data),
				'videos': bussiness_obj.videos,
				'videos_thumbnail': bussiness_obj.videos_thumbnail,
				'company_name': bussiness_obj.company_name,
				'description': bussiness_obj.description,
				'total_turnover': bussiness_obj.total_turnover,
				'rent': bussiness_obj.rent,
				'established_year': bussiness_obj.established_year,
				'premises': bussiness_obj.premises,
				'years_of_work': bussiness_obj.years_of_work,
				'operation_concept': bussiness_obj.operation_concept,
				'operation_opening_hours': bussiness_obj.operation_opening_hours,
				'turnover_last_year': bussiness_obj.turnover_last_year,
				'salary_percentage': bussiness_obj.salary_percentage,
				'other_operating_cost': bussiness_obj.other_operating_cost,
				'cost': bussiness_obj.cost,
				'reason_for_sale':bussiness_obj.reason_for_sale,
				'website_link':bussiness_obj.website_link,
				'number_of_employes':bussiness_obj.number_of_employes,
				'other_operating_cost':bussiness_obj.other_operating_cost,
				'area':bussiness_obj.area,
				'term_of_lease': bussiness_obj.term_of_lease,
				'revenue_growth': bussiness_obj.revenue_growth,
				'details': bussiness_obj.details,
				'service':bussiness_obj.service,
				'operations':bussiness_obj.operations,
				'market_initatives':bussiness_obj.market_initatives,
				'advantage_and_oppurtunity':bussiness_obj.advantage_and_oppurtunity,
				'valuation':bussiness_obj.valuation,
				'owner_name':bussiness_obj.owner_name,
				'phone':bussiness_obj.phone,
				'telephone':bussiness_obj.telephone,
				'email':bussiness_obj.email,
				'company':bussiness_obj.company,
				'public_order':bussiness_obj.public_order,
				'avaiable_attachment':bussiness_obj.avaiable_attachment,
				'location':bussiness_obj.location,
				'latitude':bussiness_obj.latitude,
				'longitude':bussiness_obj.longitude,
				'is_draft': bussiness_obj.is_draft,
			}
			return Response({'status':status.HTTP_200_OK,'message':'bussiness for sale detail fetched siccessfully','data':alldata},status=status.HTTP_200_OK,)
		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class favouriteUnfavouriteBussinessSale(APIView):
	def post(self,request):
		try:
			token = get_authorization_header(request)
			if token is None or token == "null" or token.strip() == "":
				raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
			decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
			user_id = decoded['user_id']
			customerObj=Customer.objects.filter(user=user_id).first()
			bussiness_id = request.data.get('bussiness_id')
			if not bussiness_id:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Bussiness ID is required'},status=status.HTTP_400_BAD_REQUEST)
			bussiness_obj = BussinessForSale.objects.filter(id=bussiness_id).first()
			if not bussiness_obj:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No product found'},status=status.HTTP_400_BAD_REQUEST)
			favourite_post, created = BussinessForSaleFavourite.objects.get_or_create(bussiness=bussiness_obj,customerId=customerObj,is_favourite=1)
			if not created:
				favourite_post.delete()
				return Response({'status_code':status.HTTP_200_OK,'status_message':'Removed from favourite list'},status=status.HTTP_200_OK)
			else:
				favourite_post.save()
				return Response({'status_code':status.HTTP_200_OK,'status_message':'Added to favourite list.'},status=status.HTTP_200_OK)
		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class myHouseWantedForRentDetails(APIView):
	def get(self,request):
		try:

			rent_id = self.request.query_params.get('id')
			if not rent_id:
				return Response({'status':status.HTTP_400_BAD_REQUEST,'message':'Rent sale Id is required'},status=status.HTTP_400_BAD_REQUEST)
			rent_obj = HouseWantedForRent.objects.filter(id=rent_id).first()
			if not rent_obj:
				return Response({'status':status.HTTP_400_BAD_REQUEST,'message':'No house for rent found'},status=status.HTTP_400_BAD_REQUEST)

			alldata = {
				'id': rent_obj.id,
				'short_title':rent_obj.short_title,
				'customer_id':rent_obj.customerId.id,
				'customerphoneNumber':rent_obj.customerId.phoneNumber,
				'customerImage':rent_obj.customerId.profileImage,
				'customerName':rent_obj.customerId.firstName+' '+ rent_obj.customerId.lastName,
				'fullname': rent_obj.first_name+' '+ rent_obj.last_name,
				'profile_visiblity':rent_obj.profile_visiblity,
				'profile_hidden':rent_obj.profile_hidden,
				'image': ast.literal_eval(rent_obj.image),
				'first_name': rent_obj.first_name,
				'last_name': rent_obj.last_name,
				'gender': rent_obj.gender,
				'dob': rent_obj.dob,
				'nationality': rent_obj.nationality,
				'phone_number':rent_obj.phone_number,
				'email': rent_obj.email,
				'quantity': rent_obj.quantity,
				'rental_period': rent_obj.rental_period,
				'max_rent': rent_obj.max_rent,
				'from_date': rent_obj.from_date,
				'housing_type':ast.literal_eval(rent_obj.housing_type),
				'number_of_people':rent_obj.number_of_people,
				'max_month_price': rent_obj.max_month_price,
				'desired_start_date':rent_obj.desired_start_date,
				'desired_area': rent_obj.desired_area,
				'latitude':rent_obj.latitude,
				'description':rent_obj.description,
	   			'country':rent_obj.country,
				'state':rent_obj.state,
				'city':rent_obj.city,
				'postal_code':rent_obj.postal_code,
				'landmark':rent_obj.landmark,
				'floor':rent_obj.floor,
				'longitude':rent_obj.longitude,
				'location':rent_obj.location,
				'about':rent_obj.about,
				'education':rent_obj.education,
				'martial_status':rent_obj.martial_status,
				'cleanliness':rent_obj.cleanliness,
				'party_habits':rent_obj.party_habits,
				'work':rent_obj.work,
				'interest':rent_obj.interest,
				'subscription_type':rent_obj.subscription_type,
				'is_draft':rent_obj.is_draft,
				'created_date':rent_obj.start_date,

			}
			return Response({'status':status.HTTP_200_OK,'message':'Details fetched successfully','data':alldata},status=status.HTTP_200_OK)

		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class myInvestmentMyProjectDetails(APIView):
	def get(self,request):
		try:

			project_id = self.request.query_params.get('id')
			if not project_id:
				return Response({'status':status.HTTP_400_BAD_REQUEST,'message':'Rent sale Id is required'},status=status.HTTP_400_BAD_REQUEST)
			pro_obj = InvestmentMyProject.objects.filter(id=project_id).first()
			if not pro_obj:
				return Response({'status':status.HTTP_400_BAD_REQUEST,'message':'No house for rent found'},status=status.HTTP_400_BAD_REQUEST)

			alldata = {
				'id': pro_obj.id,
				'customer_id':pro_obj.customerId.id,
				'customerImage':pro_obj.profileImage,
				'fullname': pro_obj.customerId.firstName+' '+ pro_obj.customerId.lastName,
				'property_name':pro_obj.property_name,
				'image_data':pro_obj.image_data,
				'videos':pro_obj.videos,
				'documents_data':pro_obj.documents_data,
				'property_type':pro_obj.property_type,
				'assest_equality':pro_obj.assest_equality,
				'investment_highlight':pro_obj.investment_highlight,
				'equity_price':pro_obj.equity_price,
				'lp_equity_percent':pro_obj.lp_equity_percent,
				'gp_equity_percent':pro_obj.gp_equity_percent,
				'debt_percent':pro_obj.debt_percent,
				'property_at_glance_title':pro_obj.property_at_glance_title,
				'description':pro_obj.description,
				'bussiness_plan':pro_obj.bussiness_plan,
				'minimum_investment':pro_obj.minimum_investment,
				'investment_strategy':pro_obj.investment_strategy,
				'expected_attitude_price':pro_obj.expected_attitude_price,
				'financed':pro_obj.financed,
				'target_return_on_cost':pro_obj.target_return_on_cost,
				'target_irr':pro_obj.target_irr,
				'lp_equity_percent':pro_obj.lp_equity_percent,
				'offered_by':pro_obj.offered_by,
				'estimated_first_distribution':pro_obj.estimated_first_distribution,
				'type_of_investment':pro_obj.type_of_investment,
				'phone_number':pro_obj.phone_number,
				'measure_for_multiplier':pro_obj.measure_for_multiplier,
				'address':pro_obj.address,
				'location_details':pro_obj.location_details,
				'property_summary':pro_obj.property_summary,
				'property_details':pro_obj.property_details,
				'overview':pro_obj.overview,
				'debt_assumption':pro_obj.debt_assumption,
				'location':pro_obj.location,
				'latitude':pro_obj.latitude,
				'longitude':pro_obj.longitude,
				'subscription_type':pro_obj.subscription_type,
				'status':pro_obj.status,
				'is_draft':pro_obj.is_draft,
			}
			return Response({'status':status.HTTP_200_OK,'message':'Deatils fetched successfully','data':alldata},status=status.HTTP_200_OK)

		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class myInvestmentMyCompanyDetails(APIView):
	def get(self,request):
		try:

			project_id = self.request.query_params.get('id')
			if not project_id:
				return Response({'status':status.HTTP_400_BAD_REQUEST,'message':'Rent sale Id is required'},status=status.HTTP_400_BAD_REQUEST)
			pro_obj = InvestmentMyCompany.objects.filter(id=project_id).first()
			if not pro_obj:
				return Response({'status':status.HTTP_400_BAD_REQUEST,'message':'No investment company found'},status=status.HTTP_400_BAD_REQUEST)

			alldata = {
				'id': pro_obj.id,
				'image_data':pro_obj.image_data,
				'video':pro_obj.video,
				'customer_id':pro_obj.customerId.id,
				'customerImage':pro_obj.customerId.profileImage,
				'fullname': pro_obj.customerId.firstName+' '+ pro_obj.customerId.lastName,
				'company_name' :pro_obj.company_name,
				'documents_data':pro_obj.documents_data,
				'company_established' :pro_obj.company_established,
				'company_email' :pro_obj.company_email,
				'company_telephone' :pro_obj.company_telephone,
				'company_postcode' :pro_obj.company_postcode,
				'company_postal_code' :pro_obj.company_postal_code,
				'company_website' :pro_obj.company_website,
				'issue_account_no' :pro_obj.issue_account_no,
				'bank_acc_created' :pro_obj.bank_acc_created,
				'chairman_email' :pro_obj.chairman_email,
				'no_share_bfr_issue' :pro_obj.no_share_bfr_issue,
				'nominal_share_price' :pro_obj.nominal_share_price,
				'company_logo' :pro_obj.company_logo,
				'shareholders' :pro_obj.shareholders,
				'self_report':pro_obj.self_report,
				'small_company_logo' :pro_obj.small_company_logo,
				'description' :pro_obj.description,
				'the_valuation' :pro_obj.the_valuation,
				'shares_for_sale' :pro_obj.shares_for_sale,
				'remaninig_shares' :pro_obj.remaninig_shares,
				'minimum_drawing' :pro_obj.minimum_drawing,
				'max_drawing' :pro_obj.max_drawing,
				'youtube_url' :pro_obj.youtube_url,
				'company_address' :pro_obj.company_address,
				'team' :pro_obj.team,
				'board' :pro_obj.board,
				'partners' :pro_obj.partners,
				"is_draft": pro_obj.is_draft,
				'status': pro_obj.status,
			}
			return Response({'status':status.HTTP_200_OK,'message':'Details fetched successfully','data':alldata},status=status.HTTP_200_OK)

		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class myPropertyProjectDetails(APIView):
	def get(self,request):
		try:
			project_id = self.request.query_params.get('id')
			if not project_id:
				return Response({'status':status.HTTP_400_BAD_REQUEST,'message':'Project Id is required'},status=status.HTTP_400_BAD_REQUEST)
			pro_obj = PropertyProject.objects.filter(id=project_id).first()
			if not pro_obj:
				return Response({'status':status.HTTP_400_BAD_REQUEST,'message':'No house for rent found'},status=status.HTTP_400_BAD_REQUEST)

			if pro_obj.status == 0:
				status_info = "Pending"
			elif pro_obj.status == 1:
				status_info = "Approved"
			else:
				status_info = "Disapproved"


			facilities_list = ast.literal_eval(pro_obj.facility)

			# Fetch each facility name and icon from the Facilities model
			facility_details = []
			for facility_name in facilities_list:
				facility = Facilities.objects.filter(name=facility_name).first()
				if facility:
					facility_details.append({
						'name': facility.name,
						'icon': facility.icon
					})
				else:
					facility_details.append({
						'name': facility_name,
						'icon': None
					})


			alldata = {
				'id': pro_obj.id,
				'customer_id':pro_obj.customerId.id,
				'fullname': pro_obj.customerId.firstName+' '+ pro_obj.customerId.lastName,
				'customerImage': pro_obj.customerId.profileImage,
				'customer_phone_number': pro_obj.customerId.phoneNumber,
				'spend_too_much_time':pro_obj.spend_too_much_time,
				'most_useless_skill':pro_obj.most_useless_skill,
				'fun_act':pro_obj.fun_act,
				'biography':pro_obj.biography,
				'short_title':pro_obj.short_title,
				'property_overview':pro_obj.property_overview,
				'property_description':pro_obj.property_description,
				'image_data':ast.literal_eval(pro_obj.image_data.strip()) if pro_obj.image_data and pro_obj.image_data.strip() else [],
				'videos':pro_obj.videos,
				'videos_thumbnail':pro_obj.videos_thumbnail,
				'property_document':pro_obj.property_document,
				'category':pro_obj.category,
				'property_name':pro_obj.property_name,
				'property_dimension':pro_obj.property_dimension,
				'country':pro_obj.country,
				'state':pro_obj.state,
				'city':pro_obj.city,
				'postal_code':pro_obj.postal_code,
				'landmark':pro_obj.landmark,
				'house_number':pro_obj.house_number,
				'location':pro_obj.location,
				'latitude':pro_obj.latitude,
				'longitude':pro_obj.longitude,
				'facility':ast.literal_eval(pro_obj.facility.strip()) if pro_obj.facility and pro_obj.facility.strip() else [],
				'benefits':ast.literal_eval(pro_obj.benefits.strip()) if pro_obj.benefits and pro_obj.benefits.strip() else [],
				'return_on_investment':pro_obj.return_on_investment,
				'finder_fee':pro_obj.finder_fee,
				'gross_income':pro_obj.gross_income,
				'price':pro_obj.price,
				'cashflow_pcm':pro_obj.cashflow_pcm,
				'total_termination_fee':pro_obj.total_termination_fee,
				'purchase_price':pro_obj.purchase_price,
				'potential_cashflow_pcm':pro_obj.potential_cashflow_pcm,
				'investment_finder_fee':pro_obj.investment_finder_fee,
				'investment_return_on_investment_fee':pro_obj.investment_return_on_investment_fee,
				'rental':pro_obj.rental,
				'the_vision':pro_obj.the_vision,
				'cost_to_consider':pro_obj.cost_to_consider,
				'capital_required':pro_obj.capital_required,
				'cashflow_forecast':pro_obj.cashflow_forecast,
				'investment_finder_fee':pro_obj.investment_finder_fee,
				'rent_to_landlord':pro_obj.rent_to_landlord,
				'bill_utilities':pro_obj.bill_utilities,
				'status': status_info,
				'is_draft':pro_obj.is_draft,
			}
			return Response({'status':status.HTTP_200_OK,'message':'Details fetched successfully','data':alldata},status=status.HTTP_200_OK)

		except Exception as e:
			return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class commonGetPropertiesDetail(APIView):
	def get(self,request):
		try:
				# try:
				# 	uid = authenticated(request)
				# except Exception as e:
				# 	return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
				customer_id = request.query_params.get('customer_id')
				Type = request.query_params.get('type')
				if not Type:
					return Response({'status':status.HTTP_400_BAD_REQUEST,'message':'type is required'},status=status.HTTP_400_BAD_REQUEST)
				is_requested = False
				if customer_id:
					customerObj=Customer.objects.filter(id=customer_id).first()
					inquirePropertyProjectObj= inquirePropertyProject.objects.filter(customerId=customerObj,property_type=Type)
					if inquirePropertyProjectObj.exists():
						is_requested = True
				# jwt_token = request.headers.get('Authorization')
				# if not jwt_token:
				# 	return Response({'message':'token is required'},status=status.HTTP_400_BAD_REQUEST)
				# headers = {'Authorization': jwt_token}
				payload={'id':self.request.query_params.get('id'),
						}
				try:

					if Type ==  'SaleProperty':
						url = 'http://95.111.228.198:9007/panel-api/sale-property-details'
						getAPI = requests.request("GET", url, params=payload)
						apiResponse = getAPI.json()
						if isinstance(apiResponse.get('data'), dict):
							apiResponse['data']['is_requested'] = is_requested
						return Response(apiResponse)
					if Type ==  'RentProperty':
						url = 'http://95.111.228.198:9007/panel-api/rent-property-detail'
						getAPI = requests.request("GET", url, params=payload)
						apiResponse = getAPI.json()
						if isinstance(apiResponse.get('data'), dict):
							apiResponse['data']['is_requested'] = is_requested
						return Response(apiResponse)
					# Get BussinessForSale API
					if Type ==  'BusinessSale':
						url = 'http://95.111.228.198:9007/panel-api/get-bussiness-for-sale-details'
						getAPI = requests.request("GET", url,  params=payload)

						apiResponse = getAPI.json()
						if isinstance(apiResponse.get('data'), dict):
							apiResponse['data']['is_requested'] = is_requested
						return Response(apiResponse)

					# Get HouseRent API
					if Type ==  'HouseRent':
						url = 'http://95.111.228.198:9007/panel-api/my-house-wanted-for-rent-details'
						getAPI = requests.request("GET", url,  params=payload)
						apiResponse = getAPI.json()
						if isinstance(apiResponse.get('data'), dict):
							apiResponse['data']['is_requested'] = is_requested
						return Response(apiResponse)

					# Get investmentMyProject API
					if Type ==  'InvestmentProject':
						url = 'http://95.111.228.198:9007/panel-api/my-investment-project-details'
						getAPI = requests.request("GET", url, params=payload)
						apiResponse = getAPI.json()
						if isinstance(apiResponse.get('data'), dict):
							apiResponse['data']['is_requested'] = is_requested
						return Response(apiResponse)

					# Get investmentMyCompany API
					if Type ==  'InvestmentCompany':
						url = 'http://95.111.228.198:9007/panel-api/my-investment-my-company-details'
						getAPI = requests.request("GET", url, params=payload)
						apiResponse = getAPI.json()
						if isinstance(apiResponse.get('data'), dict):
							apiResponse['data']['is_requested'] = is_requested
						return Response(apiResponse)

					# Get PropertyProject API
					if Type ==  'PropertyProject':
						url = 'http://95.111.228.198:9007/panel-api/my-property-project-details'
						getAPI = requests.request("GET", url, params=payload)
						apiResponse = getAPI.json()
						if isinstance(apiResponse.get('data'), dict):
							apiResponse['data']['is_requested'] = is_requested
						return Response(apiResponse)

					if Type ==  'CompanySeeking':
						url = 'http://95.111.228.198:9007/panel-api/detail-company-seeking'
						getAPI = requests.request("GET", url, params=payload)
						apiResponse = getAPI.json()
						if isinstance(apiResponse.get('data'), dict):
							apiResponse['data']['is_requested'] = is_requested
						return Response(apiResponse)

					if Type ==  'PropertyDevelopers':
						url = 'http://95.111.228.198:9007/panel-api/get-property-developer-details'
						getAPI = requests.request("GET", url, params=payload)
						apiResponse = getAPI.json()
						if isinstance(apiResponse.get('data'), dict):
							apiResponse['data']['is_requested'] = is_requested
						return Response(apiResponse)

					else:
						return Response({'status':status.HTTP_200_OK,'message':'No Property'},status=status.HTTP_200_OK)
				except Exception as e:
					return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)
		except Exception as e:
				return Response({'status':status.HTTP_500_INTERNAL_SERVER_ERROR,'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)
class ListCompanySeeking(APIView):
	def get(self,request):
		try:
			# token = get_authorization_header(request)
			# if token is None or token == "null" or token.strip() == "":
			#     raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
			# decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=["HS256"])
			# user_id = decoded['user_id']
			allData=[]
			list_company = CompanySeekingEquity.objects.all()
			for cs in list_company:
				allData.append({
					'id': cs.id,
					'customer_name': cs.customerId.firstName + ' ' + cs.customerId.lastName,
					'customer_id' : cs.customerId.id,
	 				'customer_phone_number' : cs.customerId.phoneNumber,
	 				'customer_images' : cs.customerId.profileImage,
					'company_name': cs.company_name,
					'short_title': cs.short_title,
					'description': cs.description,
					'about_the_owner': cs.about_the_owner,
					'image_data': ast.literal_eval(cs.property_image),
					'videos': cs.property_video,
					'videos_thumbnail': cs.videos_thumbnail,
					'company_logo': cs.company_logo,
					'maximum_drawing': cs.maximum_drawing,
					'minimum_drawing': cs.minimum_drawing,
					'share_for_sale': cs.share_for_sale,
					'price_per_share': cs.price_per_share,
					'number_of_share': cs.number_of_share,
					'self_report': cs.self_report,
					'nominal_share_price': cs.nominal_share_price,
					'e_post': cs.e_post,
					'issue_account_number': cs.issue_account_number,
					'establish_year': cs.establish_year,
					'premises_from': cs.premises_from,
					'background_for_sale': cs.background_for_sale,
					'company_website': cs.company_website,
					'number_of_employee': cs.number_of_employee,
					'company_email': cs.company_email,
					'company_telephone': cs.company_telephone,
					'youtube': cs.youtube,
					'share_before_share': cs.share_before_share,
					'name_of_shareholder': cs.name_of_shareholder,
					'beskrivelse': cs.beskrivelse,
				   	'upload_team_data': cs.upload_team_data,
					'upload_team_name': cs.upload_team_name,
					'upload_team_size': cs.upload_team_size,

					'upload_board_data': cs.upload_board_data,
					'upload_board_name': cs.upload_board_name,
					'upload_board_size': cs.upload_board_size,

					'upload_partner_data': cs.upload_partner_data,
					'upload_partner_name': cs.upload_partner_name,
					'upload_partner_size': cs.upload_partner_size,
					'location': cs.location,
					'country': cs.country,
					'state': cs.state,
					'city': cs.city,
					'zip_code': cs.zip_code,
					'landmark': cs.landmark,
					'share_holder_image': cs.share_holder_image,
					'enter_shares': cs.enter_shares,
					'status': cs.status,
					'agency': cs.agency.id if cs.agency else None,
					'subscription_type': cs.subscription_type,
					'latitude': cs.latitude,
					'longitude': cs.longitude,
					'start_date': cs.start_date,
					'end_date': cs.end_date,
					'is_favourite': cs.is_favourite,
					'favourite_date': cs.favourite_date,
				})

			return Response({'status_code':status.HTTP_200_OK,'status_message':'Success','data':allData})


		except Exception as e:
			print(e)
			return Response({'status_code':status.HTTP_500_INTERNAL_SERVER_ERROR,'status_message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)


from django.db.models import Sum

class DetailCompanySeeking(APIView):
	def get(self,request):
		try:

			seeking_id = self.request.query_params.get('id')
			if not seeking_id:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'seeking_id is required'},status=status.HTTP_400_BAD_REQUEST)

			cs = CompanySeekingEquity.objects.filter(id=seeking_id).first()
			if not cs:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No seeking company found'},status=status.HTTP_400_BAD_REQUEST)
			# investment_amount = inquirePropertyProject.objects.filter(investment_amount)
			# print(investment_amount,'-------------investment_amount')

			investments = inquirePropertyProject.objects.filter(
				property_type='company_seeking_equity',
				company_seeking_equity_id=cs.id,
				contract_status='Deal-Completed'
			).aggregate(total_investment=Sum('investment_amount'))


			total_investment = investments['total_investment'] or 0.0
			print(total_investment,'-----totak_investment')
			try:
				max_drawing = float(cs.maximum_drawing)
			except (ValueError, TypeError):
				max_drawing = 0.0

			if max_drawing > 0:
				percentage_invested = (total_investment / max_drawing) * 100
			else:
				percentage_invested = 0.0
			can_stop_investment = total_investment > 0.0
			if can_stop_investment:
				five_percent_of_investment = total_investment * 0.05
			else:
				five_percent_of_investment = 0.0
			all_data = {
				'id': cs.id,
				'customer_name': cs.customerId.firstName + ' ' + cs.customerId.lastName,
				'customer_id' : cs.customerId.id,
				'customer_phone_number' : cs.customerId.phoneNumber,
				'customerImage' : cs.customerId.profileImage,
				'company_name': cs.company_name,
				'short_title': cs.short_title,
				'description': cs.description,
				'about_the_owner': cs.about_the_owner,
				'image_data': ast.literal_eval(cs.property_image),
				'videos': cs.property_video,
				'videos_thumbnail': cs.videos_thumbnail,
				'company_logo': cs.company_logo,
				'maximum_drawing': cs.maximum_drawing,
				'minimum_drawing': cs.minimum_drawing,

				'total_investment': total_investment,
				'percentage_invested': round(percentage_invested, 2),
				'can_stop_investment': can_stop_investment,
				'payment_done': cs.payment_done,
				'admin_cut':five_percent_of_investment,

				'share_for_sale': cs.share_for_sale,
				'price_per_share': cs.price_per_share,
				'number_of_share': cs.number_of_share,
				'self_report': cs.self_report,
				'nominal_share_price': cs.nominal_share_price,
				'e_post': cs.e_post,
				'issue_account_number': cs.issue_account_number,
				'establish_year': cs.establish_year,
				'premises_from': cs.premises_from,
				'background_for_sale': cs.background_for_sale,
				'company_website': cs.company_website,
				'number_of_employee': cs.number_of_employee,
				'company_email': cs.company_email,
				'company_telephone': cs.company_telephone,
				'youtube': cs.youtube,
				'share_before_share': cs.share_before_share,
				'name_of_shareholder': cs.name_of_shareholder,
				'beskrivelse': cs.beskrivelse,
				'upload_team_data': cs.upload_team_data,
				'upload_team_name': cs.upload_team_name,
				'upload_team_size': cs.upload_team_size,

				'upload_board_data': cs.upload_board_data,
				'upload_board_name': cs.upload_board_name,
				'upload_board_size': cs.upload_board_size,

				'upload_partner_data': cs.upload_partner_data,
				'upload_partner_name': cs.upload_partner_name,
				'upload_partner_size': cs.upload_partner_size,
				'location': cs.location,
				'country': cs.country,
				'state': cs.state,
				'city': cs.city,
				'zip_code': cs.zip_code,
				'landmark': cs.landmark,
				'share_holder_image': cs.share_holder_image,
				'enter_shares': cs.enter_shares,
				'status': cs.status,
				'agency': cs.agency.id if cs.agency else None,
				'subscription_type': cs.subscription_type,
				'latitude': cs.latitude,
				'longitude': cs.longitude,
				'start_date': cs.start_date,
				'end_date': cs.end_date,
				# 'is_favourite': cs.is_favourite,
				# 'favourite_date': cs.favourite_date,
			}
			return Response({'status_code':status.HTTP_200_OK,'status_message':'Success','data':all_data})

		except Exception as e:
			print(e)
			return Response({'status_code':status.HTTP_500_INTERNAL_SERVER_ERROR,'status_message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)



class ConfirmPayment(APIView):
    def post(self, request):
        try:
            seeking_id = request.query_params.get('id')
            payment_done = request.query_params.get('payment_done', False)
            entity_type = request.query_params.get('type')
            customer_id = request.query_params.get('customer_id')

            if not seeking_id:
                return Response({'status_code': status.HTTP_400_BAD_REQUEST, 'status_message': 'seeking_id is required'},
                                status=status.HTTP_400_BAD_REQUEST)

            if not entity_type:
                return Response({'status_code': status.HTTP_400_BAD_REQUEST, 'status_message': 'type is required'},
                                status=status.HTTP_400_BAD_REQUEST)

            if not customer_id:
                return Response({'status_code': status.HTTP_400_BAD_REQUEST, 'status_message': 'customer_id is required'},
                                status=status.HTTP_400_BAD_REQUEST)

            # Process based on the entity type
            if entity_type == "CompanySeeking":
                cs = CompanySeekingEquity.objects.filter(id=seeking_id).first()
                if not cs:
                    return Response({'status_code': status.HTTP_400_BAD_REQUEST, 'status_message': 'No seeking company found'},
                                    status=status.HTTP_400_BAD_REQUEST)
                cs.payment_done = payment_done
                cs.save()

            elif entity_type == "PropertyDeveloper":
                cs = PropertyDevelopers.objects.filter(id=seeking_id).first()
                if not cs:
                    return Response({'status_code': status.HTTP_400_BAD_REQUEST, 'status_message': 'No property developer found'},
                                    status=status.HTTP_400_BAD_REQUEST)
                cs.payment_done = payment_done
                cs.save()

            elif entity_type == "BusinessForSale":
                cs = BussinessForSale.objects.filter(id=seeking_id).first()
                if not cs:
                    return Response({'status_code': status.HTTP_400_BAD_REQUEST, 'status_message': 'No business for sale found'},
                                    status=status.HTTP_400_BAD_REQUEST)
                cs.payment_done = payment_done
                cs.save()

            else:
                return Response({'status_code': status.HTTP_400_BAD_REQUEST, 'status_message': 'Invalid type provided'},
                                status=status.HTTP_400_BAD_REQUEST)

            return Response({'status_code': status.HTTP_200_OK, 'status_message': 'Payment status updated successfully'})

        except Exception as e:
            print(e)
            return Response({'status_code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'status_message': str(e)},
                             status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class getContentPages(APIView):
	def get(self,request):
		try:
			page_type = request.query_params.get('page_type')
			if not page_type:
				return Response({'status':status.HTTP_400_BAD_REQUEST,'message':'Page type is required'},status=status.HTTP_400_BAD_REQUEST)
			language = request.query_params.get('language')
			content_obj = ContentPagesAdmin.objects.filter(page_type_name= page_type).first()

			if not content_obj:
				return Response({'status':status.HTTP_400_BAD_REQUEST,'message':'No content page found'},status=status.HTTP_200_OK)

			if content_obj:
				alldata = {
					'page_title':content_obj.page_title,
					'page_content':content_obj.page_content,
					'page_title_nw':content_obj.page_title_nw,
					'page_content_nw':content_obj.page_content_nw,
					'created_at':content_obj.created_at
				}
			else:
				alldata = {}
			return Response({'status_code':status.HTTP_200_OK,'status_message':'Success','data':alldata},status=status.HTTP_200_OK)
		except Exception as e:
			print(e)
			return Response({'status_code':status.HTTP_500_INTERNAL_SERVER_ERROR,'status_message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class getFaqContent(APIView):
	def get(self,request):
		try:
			data_obj = AdminFaq.objects.filter(end_date__isnull = True).order_by('-id')
			allData = []
			for faq in data_obj:
				alldata = { 'id':faq.id,
							'title':faq.title,
							'content':faq.content,
						}
				allData.append(alldata)
			return Response({'status_code':status.HTTP_200_OK,'status_message':'Faq fetched successfully','data':allData},status=status.HTTP_200_OK)
		except Exception as e:
			print(e)
			return Response({'status_code':status.HTTP_500_INTERNAL_SERVER_ERROR,'status_message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)



class getPlanList(APIView):
	def get(self,request):
		try:
			plan_obj = SubscriptionPlan.objects.filter(end_date__isnull=True,status=True)
			allData = []
			for plan in plan_obj:
				all_data = {
					"id":plan.id,
					"plan_name":plan.planName,
					"plan_validity":plan.planDurationDays,
					"price":plan.price,
					"plan_description":plan.description,
					"digital_rental_contract":plan.digital_rental_contract,
					"notifications_stakeholders":plan.notifications_stakeholders,
					"visibility_among_ads":plan.visibility_among_ads,
					"visibility_at_top":plan.visibility_at_top,
					"information_of_local_area":plan.information_of_local_area,
				}
				allData.append(all_data)
			return Response({'status_code':status.HTTP_200_OK,'status_message':'Plan list fetched successfully','data':allData},status=status.HTTP_200_OK)
		except Exception as e:
			return Response({'status_code':status.HTTP_500_INTERNAL_SERVER_ERROR,'status_message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class getCompanyInformation(APIView):
	def get(self,request):
		check_obj  =  CompanyContactInformation.objects.all().first()
		if not check_obj:
			return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No data found'},status=status.HTTP_400_BAD_REQUEST)
		all_data = {
			'company_email':check_obj.company_email,
			'company_phone_number':check_obj.company_phone_number,
			'company_location':check_obj.company_location,
			'company_latitude':check_obj.company_latitude,
			'company_longitude':check_obj.company_longitude,
			'company_facebook':check_obj.company_facebook,
			'company_instagram':check_obj.company_instagram,
			'company_twitter':check_obj.company_twitter,
			'company_youtube':check_obj.company_youtube,
		}

		return Response({'status_code':status.HTTP_200_OK,'status_message':'company information fetched successfully','all_data':all_data},status=status.HTTP_200_OK)


class getHowItWork(APIView):
	def get(self,request):
		how_obj =  HowItWorks.objects.filter(end_date__isnull = True)
		all_Data = []
		for how in how_obj:
			all_data = {
				'id':how.id,
				'step_number':how.step_number,
				'icon':how.icon,
				'title':how.title,
				'description':how.description,
			}
			all_Data.append(all_data)

		return Response({'status_code':status.HTTP_200_OK,'status_message':'Fetched successfully','all_data':all_Data},status=status.HTTP_200_OK)




class propertyDevelopersDetails(APIView):
	def get(self,request):
		try:

			developer_id = self.request.query_params.get('id')
			if not developer_id:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'developer_id is required'},status=status.HTTP_400_BAD_REQUEST)

			cs = PropertyDevelopers.objects.filter(id=developer_id).first()
			if not cs:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No property developers found'},status=status.HTTP_400_BAD_REQUEST)
			
			investments = inquirePropertyProject.objects.filter(
				property_type ='property_developers',
				property_developers_id = cs.id,
				contract_status ='Deal-Completed',
			).aggregate(total_investment=Sum('investment_amount'))

			total_investment = investments['total_investment'] or 0.0
			print(total_investment)

			try:
				max_drawing = float(cs.maximum_drawing)

			except (ValueError, TypeError):
				max_drawing = 0.0

			if max_drawing > 0:
				percentage_invested = (total_investment / max_drawing) * 100
			else:
				percentage_invested = 0.0
			# can_stop_investment = total_investment > 0.0
			can_stop_investment=total_investment > 0.0
			if can_stop_investment:
				five_percent_of_investment = total_investment * 0.05
			else:
				five_percent_of_investment = 0.0
			all_data = {
				'id': cs.id,
				'customer_name': cs.customerId.firstName + ' ' + cs.customerId.lastName,
				'customer_id' : cs.customerId.id,
				'customer_phone_number' : cs.customerId.phoneNumber,
				'customerImage' : cs.customerId.profileImage,
				'image_data': ast.literal_eval(cs.property_image),
				'videos': cs.videos,
				'videos_thumbnail': cs.videos_thumbnail,
				'maximum_drawing':cs.maximum_drawing,
				'minimum_drawing': cs.minimum_drawing,

				'total_investment': total_investment,
				'percentage_invested': round(percentage_invested, 2),
				'can_stop_investment': can_stop_investment,
				'payment_done': cs.payment_done,
				'admin_cut':five_percent_of_investment,
				
				'document': cs.document,
				'property_name':cs.property_name,
				'property_type': cs.property_type,    
				'assest_equality': cs.assest_equality,
				'investment_highlight': cs.investment_highlight,
				'equity_price': cs.equity_price,
				'lp_equity_percent': cs.lp_equity_percent,
				'gp_equity_percent': cs.gp_equity_percent,
				'debt_percent': cs.debt_percent,
				'short_title': cs.short_title,
				'description': cs.description,
				'bussiness_plan': cs.bussiness_plan,
				'minimum_investment': cs.minimum_investment,
				'investment_strategy': cs.investment_strategy,
				'expected_period': cs.expected_period,
				'financed': cs.financed,
				'target_return_on_cost': cs.target_return_on_cost,
				'target_irr': cs.target_irr,
				'offered_by': cs.offered_by,
				'estimated_first_distribution': cs.estimated_first_distribution,
				'type_of_investment': cs.type_of_investment,
				'phone_number': cs.phone_number,
				'measure_of_multiplier': cs.measure_of_multiplier,
				'address': cs.address,
				'minimum_goal': cs.minimum_goal,

				'nominal_share_price': cs.nominal_share_price,
				'the_valuation': cs.the_valuation,
				'minimum_drawing': cs.minimum_drawing,
				'price_of_share':cs.price_of_share,
				'satutes':cs.satutes,

				'no_of_drawings': cs.no_of_drawings,
				'share_for_sale': cs.share_for_sale,
				'remaining_share': cs.remaining_share,
				'maximum_drawing': cs.maximum_drawing,
				'short_description': cs.short_description,
				'why_invest': cs.why_invest,
				'problem_to_be_solved': cs.problem_to_be_solved,
				'our_solution': cs.our_solution,
				'start_date_data': cs.start_date_data,
				'end_date_data': cs.end_date_data,
				'number_of_share': cs.number_of_share,
				'issue_minimum_investment': cs.issue_minimum_investment,
				'issue_maximum_investment': cs.issue_maximum_investment,
				'value_before_issue': cs.value_before_issue,
				'raised_capital_minimum_limit': cs.raised_capital_minimum_limit,
				'raised_capital_maximum_limit': cs.raised_capital_maximum_limit,
				'share_of_company_sold_minimum_limit': cs.share_of_company_sold_minimum_limit,
				'share_of_company_sold_maximum_limit': cs.share_of_company_sold_maximum_limit,
				'self_report': cs.self_report,
				'discussion_description': cs.discussion_description,
				'new_exisiting_details': cs.new_exisiting_details,
				'drawing_on_behalf': cs.drawing_on_behalf,
				'foundation': cs.foundation,
				'foundation_name': cs.foundation_name,

				'satutes': cs.satutes,
				'satutes_name': cs.satutes_name,

				'annual_account': cs.annual_account,
				'annual_account_name': cs.annual_account_name,

				'valuation': cs.valuation,
				'valuation_name': cs.valuation_name,

				'agreement_on_co': cs.agreement_on_co,
				'agreement_on_co_name': cs.agreement_on_co_name,

				'conversion_of_debt': cs.conversion_of_debt,
				'conversion_of_debt_name': cs.conversion_of_debt_name,

				'balance_sheet': cs.balance_sheet,
				'balance_sheet_name': cs.balance_sheet_name,

				'result_report': cs.result_report,
				'result_report_name': cs.result_report_name,

				'location': cs.location,
				'country': cs.country,
				'state': cs.state,
				'city': cs.city,
				'zip_code': cs.postal_code,
				'landmark': cs.landmark,
				'latitude': cs.latitude,
				'longitude': cs.longitude,
				'status': cs.status,
				'agency': cs.agency.id if cs.agency else None,
				'subscription_type': cs.subscription_type,
				'start_date': cs.start_date,
				'end_date': cs.end_date,
			}
			return Response({'status_code':status.HTTP_200_OK,'status_message':'Success','data':all_data})

		except Exception as e:
			print(e)
			return Response({'status_code':status.HTTP_500_INTERNAL_SERVER_ERROR,'status_message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)
		

class favouriteUnfavouritePropertyDevelopers(APIView):
	def post(self,request):
		token = get_authorization_header(request)
		if token is None or token == "null" or token.strip() == "":
			raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
		decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
		user_id = decoded['user_id']
		# return Response({'status_code':status.HTTP_200_OK,'status_message':'Removed from favourite list','id':user_id})
		customerObj=Customer.objects.filter(user=user_id).first()
		developer_id = request.data.get('developer_id')
		if not developer_id:
			return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Developer ID is required'},status=status.HTTP_400_BAD_REQUEST)
		developer_obj = PropertyDevelopers.objects.filter(id=developer_id).first()
		if not developer_obj:
			return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No property developer found'},status=status.HTTP_400_BAD_REQUEST)
		favourite_post, created = PropertyDevelopersFavourite.objects.get_or_create(property_developer=developer_obj,customerId=customerObj,is_favourite=1)
		if not created:
			favourite_post.delete()
			return Response({'status_code':status.HTTP_200_OK,'status_message':'Removed from favourite list'})
		else:
			favourite_post.save()
			return Response({'status_code':status.HTTP_200_OK,'status_message':'Added to favourite list.'})

"""-----------------------------------------------"""

# class HelpAndSupportQuerySerializer(serializers.ModelSerializer):
# 	user = serializers.PrimaryKeyRelatedField(read_only=True)

# 	class Meta:
# 		model = HelpAndSupportQuery
# 		fields = ['query', 'user']

# class RaiseQueryView(APIView):
# 	def post(self, request):
# 		token = get_authorization_header(request)
# 		if token is None or token == "null" or token.strip() == "":
# 			raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
# 		decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
# 		user_id = decoded['user_id']
# 		# return Response({'status_code':status.HTTP_200_OK,'status_message':'Removed from favourite list','id':user_id})
# 		customerObj=Customer.objects.filter(user=user_id).first()
# 		query = request.data.get('query')
# 		HelpAndSupportQuery.objects.create(user = customerObj,query = query)

# 		admin_notification = AdminNotifications.objects.create(
# 			message=f"New Query Raised by {customerObj.username}. Please review.",
# 			notification_type="Query Raised",
# 			is_read=False,
# 			start_date=now(),
# 			end_date=None
# 		)
# 		return Response({'status_code':status.HTTP_200_OK,'status_message':'Send successfully','id_get':user_id})
