from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from datetime import datetime
from django.conf import settings
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.backends import TokenBackend
from rest_framework.authentication import get_authorization_header
import jwt
from rest_framework import exceptions
from .models import *
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Q,Avg
from datetime import date
import datetime
from django.template.loader import render_to_string
from django.http.response import HttpResponse
import requests
from django.http import JsonResponse
from django.shortcuts import redirect
from customer_api.authentication import authenticated
from customer_api.models import *
# Create your views here.
from django.core.mail import EmailMultiAlternatives


from twilio.jwt.access_token.grants import (
    SyncGrant,
    ChatGrant,
    VideoGrant
)
from twilio.rest import Client
from twilio.jwt.access_token import AccessToken
from django.utils.timesince import timesince


account_sid= settings.TWILIO_ACCOUNT_SID
auth_token = settings.TWILIO_AUTH_TOKEN
chat_service_sid = settings.TWILIO_CHAT_SID
sync_service_sid = settings.TWILIO_SYNC_SID
api_sid = settings.TWILIO_API_SID
api_secret= settings.TWILIO_API_SECRET
client = Client(account_sid, auth_token)

class LawyerChangePassword(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            customer_obj=Customer.objects.filter(user=uid,loginUserType="lawyer").first()
            if not customer_obj:
                return Response({'message':'no user found'},status=status.HTTP_400_BAD_REQUEST)
            old_password = request.data.get('old_password')
            if not old_password:
                return Response({'message':'Old password is required'},status=status.HTTP_400_BAD_REQUEST)
            password = request.data.get('password')
            if not password:
                return Response({'message':'Password is required'},status=status.HTTP_400_BAD_REQUEST)
            confirm_password = request.data.get('confirm_password')
            if not confirm_password:
                return Response({'message':'Confirm password is required'},status=status.HTTP_400_BAD_REQUEST)
            if customer_obj.user.check_password(old_password) == False:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Does not match with the old password'},status=status.HTTP_400_BAD_REQUEST)
            if customer_obj.user.check_password(confirm_password) == True:
                    return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'You cannot set new password same as old password'},status=status.HTTP_400_BAD_REQUEST)
            customer_obj.user.set_password(confirm_password)
            customer_obj.user.save()
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Successfully Password Changed','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)
    
from customer_api.models import *

class LawyeremailVerifyOtp(APIView):
    def post(self, request):
        try:
            data=request.data
            email = data.get('email')
            otp = data.get('otp')
            customerObj=Customer.objects.filter(email=email).first()
            userObj = User.objects.filter(username=email).first()
            if not otp:
                return Response({'message':'otp is required'},status=status.HTTP_400_BAD_REQUEST)
            if customerObj.otp != otp:
                return Response({'message':'Invalid Otp'},status=status.HTTP_400_BAD_REQUEST)
            customerObj.emailVerified = True
            customerObj.save()
            refresh_token = RefreshToken.for_user(userObj)
            # sub_data = AgencySubscriptions.objects.filter(customer=customerObj,is_active=True).order_by('-id').first()
            # if sub_data:
            #     plan_id = sub_data.plan_id
            # else:
            #     plan_id = ""
            userData = {
                    'first_name':customerObj.firstName,
                    'last_name':customerObj.lastName,
                    'company':customerObj.agency_company,
                    'profile_image':customerObj.profileImage,
                    'email':customerObj.email,
                    'otp':customerObj.otp,
                    'email_verified':customerObj.emailVerified,
                    'isProfileCompleted':customerObj.isProfileCompleted,
                    'phoneVerified':customerObj.phoneVerified,
                    'customer_id':customerObj.id,
                    'has_subscription':customerObj.has_subscription,
                    # 'subscription_id':plan_id,

                }

            allData={
                    'refresh': str(refresh_token),
                    'access': str(refresh_token.access_token),
                    'user': userData
                    }
            return Response({'message':'OTP Verified','data':allData})
        except  Exception as e:
            return Response({"message":str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

import math, random, pytz, string


def GernateOTP():
    '''Function for gernate otp'''
    digits = "0123456789"
    OTP = ""
    for i in range(4) :
        OTP += digits[math.floor(random.random() * 10)]
    return OTP

class LawyerregisterResendOtp(APIView):
    def post(self, request):
        try:
            data=request.data
            email = data.get('email')
            customerObj=Customer.objects.filter(email=email).first()
            OTP=GernateOTP()
            customerObj.otp=OTP
            customerObj.save()
            message = "\nOTP has been sent on you registered email successfully:\n" + OTP
            context = {}
            to_emails = email
            subject = "Verify OTP:"
            message = EmailMultiAlternatives(subject=subject, from_email=settings.EMAIL_HOST_USER, to=[to_emails],body=message)
            message.send(fail_silently=False)
            return Response({'message':'Thank you for registering with us! To complete your sign-up process and verify your account, please use the One-Time Password (OTP) below:\n\nYour OTP is:',"otp":OTP})
        except  Exception as e:
            return Response({"message":str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class UserContractRequest(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_obj=Customer.objects.filter(user=uid,loginUserType="lawyer").first()
            if not customer_obj:
                return Response({'message':'no user found'},status=status.HTTP_400_BAD_REQUEST)
            
            contract_obj = LawyerContractDeals.objects.filter(lawyer= customer_obj.id)
            all_Data = []
            for contract in contract_obj:
                all_data = {
                    'id':contract.id,
                    'inquire_id':contract.inquiry.id,
                    'property_project_customer_name':contract.inquiry.customerId.firstName+' '+contract.inquiry.customerId.lastName,
                    'property_project_customer_email':contract.inquiry.customerId.email,
                    'property_project_customer_phone_number':contract.inquiry.customerId.phoneNumber,
                    'customer_email':contract.customer.email,
                    'customer_phone_number':contract.customer.phoneNumber,
                    'customer_name':contract.customer.firstName+' '+contract.customer.lastName,
                    'company_name':contract.inquiry.company_name,
                    'req_status':contract.req_status,
                }
                all_Data.append(all_data)
            return Response({'status_code':status.HTTP_200_OK,'status_message':'success','data':all_Data,'has_subscription':customer_obj.has_subscription}) 
        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 UserContractDetails(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_obj=Customer.objects.filter(user=uid,loginUserType="lawyer").first()
            if not customer_obj:
                return Response({'message':'no user found'},status=status.HTTP_400_BAD_REQUEST)
            contract_id = request.query_params.get('contract_id')
            if not contract_id:
                return Response({'message':'contract id is required'},status=status.HTTP_400_BAD_REQUEST)
            contract_obj = LawyerContractDeals.objects.filter(id=contract_id).first()
            if not contract_obj:
                return Response({'message':'No contract found'},status=status.HTTP_400_BAD_REQUEST)

            all_data = {
                'id': contract_obj.id if contract_obj and contract_obj.id else None,
                'inquire_id': contract_obj.inquiry.id if contract_obj and contract_obj.inquiry and contract_obj.inquiry.id else None,
                'property_project_customer_name': (
                    (contract_obj.inquiry.property_project.customerId.firstName or '') + ' ' +
                    (contract_obj.inquiry.property_project.customerId.lastName or '')
                ) if contract_obj and contract_obj.inquiry and contract_obj.inquiry.property_project and contract_obj.inquiry.property_project.customerId else None,
                'property_project_customer_email': contract_obj.inquiry.property_project.customerId.email if contract_obj and contract_obj.inquiry and contract_obj.inquiry.property_project and contract_obj.inquiry.property_project.customerId and contract_obj.inquiry.property_project.customerId.email else None,
                'property_project_customer_phone_number': contract_obj.inquiry.property_project.customerId.phoneNumber if contract_obj and contract_obj.inquiry and contract_obj.inquiry.property_project and contract_obj.inquiry.property_project.customerId and contract_obj.inquiry.property_project.customerId.phoneNumber else None,
                'customer_email': contract_obj.inquiry.email if contract_obj and contract_obj.inquiry and contract_obj.inquiry.email else None,
                'customer_phone_number': contract_obj.inquiry.telephone if contract_obj and contract_obj.inquiry and contract_obj.inquiry.telephone else None,
                'company_name': contract_obj.inquiry.company_name if contract_obj and contract_obj.inquiry and contract_obj.inquiry.company_name else None,
                'message': contract_obj.inquiry.message if contract_obj and contract_obj.inquiry and contract_obj.inquiry.message else None,
                'contract_status': contract_obj.inquiry.contract_status if contract_obj and contract_obj.inquiry and contract_obj.inquiry.contract_status else None,
            }

            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 AcceptRejectUserContractRequest(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)
            customerObj = Customer.objects.filter(user=uid).first()
            req_status = request.data.get('req_status')
            contract_id = request.data.get('contract_id')
            if not req_status:
                return Response({'message':'req_status is required'},status=status.HTTP_400_BAD_REQUEST)
            if not contract_id:
                return Response({'message':'contract_id is required'},status=status.HTTP_400_BAD_REQUEST)
            get_data=LawyerContractDeals.objects.filter(id=contract_id).first()
            if not get_data:
                return Response({'message':'LawyerContractDeals not found'},status=status.HTTP_400_BAD_REQUEST)
            get_data.req_status=req_status
            get_data.save()
            return Response({'message': 'Success'})
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)    

class LawyerSubscriptionExpires(APIView):
    def get(self, request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            customerObj=Customer.objects.filter(loginUserType="agency").first()
            for customer in customerObj:
                agency_obj = LawyerSubscriptions.objects.filter(customer=customer.id,is_active = True).order_by('-id').first()
                today = date.today()
                if agency_obj.sub_expiry_date == today:
                    customer.has_subscription = False
                    customer.save()
                    agency_obj.is_active = False
                    agency_obj.save()
            return Response({'message':'success'})

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



class LawyerAddRatingReview(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)
            customerObj = Customer.objects.filter(user=uid).first()
            rating_data = request.data.get('rating_data')
            if not rating_data:
                return Response({'message':'rating_data is required'},status=status.HTTP_400_BAD_REQUEST)
            review_data = request.data.get('review_data')
            if not review_data:
                return Response({'message':'review_data is required'},status=status.HTTP_400_BAD_REQUEST)
            receive_customer_id = request.data.get('receive_customer_id')
            if not receive_customer_id:
                return Response({'message':'receive_customer_id is required'},status=status.HTTP_400_BAD_REQUEST)
            receieve_customer_obj = Customer.objects.filter(id = receive_customer_id).first()
            lawyerRatingAndReview.objects.create(send_user_customer=customerObj,lawyer_receive_customer=receieve_customer_obj,rating=rating_data,review=review_data)
            return Response({'message': 'Success'})
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)         

class LawyerEditRatingReview(APIView):
    def get(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)
            customerObj = Customer.objects.filter(user=uid).first()	
            rating_id =  request.query_params.get('rating_id')
            if not rating_id:
                return Response({'message':'rating_id is required'},status=status.HTTP_400_BAD_REQUEST)
            rating_obj = lawyerRatingAndReview.objects.filter(id=rating_id).first()
            if not rating_obj:
                return Response({'message':'No rating data found is required'},status=status.HTTP_400_BAD_REQUEST)
            all_data = {
                'rating': rating_obj.rating,
                'review': rating_obj.review,

            }
            return Response({'message': 'Success','data':all_data})
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        
        
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)
            customerObj = Customer.objects.filter(user=uid).first()
            rating_id = request.data.get('rating_id')
            if not rating_id:
                return Response({'message':'rating_id is required'},status=status.HTTP_400_BAD_REQUEST)
            rating_data = request.data.get('rating_data')
            if not rating_data:
                return Response({'message':'rating_data is required'},status=status.HTTP_400_BAD_REQUEST)
            review_data = request.data.get('review_data')
            if not review_data:
                return Response({'message':'review_data is required'},status=status.HTTP_400_BAD_REQUEST)
            lawyerRatingAndReview.objects.filter(id=rating_id).update(rating=rating_data,review=review_data)
            return Response({'message': 'Success'})
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class LawyerDeleteRatingReview(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)
            customerObj = Customer.objects.filter(user=uid).first()	
            rating_id = request.data.get('rating_id')
            if not rating_id:
                return Response({'message':'rating_id is required'},status=status.HTTP_400_BAD_REQUEST)
            rating_obj = lawyerRatingAndReview.objects.filter(id = rating_id).first()
            rating_obj.delete()
            return Response({'message': 'Success'})
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class LawyerGetMyRatings(APIView):
    def get(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)
            customerObj = Customer.objects.filter(user=uid).first()	
            rating_obj = lawyerRatingAndReview.objects.filter(lawyer_receive_customer=customerObj )
            all_Data = []
            for rating in rating_obj:
                all_data = {
                    'customer_name': rating.send_customer.firstName +" "+ rating.send_customer.lastName,
                    'customer_image': rating.send_customer.profileImage,
                    'rating': rating.rating,
                    'rating_date': rating.created_at,
                }
                all_Data.append(all_data)
            return Response({'message': 'Success','data':all_Data})
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class LawyerGetMyReviews(APIView):
    def get(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)
            customerObj = Customer.objects.filter(user=uid).first()	
            review_obj = lawyerRatingAndReview.objects.filter(lawyer_receive_customer=customerObj )
            all_Data = []
            for review in review_obj:
                all_data = {
                    'customer_name':review.send_customer.firstName+" "+review.send_customer.lastName,
                    'customer_image':review.send_customer.profileImage,
                    'reviews':review.review,
                    'review_date':review.start_date,
                }
                all_Data.append(all_data)
            return Response({'message': 'Success','data':all_Data})			
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



class LawyerViewRatingReviews(APIView):
    def get(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)
            customerObj = Customer.objects.filter(user=uid).first()	
            customer_id =  request.query_params.get('customer_id')
            if not customer_id:
                return Response({'message':'customer_id is required'},status=status.HTTP_400_BAD_REQUEST)
            rating_obj = lawyerRatingAndReview.objects.filter(lawyer_receive_customer = customer_id)
            if rating_obj:
                average_rating = lawyerRatingAndReview.objects.filter(lawyer_receive_customer=customer_id).aggregate(Avg('rating'))['rating__avg']
                total_reviews = lawyerRatingAndReview.objects.filter(lawyer_receive_customer = customer_id).count()
                rating_review_data = []
                for rating in rating_obj:
                    all_data = {
                        'customer_name':rating.send_customer.firstName+" "+rating.send_customer.firstName,
                        'customer_image':rating.send_customer.profileImage,
                        'rating':rating.rating,
                        'review':rating.review,
                        'rating_review_date':rating.start_date,

                    }
                    rating_review_data.append(all_data)
                return Response({'message': 'Success','rating_review_data':rating_review_data,'average_rating':round(average_rating),'total_reviews':total_reviews})			
            else:
                return Response({'message': 'Success','rating_review_data':" ",'average_rating':" ",'total_reviews':" "})			

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




class lawyerConverstationToken(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

                identity = customerObj.id
                token = AccessToken(account_sid,api_sid,api_secret,identity=identity)

                if chat_service_sid:
                    chat_grant = ChatGrant(service_sid=chat_service_sid)
                    token.add_grant(chat_grant)

                notification = client.conversations \
                .v1 \
                .services(chat_service_sid) \
                .configuration \
                .notifications() \
                .update(
                    new_message_enabled=True,
                    new_message_sound='default',
                    new_message_template="You have a new message in ${CONVERSATION}: ${MESSAGE}"
                )

                alldata = {
                'identity':identity,
                'token':token.to_jwt(),
                }
                return Response ({'status_code':status.HTTP_200_OK,'status_message':'Token Created Successfully','data':alldata})
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        

class lawyerConverstationListing(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
            conversations = ConversationLawyer.objects.filter(lawyer = customerObj.id ).order_by('-id')
            
            conversation_list = []
            for conversation in conversations:
                messages = client.conversations \
                    .v1 \
                    .conversations(conversation.twilio_channel_sid) \
                    .messages \
                    .list(order='desc', limit=1)
                last_message = ''
                time = ''
                message_date = ''
                for record in messages:
                    if record.body:
                        last_message = record.body 
                        time = timesince(record.date_created)+' ago'
                        message_date = record.date_created
                    elif record.media:
                        last_message = 'file'
                        time = timesince(record.date_created)+' ago'
                        message_date = record.date_created
        
                
                conversation_data = {
                    "id": conversation.id,
                    "twilio_channel_sid": conversation.twilio_channel_sid,
                    "customer_id": conversation.customer.id,
                    "customer_name": conversation.customer.name,
                    "customer_image": conversation.customer.image,
                    "lawyer_id":conversation.lawyer.id,
                    "lawyer_name": conversation.lawyer.name,
                    "lawyer_image": conversation.lawyer.image,
                    "last_message":last_message,
                    "time":time,
                    "message_date":message_date,
                }
                conversation_list.append(conversation_data)
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'success','data':conversation_list})	
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        

        
class lawyerConverstationDelete(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
            converstation_id = request.data.get('converstation_id')
            if not converstation_id:
                return Response({'status_code': status.HTTP_400_BAD_REQUEST, 'status_message': 'No customer found'})

            conversations = ConversationLawyer.objects.filter(id = converstation_id ).first()
            conversations.delete()
            
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'success'})	

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


class getPrivacyPolicy(APIView):
    def get(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)
            customerObj = Customer.objects.filter(user=uid).first()	
            customer_id =  request.query_params.get('customer_id')
            if not customer_id:
                return Response({'message':'customer_id is required'},status=status.HTTP_400_BAD_REQUEST)
            privacy_obj  = ContentPagesAdmin.object.filter(page_type_name = 'lawyer_privacy').first()
            all_data = {
                'id':privacy_obj.id,
                'page_type_name':privacy_obj.page_type_name,
                'page_title':privacy_obj.page_title,
                'page_content':privacy_obj.page_content,
                'status':privacy_obj.status,
            }
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'success','all_data':all_data})	
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class getTermsCondition(APIView):
    def get(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)
            customerObj = Customer.objects.filter(user=uid).first()	
            terms_obj  = ContentPagesAdmin.object.filter(page_type_name = 'lawyer_terms').first()
            all_data = {
                'id':terms_obj.id,
                'page_type_name':terms_obj.page_type_name,
                'page_title':terms_obj.page_title,
                'page_content':terms_obj.page_content,
                'status':terms_obj.status,
            }		
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'success','all_data':all_data})	

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


class getFAQLawyer(APIView):
    def get(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)
            customerObj = Customer.objects.filter(user=uid).first()	
            faq_obj  =  AgencyFaq.objects.filter(end_date__isnull = True)
            all_Data = []
            for faq in faq_obj:
                all_Data.append({
                    'id':faq.id,
                    'title':faq.title,
                    'content':faq.content,
                })
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'success','all_Data':all_Data})	
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        
import ast

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

            # Retrieve and exclude finalized records at the ORM level
            finalise_qs = FinalizeLawyerTable.objects.filter(
                lawyer=customerObj
            )
            if not finalise_qs.exists():
                return Response({
                    'status_code': status.HTTP_200_OK,
                    'status_message': 'No records found .'
                }, status=status.HTTP_200_OK)

            # --- Pagination parameters ---
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('page_size', 10))
            start = (page - 1) * page_size
            end = start + page_size

            total_records = finalise_qs.count()
            paginated_qs = finalise_qs[start:end]

            all_data = []
            for finalise in paginated_qs:
                all_data.append({
                    "id": finalise.id,
                    "customer_id": finalise.customer.id if finalise.customer else None,
                    "customer_firstName": finalise.customer.firstName if finalise.customer else "",
                    "customer_lastName": finalise.customer.lastName if finalise.customer else "",
                    "customer_email": finalise.customer.email if finalise.customer else "",
                    "customer_phoneNumber": finalise.customer.phoneNumber if finalise.customer else "",
                    "lawyer_id": finalise.lawyer.id if finalise.lawyer else None,
                    "lawyer_email": finalise.lawyer.email if finalise.lawyer else "",
                    "lawyer_phoneNumber": finalise.lawyer.phoneNumber if finalise.lawyer else "",
                    "property_type": finalise.property_type,
                    # images/docs omitted
                    "final_amount": finalise.final_amount,
                    "customer_signature": finalise.customer_signature,
                    "lawyer_signature": finalise.lawyer_signature,
                    "finalized_status": finalise.finalized_status,
                    "contract_id": finalise.contract_id,
                    
                    "created_at": finalise.created_at,
                    "updated_at": finalise.updated_at,
                    "end_date": finalise.end_date,
                })

            return Response({
                'status_code': status.HTTP_200_OK,
                'message': 'Listed Successfully',
                'all_data': all_data,
                'page': page,
                'page_size': page_size,
                'total_records': total_records
            }, 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 CompleteFinalizeLawyer(APIView):
    def get(self,request):
        try:
            token = get_authorization_header(request)
            if token:
                decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=["HS256"])
                user_id = decoded['user_id']
                customerObj=Customer.objects.filter(user=user_id).first()
            else:
                customerObj= 0
            all_data=[]
            finalize_request_id = request.GET.get('finalize_request_id')
            if not finalize_request_id:
                 return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'finalize_request_id  is required'},status=status.HTTP_400_BAD_REQUEST)
            finalise=FinalizeLawyerTable.objects.filter(id=finalize_request_id).first()
            if not finalise:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'finalise_table not found'},status=status.HTTP_400_BAD_REQUEST)
            elif finalise.finalized_status=="finalized by customer and lawyer":
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Already finalized'},status=status.HTTP_400_BAD_REQUEST)
            all_data.append({
                    "id": finalise.id,
                    "customer_id": finalise.customer.id if finalise.customer else None,
                    "customer_firstName": finalise.customer.firstName if finalise.customer else "",
                    "customer_lastName": finalise.customer.lastName if finalise.customer else "",
                    "customer_email": finalise.customer.email if finalise.customer else "",
                    "customer_phoneNumber": finalise.customer.phoneNumber if finalise.customer else "",

                    "lawyer_id": finalise.lawyer.id if finalise.lawyer else None,
                    "lawyer_company": finalise.lawyer.agency_company if finalise.lawyer else "",
                    "lawyer_email": finalise.lawyer.email if finalise.lawyer else "",
                    "lawyer_phoneNumber": finalise.lawyer.phoneNumber if finalise.lawyer else "",

                    "property_type": finalise.property_type,
                    "property_image": ast.literal_eval(finalise.property_image),
                    "property_video": finalise.property_video,
                    "property_document": finalise.property_doc,
                    "property_name": finalise.property_type,
                    "final_amount": finalise.final_amount,
                    "customer_signature": finalise.customer_signature,
                    "lawyer_signature": finalise.lawyer_signature,
                    "created_at": finalise.created_at,
                    "updated_at": finalise.updated_at,
                    "finalized_status":finalise.finalized_status,
                    "end_date": finalise.end_date,
                })
            
            

            return Response({'status_code':status.HTTP_200_OK,'message':'Listed Successfully',"all_data":all_data[0]},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)
    def post(self,request):
        try:
            token = get_authorization_header(request)
            if token:
                decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=["HS256"])
                user_id = decoded['user_id']
                customerObj=Customer.objects.filter(user=user_id).first()
            else:
                customerObj= 0
            all_data=[]
            finalize_request_id = request.data.get('finalize_request_id')
            lawyer_signature = request.data.get('lawyer_signature')
            if not finalize_request_id:
                 return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'finalize_request_id  is required'},status=status.HTTP_400_BAD_REQUEST)
            if not lawyer_signature:
                 return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'lawyer_signature  is required'},status=status.HTTP_400_BAD_REQUEST)
            finalise=FinalizeLawyerTable.objects.filter(id=finalize_request_id).first()
            if not finalise:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'finalise_table not found'},status=status.HTTP_400_BAD_REQUEST)
            finalise.lawyer_signature=lawyer_signature
            finalise.finalized_status="finalized by customer and lawyer"
            finalise.contract.req_status="finalized by customer and lawyer"
            finalise.lawyer.total_hire_count-=1
            finalise.lawyer.save()
            finalise.save()
            finalise.contract.save()
            
            

            return Response({'status_code':status.HTTP_200_OK,'message':'Signature added Successfully'},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 createConverstationCustomer(APIView):
    def post(self, request):
        token = get_authorization_header(request)
        if token:
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=["HS256"])
            user_id = decoded['user_id']
            customerObj=Customer.objects.filter(user=user_id).first()
        else:
            customerObj= 0
        
        chat_customer = request.data.get('chat_customer')
        if not chat_customer:
            return Response({'status_code': status.HTTP_400_BAD_REQUEST, 'status_message': 'chat_customer is required.'},status= status.HTTP_400_BAD_REQUEST)
        
        chat_customer_obj = Customer.objects.filter(id=chat_customer).first()
        if not chat_customer_obj:
            return Response({'status_code': status.HTTP_400_BAD_REQUEST, 'status_message': 'No customer found'},status= status.HTTP_400_BAD_REQUEST)
        existing_conversation = ConversationCustomers.objects.filter(customer_two=chat_customer_obj, customer_one=customerObj).first()
        if existing_conversation:
            print("here")
            twilio_channel_sid = existing_conversation.twilio_channel_sid
        else:
            print("here2")

            concatinate_names= str(chat_customer_obj.firstName) + str(customerObj.firstName) + str(chat_customer_obj.id) + str(customerObj.id) 
            suffle_string = list(concatinate_names)
            random.shuffle(suffle_string)
            conversation_name = ''.join(suffle_string)
            # Create Conversation chat
            conversation = client.conversations \
                    .v1 \
                    .conversations \
                    .create(friendly_name=conversation_name)
            
            conversation_obj = ConversationCustomers.objects.filter(Q(customer_one=customerObj,customer_two=chat_customer_obj) | Q(customer_one = chat_customer_obj,customer_two=customerObj)).first()
            if not conversation_obj:
                conversation_obj = ConversationCustomers.objects.create(customer_one=customerObj,customer_two=chat_customer_obj )
                conversation_obj.twilio_channel_sid = conversation.sid
            conversation_obj.last_message = datetime.now()
            conversation_obj.save()
            user_attributes= {"id":str(customerObj.id),"name":str(customerObj.firstName),
                "image":str(customerObj.profileImage)
            }
            user_json_attributes = json.dumps(user_attributes)

            chat_user_participant = client.conversations \
                .v1 \
                .conversations(conversation.sid) \
                .participants \
                .create(identity=str(customerObj.id),attributes=user_json_attributes)
            
              
            user_two_attributes= {"id":str(chat_customer_obj.id),"name":str(chat_customer_obj.firstName),
                "image":str(chat_customer_obj.profileImage)
            }	
            user_two_attributes_json_attributes = json.dumps(user_two_attributes)

            user_two_attributes_participant = client.conversations \
                .v1 \
                .conversations(conversation.sid) \
                .participants \
                .create(identity=str(chat_customer_obj.id),attributes=user_two_attributes_json_attributes)
    


            conversation_obj.customer_one_twilio_id = chat_user_participant.sid
            conversation_obj.customer_two_twilio_id = user_two_attributes_participant.sid
            conversation_obj.save()

            twilio_channel_sid = conversation_obj.twilio_channel_sid
        return Response ({'status_code':status.HTTP_200_OK,'status_message':'conversation Added successfully','twilio_channel_sid':twilio_channel_sid},status= status.HTTP_200_OK)



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

            identity = customerObj.id
            token = AccessToken(account_sid,api_sid,api_secret,identity=identity)

            if chat_service_sid:
                chat_grant = ChatGrant(service_sid=chat_service_sid)
                token.add_grant(chat_grant)

            notification = client.conversations \
            .v1 \
            .services(chat_service_sid) \
            .configuration \
            .notifications() \
            .update(
                new_message_enabled=True,
                new_message_sound='default',
                new_message_template="You have a new message in ${CONVERSATION}: ${MESSAGE}"
            )

            alldata = {
            'identity':identity,
            'token':token.to_jwt(),
            }
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Token Added 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 customerConverstationListing(APIView):
    def get(self,request):
        try:
            token = get_authorization_header(request)
            if token:
                decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=["HS256"])
                user_id = decoded['user_id']
                customerObj=Customer.objects.filter(user=user_id).first()
                print(customerObj)
            else:
                customerObj= 0
            print('customerObj',customerObj)
            # customer=request.GET.get(cui)
            conversations = ConversationCustomers.objects.filter(
                Q(customer_one=customerObj.id, customer_two__loginUserType='customer') |
                Q(customer_two=customerObj.id, customer_one__loginUserType='customer')
            ).exclude(
                customer_deleted=customerObj
            ).order_by('-id')
            if not conversations:
                print("here")
                # conversations = ConversationAgency.objects.filter(customer = customerObj ).order_by('-id')
                conversations = ConversationAgency.objects.filter(Q(customer=customerObj) |
                Q(agency=customerObj)).order_by('-id')
            print(conversations)
            # if not conversations:
            # 	print("here")
            # 	conversations = ConversationCustomers.objects.filter(customer_two = customerObj.id ).exclude(id=user_id).order_by('-id')
            print(conversations)
            conversation_list = []
            for conversation in conversations:
                messages = client.conversations \
                    .v1 \
                    .conversations(conversation.twilio_channel_sid) \
                    .messages \
                    .list(order='desc', limit=1)
                print('messages:-')
                print(messages)
                last_message = ''
                time = ''
                message_date = ''
                for record in messages:
                    print('record:-')
                    print('record:-',record.body)
                    print('record:-',record.media)
                    if record.body:
                        print('record.body')
                        print(record.body)
                        last_message = record.body
                         
                        print(last_message)
                        last_message = json.loads(last_message)
                        # Access the 'message' value
                        last_message = last_message['message']
                    

                        time = timesince(record.date_created)+' ago'
                        message_date = record.date_created

                    elif not record.media:
                        print('record.media')
                        print(record.media)

                        last_message = 'Media file'
                        time = timesince(record.date_created)+' ago'
                        message_date = record.date_created
        
                print(conversation)
                conversation_data = {
                    "id": conversation.id,
                    "twilio_channel_sid": conversation.twilio_channel_sid,
                    "customer_one_name": conversation.customer_one.firstName +" "+conversation.customer_one.lastName,
                    "customer_one_image": conversation.customer_one.profileImage,
                    "customer_one_id":conversation.customer_one.id,
                    "customer_one_phone_number":conversation.customer_one.phoneNumber,
                    "customer_two_name": conversation.customer_two.firstName +" "+conversation.customer_two.lastName,
                    "customer_two_image": conversation.customer_two.profileImage,
                    "customer_two_id": conversation.customer_two.id,
                    "customer_two_phone_number":conversation.customer_two.phoneNumber,
                    "last_message":last_message,
                    "time":time,
                    "message_date":message_date,
                }
                conversation_list.append(conversation_data)
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'success','data':conversation_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)

import json
class AgencyConverstationListing(APIView):
    def get(self,request):
        try:
            token = get_authorization_header(request)
            if token:
                decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=["HS256"])
                user_id = decoded['user_id']
                customerObj=Customer.objects.filter(user=user_id).first()
            else:
                customerObj= 0
            # customer=request.GET.get(cui)
            conversations = ConversationCustomers.objects.filter(
                Q(customer_one=customerObj.id, customer_two__loginUserType='agency') |
                Q(customer_two=customerObj.id, customer_one__loginUserType='agency')
            ).exclude(
                customer_deleted=customerObj
            ).order_by('-id')
            
            conversation_list = []
            for conversation in conversations:
                messages = client.conversations \
                    .v1 \
                    .conversations(conversation.twilio_channel_sid) \
                    .messages \
                    .list(order='desc', limit=1)
                print('messages:-')
                print(messages)
                last_message = ''
                time = ''
                message_date = ''
                for record in messages:
                    print('record:-')
                    print('record:-',record.body)
                    print('record:-',record.media)
                    if record.body:
                        print('record.body')
                        print(record.body)
                        last_message = record.body
                         
                        print(last_message)
                        last_message = json.loads(last_message)
                        # Access the 'message' value
                        last_message = last_message['message']
                    

                        time = timesince(record.date_created)+' ago'
                        message_date = record.date_created

                    elif not record.media:
                        print('record.media')
                        print(record.media)

                        last_message = 'Media file'
                        time = timesince(record.date_created)+' ago'
                        message_date = record.date_created
        
                print(conversation)
                conversation_data = {
                    "id": conversation.id,
                    "twilio_channel_sid": conversation.twilio_channel_sid,
                    "customer_one_name": conversation.customer_one.firstName +" "+conversation.customer_one.lastName,
                    "customer_one_image": conversation.customer_one.profileImage,
                    "customer_one_id":conversation.customer_one.id,
                    "customer_one_phone_number":conversation.customer_one.phoneNumber,
                    "customer_two_name": conversation.customer_two.firstName +" "+conversation.customer_two.lastName,
                    "customer_two_image": conversation.customer_two.profileImage,
                    "customer_two_id": conversation.customer_two.id,
                    "customer_two_phone_number":conversation.customer_two.phoneNumber,
                    "last_message":last_message,
                    "time":time,
                    "message_date":message_date,
                }
                conversation_list.append(conversation_data)
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'success','data':conversation_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 LawyerConverstationListing(APIView):
    def get(self,request):
        try:
            token = get_authorization_header(request)
            if token:
                decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=["HS256"])
                user_id = decoded['user_id']
                customerObj=Customer.objects.filter(user=user_id).first()
            else:
                customerObj= 0
            # customer=request.GET.get(cui)
            conversations = ConversationCustomers.objects.filter(
                Q(customer_one=customerObj.id, customer_two__loginUserType='lawyer') |
                Q(customer_two=customerObj.id, customer_one__loginUserType='lawyer')
            ).exclude(
                customer_deleted=customerObj
            ).order_by('-id')
            # if not conversations:
            # 	print("here")
            # 	conversations = ConversationCustomers.objects.filter(customer_two = customerObj.id ).exclude(id=user_id).order_by('-id')
            print(conversations)
            conversation_list = []
            for conversation in conversations:
                messages = client.conversations \
                    .v1 \
                    .conversations(conversation.twilio_channel_sid) \
                    .messages \
                    .list(order='desc', limit=1)
                print('messages:-')
                print(messages)
                last_message = ''
                time = ''
                message_date = ''
                for record in messages:
                    print('record:-')
                    print('record:-',record.body)
                    print('record:-',record.media)
                    if record.body:
                        print('record.body')
                        print(record.body)
                        last_message = record.body
                         
                        print(last_message)
                        last_message = json.loads(last_message)
                        # Access the 'message' value
                        last_message = last_message['message']
                    

                        time = timesince(record.date_created)+' ago'
                        message_date = record.date_created

                    elif not record.media:
                        print('record.media')
                        print(record.media)

                        last_message = 'Media file'
                        time = timesince(record.date_created)+' ago'
                        message_date = record.date_created
        
                print(conversation)
                conversation_data = {
                    "id": conversation.id,
                    "twilio_channel_sid": conversation.twilio_channel_sid,
                    "customer_one_name": conversation.customer_one.firstName +" "+conversation.customer_one.lastName,
                    "customer_one_image": conversation.customer_one.profileImage,
                    "customer_one_id":conversation.customer_one.id,
                    "customer_one_phone_number":conversation.customer_one.phoneNumber,
                    "customer_two_name": conversation.customer_two.firstName +" "+conversation.customer_two.lastName,
                    "customer_two_image": conversation.customer_two.profileImage,
                    "customer_two_id": conversation.customer_two.id,
                    "customer_two_phone_number":conversation.customer_two.phoneNumber,
                    "last_message":last_message,
                    "time":time,
                    "message_date":message_date,
                }
                conversation_list.append(conversation_data)
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'success','data':conversation_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 LawyerPropertyRequest(APIView):
    def get(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            customerObj=Customer.objects.filter(user=uid,loginUserType="lawyer").first()
            propertyObj =  LawyerPropertyRequests.objects.filter(lawyer = customerObj.id)
            propertyData = []
            for property in propertyObj:
                approved_requested = LawyerApprovedProperty.objects.filter(lawyer = customerObj.id)
                if approved_requested:
                    is_requested = True
                else:
                    is_requested = False

                data = {
                    'id':property.id,
                    'mobile_number':property.mobile_number,
                    'name':property.name,
                    'email':property.email,
                    'property_type':property.property_type,
                    'req_status':property.status,
                    'is_requested':is_requested,
                    'customer_id':property.customer.id,
                    'customer_mail':property.customer.email,
                    'is_contract_created':property.is_contract_created,
                    'date':property.start_date,
                }
                propertyData.append(data)
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Success','data':propertyData,'has_subscription':customerObj.has_subscription})
        except Exception as e:
            return Response({'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)




class ApprovePropertyRequest(APIView):
    def post(self, request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            customerObj=Customer.objects.filter(user=uid,loginUserType="lawyer").first()
            property_id = request.data.get('property_id')
            if not property_id:
                return Response({'message':'property_id is required'},status=status.HTTP_400_BAD_REQUEST)
            req_status = request.data.get('req_status')
            if not req_status:
                return Response({'message':'req_status is required'},status=status.HTTP_400_BAD_REQUEST)

            property_obj = LawyerPropertyRequests.objects.filter(id= property_id).first()
            if not property_obj:
                return Response({'message':'Property request not found'},status=status.HTTP_400_BAD_REQUEST)
            property_obj.status = req_status
            property_obj.save()
            request_customer = Customer.objects.filter(id=property_obj.customer.id).first()
            LawyerApprovedProperty.objects.create(lawyer_id = customerObj.id,customer = request_customer,property_request = property_obj)
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Success'})
        except Exception as e:
            return Response({'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)




class DoItLawyerContract(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'status_code':status.HTTP_401_UNAUTHORIZED,'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)
            customerObj=Customer.objects.filter(user=uid,loginUserType="lawyer").first()
            data = request.data
            property_id =  data.get('property_id')
            if not property_id:
                return Response({'status':status.HTTP_400_BAD_REQUEST,'message':'property_id is required'},status=status.HTTP_400_BAD_REQUEST)
            request_obj = LawyerPropertyRequests.objects.filter(id =  property_id).first()
            if not request_obj:
                return Response({'status':status.HTTP_400_BAD_REQUEST,'message':'No do it by lawyer property request found'},status=status.HTTP_400_BAD_REQUEST)
            customer_id = data.get('customer_id')
            customer_new=Customer.objects.filter(id=customer_id).first()
            if not customer_new:
                return Response({'status':status.HTTP_400_BAD_REQUEST,'message':'No customer found'},status=status.HTTP_400_BAD_REQUEST)


            contract_file = data.get('contract_file')
            company_name = data.get('company_name')
            full_name = data.get('full_name')
            if not contract_file:
                return Response({'status':status.HTTP_400_BAD_REQUEST,'message':'Please select contract file'},status=status.HTTP_400_BAD_REQUEST)
            if not full_name:
                return Response({'status':status.HTTP_400_BAD_REQUEST,'message':'full_name is required'},status=status.HTTP_400_BAD_REQUEST)
            if not company_name:
                return Response({'status':status.HTTP_400_BAD_REQUEST,'message':'company_name is required'},status=status.HTTP_400_BAD_REQUEST)
            contractObj = LawyerDoItPropertyContract.objects.create(contract_file=contract_file,company_name=company_name,full_name=full_name,lawyer_doit = customerObj,customer_doit= customer_new,property_request = request_obj,status = "contract_created")
            request_obj.is_contract_created = True
            request_obj.status = "contract created"

            request_obj.save()
            return Response({'status':status.HTTP_200_OK,'message':'Contract start from Seller Successfully','contract_id':contractObj.id},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) 
