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,timedelta
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
from customer_api.authentication import authenticated
from customer_api.models import *
from datetime import date
import datetime
from django.template.loader import render_to_string
from django.core import mail
from django.template.loader import get_template
from django.http.response import HttpResponse
from django.core.mail import EmailMessage
import xhtml2pdf.pisa as pisa
import stripe
import paypalrestsdk
import requests
from django.http import JsonResponse
from django.shortcuts import redirect
from agency_panel.models import *
from lawyer_panel.models import *

# Create your views here.


class addPlan(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            plan_name = data.get('plan_name')
            plan_description= data.get('plan_description')
            price = data.get('price')
            discount =  data.get('discount')
            package_type = data.get('package_type')
            plan_validity = data.get('plan_validity')
            digital_rental_contract = data.get('digital_rental_contract')
            notifications_stakeholders = data.get('notifications_stakeholders')
            visibility_among_ads = data.get('visibility_among_ads')
            visibility_at_top = data.get('visibility_at_top')
            information_of_local_area = data.get('information_of_local_area')
            property_count = data.get('property_count')
            tyre_type = data.get('tier_type')

            if not plan_name:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan name is required'},status=status.HTTP_400_BAD_REQUEST)
            if not plan_description:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan description is required'},status=status.HTTP_400_BAD_REQUEST)
            if not price:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'price is required'},status=status.HTTP_400_BAD_REQUEST)
            if not plan_validity:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan validity is required'},status=status.HTTP_400_BAD_REQUEST)
            if not tyre_type:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'tyre type is required'},status=status.HTTP_400_BAD_REQUEST)
            if not package_type:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Package type is required'},status=status.HTTP_400_BAD_REQUEST)
            if not property_count:
                 return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'property count is required'},status=status.HTTP_400_BAD_REQUEST)
            # if not notifications_stakeholders:
            # 	return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'notifications stakeholders is required'},status=status.HTTP_400_BAD_REQUEST)
            # if not visibility_among_ads:
            # 	return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'visibility among ads is required'},status=status.HTTP_400_BAD_REQUEST)
            # if not visibility_at_top:
            # 	return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'visibility at top is required'},status=status.HTTP_400_BAD_REQUEST)
            # if not information_of_local_area:
            # 	return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'information of local area is required'},status=status.HTTP_400_BAD_REQUEST)

            
            ifExist = SubscriptionPlan.objects.filter(planName=plan_name).first()
            if ifExist:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Plan name already in use'},status=status.HTTP_400_BAD_REQUEST)

            planObj = SubscriptionPlan.objects.create(planName=plan_name)
            planObj.planDurationDays = plan_validity
            planObj.price = price
            planObj.discount = discount
            planObj.package_type = package_type
            planObj.description = plan_description
            planObj.digital_rental_contract = digital_rental_contract
            planObj.notifications_stakeholders = notifications_stakeholders
            planObj.visibility_among_ads = visibility_among_ads
            planObj.visibility_at_top = visibility_at_top
            planObj.information_of_local_area = information_of_local_area
            planObj.tyre_type = tyre_type
            planObj.property_count = property_count
            planObj.save()
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Plan created successfully'})
        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 editPlan(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            plan_id = data.get('id')
            plan_name = data.get('plan_name')
            plan_description= data.get('plan_description')
            price = data.get('price')
            discount =  data.get('discount')
            package_type = data.get('package_type')
            plan_validity = data.get('plan_validity')
            digital_rental_contract = data.get('digital_rental_contract')
            notifications_stakeholders = data.get('notifications_stakeholders')
            visibility_among_ads = data.get('visibility_among_ads')
            visibility_at_top = data.get('visibility_at_top')
            information_of_local_area = data.get('information_of_local_area')
            tyre_type = data.get('tier_type')
            property_count = data.get('property_count')
            
            if not plan_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            if not plan_name:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan name is required'},status=status.HTTP_400_BAD_REQUEST)
            if not plan_description:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan description is required'},status=status.HTTP_400_BAD_REQUEST)
            if not price:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'price is required'},status=status.HTTP_400_BAD_REQUEST)
            if not plan_validity:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan validity is required'},status=status.HTTP_400_BAD_REQUEST)
            if not tyre_type:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'tyre type is required'},status=status.HTTP_400_BAD_REQUEST)
            if not package_type:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'package type is required'},status=status.HTTP_400_BAD_REQUEST)
            if not property_count:
                 return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'property count is required'},status=status.HTTP_400_BAD_REQUEST)

            # if not digital_rental_contract:
            # 	return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'digital rental contract is required'},status=status.HTTP_400_BAD_REQUEST)
            # if not notifications_stakeholders:
            # 	return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'notifications stakeholders is required'},status=status.HTTP_400_BAD_REQUEST)
            # if not visibility_among_ads:
            # 	return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'visibility among ads is required'},status=status.HTTP_400_BAD_REQUEST)
            # if not visibility_at_top:
            # 	return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'visibility at top is required'},status=status.HTTP_400_BAD_REQUEST)
            # if not information_of_local_area:
            # 	return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'information of local area is required'},status=status.HTTP_400_BAD_REQUEST)

            ifExist = SubscriptionPlan.objects.filter(planName=plan_name).exclude(id=plan_id)
            if ifExist:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Plan name already in use'},status=status.HTTP_400_BAD_REQUEST)

            planObj = SubscriptionPlan.objects.filter(id=plan_id).first()
            planObj.planName=plan_name
            planObj.planDurationDays = plan_validity
            planObj.price = price
            planObj.discount = discount
            planObj.package_type = package_type
            planObj.description = plan_description
            planObj.digital_rental_contract = digital_rental_contract
            planObj.notifications_stakeholders = notifications_stakeholders
            planObj.visibility_among_ads = visibility_among_ads
            planObj.visibility_at_top = visibility_at_top
            planObj.information_of_local_area = information_of_local_area
            planObj.tyre_type = tyre_type
            planObj.property_count = property_count
            planObj.save()
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Plan updated successfully'})
        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 changePlanStatus(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            plan_id = data.get('id')
            status_data = data.get('status')
            if not plan_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            # if not status_data:
            # 	return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'status is required'},status=status.HTTP_400_BAD_REQUEST)
            thePlan=SubscriptionPlan.objects.filter(id=plan_id).first()
            if thePlan:
                if status_data == True:
                    thePlan.status=True
                else:
                    thePlan.status=False
                thePlan.save()
            else:
                return Response({'status_code':status.HTTP_200_OK,'status_message':'Invalid plan id'})
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Success'})
        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 planListing(APIView):
    def get(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            plan_obj = SubscriptionPlan.objects.filter(end_date__isnull=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,
                    'package_type':plan.package_type,
                    'status':plan.status,
                    'tier_type':plan.tyre_type,
                    'discount':plan.discount,
                    "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,
                    "property_count":plan.property_count,
                }
                allData.append(all_data)
            return Response({'status_code':status.HTTP_200_OK,'status_message':'success','data':allData})
        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 getplanDetail(APIView):
    def get(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            plan_id = self.request.query_params.get('id')
            if not plan_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            plan_obj = SubscriptionPlan.objects.filter(id=plan_id).first()
            if not plan_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No plan found'},status=status.HTTP_400_BAD_REQUEST)
            alldata = {
                "id":plan_obj.id,
                   "plan_name":plan_obj.planName,
                "plan_validity":plan_obj.planDurationDays,
                "price":plan_obj.price,
                "plan_description":plan_obj.description,
                "digital_rental_contract":plan_obj.digital_rental_contract,
                "notifications_stakeholders":plan_obj.notifications_stakeholders,
                "visibility_among_ads":plan_obj.visibility_among_ads,
                "visibility_at_top":plan_obj.visibility_at_top,
                "information_of_local_area":plan_obj.information_of_local_area,
                'tier_type':plan_obj.tyre_type,
                'package_type':plan_obj.package_type,
                'discount':plan_obj.discount,
                "property_count":plan_obj.property_count,

            }
            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)


class purchaseSubscriptionPlan(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            customerObj=Customer.objects.filter(user=uid).first()
            subscription_id = data.get('subscription_id')
            payment_token = data.get('payment_token')
            price = data.get('price')
            if not subscription_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Subscription plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            if not payment_token:
                return Response({'message':'payment_token is required'},status=status.HTTP_400_BAD_REQUEST)
            sub_obj = SubscriptionPlan.objects.filter(id=subscription_id).first()
            today = datetime.date.today()
            if sub_obj.package_type == "monthly":
                expiry_date = int(sub_obj.planDurationDays) * 30
            else:
                expiry_date = int(sub_obj.planDurationDays) * 365

            new_date = today + datetime.timedelta(days=int(expiry_date))

            stripe.api_key =settings.STRIPE_SECRET_KEY

            charge = stripe.Charge.create(
                amount=int(price) * 100,
                currency='usd',
                source=payment_token,
                description='Purchase Subscription'
            )
            if charge:
                sub_data = CustomersSubscriptions.objects.filter(customer_id = customerObj,is_active=True).first()
                if sub_data:
                    sub_data.is_active = False
                    sub_data.save()
                new_data = CustomersSubscriptions.objects.create(customer=customerObj,plan=sub_obj,sub_start_date= today,sub_expiry_date=new_date,is_active=True)
                
                customerObj.has_subscription = True
                customerObj.save()
                ads = [BussinessForSale, HouseWantedForRent, InvestmentMyProject, InvestmentMyCompany, PropertyProject, SaleProperty, RentProperty]
                for ad in ads:
                    ad.objects.filter(customerId=customerObj, end_date__isnull=True).update(subscription_type=sub_obj.tyre_type)
                

                # Generate HTML content from template and render it using context data
                data = {'customer_name': str(customerObj.firstName) + str(customerObj.lastName),'customer_address':customerObj.address,'customer_number':customerObj.phoneNumber,'invoice_id':new_data.id,'invoice_date': datetime.datetime.now(),'amount': new_data.plan.price,'subscription_name':new_data.plan.planName,'description':new_data.plan.description}
                template = get_template('eipo-invoice.html')
                html = template.render(data)

                # Generate PDF content from HTML using xhtml2pdf library
                pdf_file = HttpResponse(content_type='application/pdf')
                pdf_file['Content-Disposition'] = 'attachment; filename="file.pdf"'
                
                pisa.CreatePDF(html, dest=pdf_file)
                # Create an EmailMessage object with the required details
                subject = 'Invoice'
                message = 'Your subscription is purchased successfully.Please find attached your invoice.'
                from_email = settings.EMAIL_HOST_USER
                recipient_list = ['test132@yopmail.com']

                email_message = EmailMessage(
                    subject=subject,
                    body=message,
                    from_email=from_email,
                    to=recipient_list,
                )
                # Attach the PDF file to the email message
                email_message.attach(filename='file.pdf', content=pdf_file.getvalue(), mimetype='application/pdf')

                # Send the email message using your SMTP server or other backend configured in Django settings.
                email_message.send()
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Subscription purchased 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 mySubscriptionPlan(APIView):
    def get(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            customerObj=Customer.objects.filter(user=uid).first()
            sub_obj = CustomersSubscriptions.objects.filter(customer=customerObj).order_by('-id')
            if not sub_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No active subscription found.'},status=status.HTTP_400_BAD_REQUEST)
            all_Data = []
            for i in sub_obj:
                all_data = {
                    'id': i.id,
                    'plan_id':i.plan.id,
                    'plan_name':i.plan.planName,
                    'sub_start_date':i.sub_start_date,
                    'sub_expiry_date':i.sub_expiry_date,
                    'is_active':i.is_active,
                    'plan_description':i.plan.description,
                    'price':i.plan.price,
                    'discount':i.plan.discount,
                    'package_type':i.plan.package_type,
                    'plan_validity':i.plan.planDurationDays,
                    'digital_rental_contract':i.plan.digital_rental_contract,
                    'notifications_stakeholders':i.plan.notifications_stakeholders,
                    'visibility_among_ads':i.plan.visibility_among_ads,
                    'visibility_at_top':i.plan.visibility_at_top,
                    'information_of_local_area':i.plan.information_of_local_area,
                    'status':i.plan.status,
                    "property_count":i.plan.property_count,

                }
                all_Data.append(all_data)
            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 mySubscriptionPlanDetails(APIView):
    def get(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            customerObj = Customer.objects.filter(user=uid).first()
            subscription_id = data.get('subscription_id')
            if not subscription_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Subscription Id is required'},status=status.HTTP_400_BAD_REQUEST)
            sub_obj = SubscriptionPlan.objects.filter(id= subscription_id).first()
            if not sub_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No subscription plan found'},status=status.HTTP_400_BAD_REQUEST)
            all_data = {
                'id':sub_obj.id,
                'plan_name' :sub_obj.planName,
                'plan_validity':sub_obj.planDurationDays,
                'price':sub_obj.price,
                'plan_description':sub_obj.description,
                'digital_rental_contract':sub_obj.digital_rental_contract,
                'notifications_stakeholders':sub_obj.notifications_stakeholders,
                'visibility_among_ads':sub_obj.visibility_among_ads,
                'visibility_at_top':sub_obj.visibility_at_top,
                'information_of_local_area':sub_obj.information_of_local_area,
                'status':sub_obj.status,
                'discount':sub_obj.discount,
                'package_type':sub_obj.package_type,
                "property_count":sub_obj.property_count,

            }
            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 subscriptionRenew(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            customerObj=Customer.objects.filter(user=uid).first()
            subscription_id = data.get('subscription_id')
            if not subscription_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Subscription Id is required'},status=status.HTTP_400_BAD_REQUEST)
            subscription_obj = SubscriptionPlan.objects.filter(id=subscription_id).first()
            if subscription_obj.planDurationDays == '30':
                today = datetime.date.today()
                new_date = today + datetime.timedelta(days=30)
            elif subscription_obj.planDurationDays == '60':
                today = datetime.date.today()
                new_date = today + datetime.timedelta(days=60)
            else:
                today = datetime.date.today()
                new_date = today + datetime.timedelta(days=90)
            if not subscription_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No subscription package found'},status=status.HTTP_400_BAD_REQUEST)
            cust_sub = CustomersSubscriptions.objects.filter(customer=customerObj ).first()
            cust_sub.plan = subscription_obj
            cust_sub.sub_start_date = today
            cust_sub.sub_expiry_date = new_date
            cust_sub.is_active = True
            cust_sub.save()
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Subscription renewed 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 deleteSubscription(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            customerObj=Customer.objects.filter(user=uid).first()
            customerObj.has_subscription = False
            customerObj.save()
            return Response({'status_code':status.HTTP_200_OK,'status_message':'success'})
        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 BuyBasicUserPlan(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            customerObj=Customer.objects.filter(user=uid).first()
            subscription_id = data.get('subscription_id')
            if not subscription_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Subscription plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            sub_data = CustomersSubscriptions.objects.filter(customer_id = customerObj,is_active=True).first()
            sub_obj = SubscriptionPlan.objects.filter(id=subscription_id).first()
            today = datetime.date.today()
            expiry_date = sub_obj.planDurationDays
            new_date = today + datetime.timedelta(days=int(expiry_date))
            if sub_data:
                sub_data.is_active = False
                sub_data.save()
            new_data = CustomersSubscriptions.objects.create(customer=customerObj,plan=sub_obj,sub_start_date= today,sub_expiry_date=new_date,is_active=True)
            
            customerObj.has_subscription = True
            customerObj.save()
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Subscription purchased 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)


paypalrestsdk.configure({
    "mode": "sandbox",  # Change to "live" for production
    "client_id": "Ac7hv0w6SpPe3CDXaIVxk1pEwRL8b558GstnRM5IC43_tk7h9TFCKLkobbUXc2udA8Vblhy8AoYUlDxN",
    "client_secret": "EJNK3-Ur7oHlCiT7kY5BdMSLT1pvLKjG3BO2cTDJIp-VgFIQKq3ZBvknnncjejbKGySb4p5DLkD__tCA",
})

from datetime import datetime

class MakePayment(APIView):
    def post(self, request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            customerObj=Customer.objects.filter(user=uid).first()
            # subscription_id = data.get('subscription_id')
            price = data.get('price')
            property_type= data.get('property_type')
            property_id= data.get('property_id')
            plan_id= data.get('plan_id')
            subscription_id= data.get('subscription_id')

            today = datetime.today()
            print(today)
            
            
            if plan_id:
                plan_obj = FeatureAddPricing.objects.filter(id = plan_id).first()
                payment = paypalrestsdk.Payment({
                    "intent": "sale",
                    "payer": {
                        "payment_method": "paypal",
                    },
                    "redirect_urls": {
                        "return_url":"https://reeipo-new.vipankumar.in/user/payment-success?subscription_id="+str(plan_id)+"&customer_id="+str(uid)+"&amount="+str(price),
                        "cancel_url": "https://reeipo-new.vipankumar.in/user/payment-failed?amount="+str(price),
                    },
                    "transactions": [
                        {
                            "amount": {
                                "total" :  int(price),  # Total amount in USD (replace with your desired amount)
                                "currency": "USD",
                            },
                            "description": "Payment for Subscription",
                        }
                    ],
                })
                try:
                    days_to_add = int(plan_obj.days)  
                except ValueError:
                    days_to_add = int(0)  
                last_date = datetime.today() + timedelta(days=days_to_add)  # Explicit use of datetime.date

                if payment.create():
                    new_data = CustomersFeatureAdsHistory.objects.create(customer=customerObj,plan=plan_obj,payment_date= today,property_type=property_type,property_id=property_id,is_active=True)
                    if property_type == "property_project":
                        property_obj = PropertyProject.objects.filter(id = property_id).first()
                        property_obj.is_featured = True
                        property_obj.feature_plan = plan_obj
                        property_obj.featured_end_date = last_date
                        property_obj.save()
                    elif property_type == "sale_property":
                        property_obj = SaleProperty.objects.filter(id = property_id).first()
                        property_obj.is_featured = True
                        property_obj.feature_plan = plan_obj
                        property_obj.featured_end_date = last_date
                        property_obj.save()
                    elif property_type == "rent_property":
                        property_obj = RentProperty.objects.filter(id = property_id).first()
                        property_obj.is_featured = True
                        property_obj.feature_plan = plan_obj
                        property_obj.featured_end_date = last_date
                        property_obj.save()
                    elif property_type == "house_for_rent":
                        property_obj = HouseWantedForRent.objects.filter(id = property_id).first()
                        property_obj.is_featured = True
                        property_obj.feature_plan = plan_obj
                        property_obj.featured_end_date = last_date
                        property_obj.save()
            
                    elif property_type == "company_seeking_equity":
                        property_obj = CompanySeekingEquity.objects.filter(id = property_id).first()
                        property_obj.is_featured = True
                        property_obj.feature_plan = plan_obj
                        property_obj.featured_end_date = last_date
                        property_obj.save()
            
                    elif property_type == "bussiness_for_sale":
                        property_obj = BussinessForSale.objects.filter(id = property_id).first()
                        property_obj.is_featured = True
                        property_obj.feature_plan = plan_obj
                        property_obj.featured_end_date = last_date
                        property_obj.save()
            
                    elif property_type == "property_developer":
                        property_obj = PropertyDevelopers.objects.filter(id = property_id).first()
                        property_obj.is_featured = True
                        property_obj.feature_plan = plan_obj
                        property_obj.featured_end_date = last_date
                        property_obj.save()
                    else:
                        pass

                    return Response({"payment_url": payment.links[1].href})
                else:
                    return Response({"error": "Payment creation failed"}, status=status.HTTP_400_BAD_REQUEST)

            elif subscription_id:
                plan_obj = SubscriptionPlan.objects.filter(id=subscription_id).first()
                
                payment = paypalrestsdk.Payment({
                    "intent": "sale",
                    "payer": {
                        "payment_method": "paypal",
                    },
                    "redirect_urls": {
                        "return_url":"https://reeipo-new.vipankumar.in/user/payment-success?subscription_id="+str(subscription_id)+"&customer_id="+str(uid)+"&amount="+str(price),
                        "cancel_url": "https://reeipo-new.vipankumar.in/user/payment-failed?amount="+str(price),
                    },
                    "transactions": [
                        {
                            "amount": {
                                "total" :  int(price),  # Total amount in USD (replace with your desired amount)
                                "currency": "USD",
                            },
                            "description": "Payment for Subscription",
                        }
                    ],
                })

                if payment.create():
                    return Response({"payment_url": payment.links[1].href})
                else:
                    return Response({"error": "Payment creation failed"}, status=status.HTTP_400_BAD_REQUEST)
        
        
        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 MakePayment(APIView):
# 	def post(self, request):
# 		try:
# 			try:
# 				uid = authenticated(request)
# 			except Exception as e:
# 				return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)
            
# 			data = request.data
# 			customerObj = Customer.objects.filter(user=uid).first()
# 			subscription_id = data.get('subscription_id')
# 			price = data.get('price')

# 			if not subscription_id:
# 				return Response({'status_code': status.HTTP_400_BAD_REQUEST, 'status_message': 'Subscription plan id is required'}, status=status.HTTP_400_BAD_REQUEST)

# 			sub_obj = SubscriptionPlan.objects.filter(id=subscription_id).first()
# 			if sub_obj.package_type == "monthly":
# 				duration = "MONTH"
# 			else:
# 				duration = "YEAR"


# 			# Create a billing plan
# 			billing_plan_attributes = {
# 				"name": "Recurring Payment Plan",
# 				"description": "Recurring payment plan for subscription",
# 				"type": "INFINITE",
# 				"payment_definitions": [{
# 					"name": "Regular Payment",
# 					"type": "REGULAR",
# 					"frequency": str(duration),
# 					"frequency_interval": str(sub_obj.planDurationDays),
# 					"amount": {
# 						"value": str(price),
# 						"currency": "USD"
# 					},
# 					"cycles": "0",
# 				}],
# 				"merchant_preferences": {
# 					"setup_fee": {
# 						"value": "0",
# 						"currency": "USD"
# 					},
# 					"cancel_url": "http://vipankumar.in:4016/",
# 					"return_url": f"http://54.225.243.254:9007/subscription-api/payment-success-paypal?subscription_id={subscription_id}&customer_id={uid}",
# 					"max_fail_attempts": "0",
# 					"auto_bill_amount": "YES",
# 					"initial_fail_amount_action": "CONTINUE"
# 				}
# 			}

# 			billing_plan = paypalrestsdk.BillingPlan(billing_plan_attributes)

# 			if billing_plan.create():
# 				return_url = f"http://54.225.243.254:9007/subscription-api/payment-success-paypal?subscription_id={subscription_id}&customer_id={uid}"

# 				# Activate the plan
# 				billing_plan.activate()

# 				# Create billing agreement
# 				billing_agreement = paypalrestsdk.BillingAgreement({
# 					"name": "Subscription Agreement",
# 					"description": "Subscription agreement for recurring payment",
# 					"start_date": "2023-11-01T00:00:00Z",
# 					"plan": {
# 						"id": billing_plan.id
# 					},
# 					"payer": {
# 						"payment_method": "paypal"
# 					},
# 					"override_merchant_preferences": {
# 						"return_url": return_url
# 					}
# 				})

# 				if billing_agreement.create():
# 					print(billing_agreement)
# 					approval_url = billing_agreement.links[0].href
# 					return Response({"approval_url": approval_url})
# 				else:

# 					return Response({"error": "Billing agreement creation failed"}, status=status.HTTP_400_BAD_REQUEST)
# 			else:
# 				return Response({"error": "Billing plan creation failed"}, status=status.HTTP_400_BAD_REQUEST)

# 		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 paymentSuccessPaypal(APIView):
    def get(self, request):
        try:
            customer_id = self.request.query_params.get('customer_id')
            customerObj=Customer.objects.filter(user=customer_id).first()

            subscription_id = self.request.query_params.get('subscription_id')
            if not subscription_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Subscription plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            sub_obj = SubscriptionPlan.objects.filter(id=subscription_id).first()

            today = datetime.date.today()
            if sub_obj.package_type == "monthly":
                expiry_date = int(sub_obj.planDurationDays) * 30
            else:
                expiry_date = int(sub_obj.planDurationDays) * 365
            new_date = today + datetime.timedelta(days=int(expiry_date))

            sub_data = CustomersSubscriptions.objects.filter(customer_id = customerObj,is_active=True).first()
            if sub_data:
                sub_data.is_active = False
                sub_data.save()
            new_data = CustomersSubscriptions.objects.create(customer=customerObj,plan=sub_obj,sub_start_date= today,sub_expiry_date=new_date,is_active=True)
            
            customerObj.has_subscription = True
            customerObj.save()
            ads = [BussinessForSale, HouseWantedForRent, InvestmentMyProject, InvestmentMyCompany, PropertyProject, SaleProperty, RentProperty]
            for ad in ads:
                ad.objects.filter(customerId=customerObj, end_date__isnull=True).update(subscription_type=sub_obj.tyre_type)
            data = {'customer_name': str(customerObj.firstName) + str(customerObj.lastName),'customer_address':customerObj.address,'customer_number':customerObj.phoneNumber,'invoice_id':new_data.id,'invoice_date': datetime.datetime.now(),'amount': new_data.plan.price,'subscription_name':new_data.plan.planName,'description':new_data.plan.description}
            template = get_template('eipo-invoice.html')
            html = template.render(data)
            pdf_file = HttpResponse(content_type='application/pdf')
            pdf_file['Content-Disposition'] = 'attachment; filename="file.pdf"'
            
            pisa.CreatePDF(html, dest=pdf_file)
            subject = 'Invoice'
            message = 'Your subscription is purchased successfully.Please find attached your invoice.'
            from_email = settings.EMAIL_HOST_USER
            recipient_list = ['test132@yopmail.com']

            email_message = EmailMessage(
                subject=subject,
                body=message,
                from_email=from_email,
                to=recipient_list,
            )
            email_message.attach(filename='file.pdf', content=pdf_file.getvalue(), mimetype='application/pdf')
            email_message.send()
            return redirect ('https://reeipo-new.vipankumar.in/user?paymentpalsuccess=true')


        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 makePaymentVips(APIView):
    def post(self, request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            customerObj=Customer.objects.filter(user=uid).first()
            subscription_id = data.get('subscription_id')
            if not subscription_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Subscription plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            sub_obj = SubscriptionPlan.objects.filter(id=subscription_id).first()


            today = datetime.date.today()
            expiry_date = sub_obj.planDurationDays
            new_date = today + datetime.timedelta(days=int(expiry_date))


            sub_data = CustomersSubscriptions.objects.filter(customer_id = customerObj,is_active=True).first()
            if sub_data:
                sub_data.is_active = False
                sub_data.save()
            new_data = CustomersSubscriptions.objects.create(customer=customerObj,plan=sub_obj,sub_start_date= today,sub_expiry_date=new_date,is_active=True)
            

            customerObj.has_subscription = True
            customerObj.save()
            ads = [BussinessForSale, HouseWantedForRent, InvestmentMyProject, InvestmentMyCompany, PropertyProject, SaleProperty, RentProperty]
            for ad in ads:
                ad.objects.filter(customerId=customerObj, end_date__isnull=True).update(subscription_type=sub_obj.tyre_type)

            data = {'customer_name': str(customerObj.firstName) + str(customerObj.lastName),'customer_address':customerObj.address,'customer_number':customerObj.phoneNumber,'invoice_id':new_data.id,'invoice_date': datetime.datetime.now(),'amount': new_data.plan.price,'subscription_name':new_data.plan.planName,'description':new_data.plan.description}
            template = get_template('eipo-invoice.html')
            html = template.render(data)
            pdf_file = HttpResponse(content_type='application/pdf')
            pdf_file['Content-Disposition'] = 'attachment; filename="file.pdf"'
            
            pisa.CreatePDF(html, dest=pdf_file)
            subject = 'Invoice'
            message = 'Your subscription is purchased successfully.Please find attached your invoice.'
            from_email = settings.EMAIL_HOST_USER
            recipient_list = ['test132@yopmail.com']

            email_message = EmailMessage(
                subject=subject,
                body=message,
                from_email=from_email,
                to=recipient_list,
            )
            email_message.attach(filename='file.pdf', content=pdf_file.getvalue(), mimetype='application/pdf')
            email_message.send()
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Subscription purchased 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 InitatePayment(APIView):
    def post(self, request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            customerObj = Customer.objects.filter(user=uid).first()
            subscription_id = request.data.get('subscription_id')
            if not subscription_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Subscription plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            sub_obj = SubscriptionPlan.objects.filter(id=subscription_id).first()
            amount = sub_obj.price

            order_id = data.get('orderId')

            vipps_client_id = 'YOUR_CLIENT_ID'
            vipps_client_secret = 'YOUR_CLIENT_SECRET'

            vipps_payment_request = {
                "merchantInfo": {
                    "merchantSerialNumber": vipps_client_id
                },
                "customerInfo": {
                    "mobileNumber": "12345678"  # Customer's mobile number
                },
                "transaction": {
                    "orderId": order_id,
                    "amount": amount,
                    "transactionText": "Payment description"
                }
            }
            
            vipps_response = requests.post('https://api.vipps.no/paymentapi/v2/payment', json=vipps_payment_request, auth=(vipps_client_id, vipps_client_secret))

            vipps_data = vipps_response.json()
            vipps_url = vipps_data.get('url')

            return Response({'status_code':status.HTTP_200_OK,'data':vipps_url})
    
        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 addAgencyPlan(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            plan_name = data.get('plan_name')
            plan_description= data.get('plan_description')
            price = data.get('price')
            plan_validity = data.get('plan_validity')
            tyre_type = data.get('tier_type')

            if not plan_name:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan name is required'},status=status.HTTP_400_BAD_REQUEST)
            if not plan_description:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan description is required'},status=status.HTTP_400_BAD_REQUEST)
            if not price:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'price is required'},status=status.HTTP_400_BAD_REQUEST)
            if not plan_validity:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan validity is required'},status=status.HTTP_400_BAD_REQUEST)
            if not tyre_type:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'tyre type is required'},status=status.HTTP_400_BAD_REQUEST)

            
            ifExist = AgencySubscriptionPlan.objects.filter(planName=plan_name).first()
            if ifExist:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Plan name already in use'},status=status.HTTP_400_BAD_REQUEST)

            planObj = AgencySubscriptionPlan.objects.create(planName=plan_name)
            planObj.planDurationDays = plan_validity
            planObj.price = price
            planObj.description = plan_description
            planObj.tyre_type = tyre_type
            planObj.save()
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Plan created successfully'})
        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 editAgencyPlan(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            plan_id = data.get('id')
            plan_name = data.get('plan_name')
            plan_description= data.get('plan_description')
            price = data.get('price')
            plan_validity = data.get('plan_validity')
            tyre_type = data.get('tier_type')
            property_count = data.get('property_count')
            
            if not plan_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            if not plan_name:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan name is required'},status=status.HTTP_400_BAD_REQUEST)
            if not plan_description:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan description is required'},status=status.HTTP_400_BAD_REQUEST)
            if not price:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'price is required'},status=status.HTTP_400_BAD_REQUEST)
            if not plan_validity:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan validity is required'},status=status.HTTP_400_BAD_REQUEST)
            if not tyre_type:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'tyre type is required'},status=status.HTTP_400_BAD_REQUEST)
            if not property_count:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'property count is required'},status=status.HTTP_400_BAD_REQUEST)


            ifExist = AgencySubscriptionPlan.objects.filter(planName=plan_name).exclude(id=plan_id)
            if ifExist:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Plan name already in use'},status=status.HTTP_400_BAD_REQUEST)

            planObj = AgencySubscriptionPlan.objects.filter(id=plan_id).first()
            if not planObj:
                return Response({
                    'status_code': status.HTTP_404_NOT_FOUND,
                    'status_message': 'Plan not found'
                }, status=status.HTTP_404_NOT_FOUND)
            planObj.planName=plan_name
            planObj.planDurationDays = plan_validity
            planObj.price = price
            planObj.description = plan_description
            planObj.tyre_type = tyre_type
            planObj.property_number = property_count
            planObj.save()
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Plan updated successfully'})
        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 agencyChangePlanStatus(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            plan_id = data.get('id')
            status_data = data.get('status')
            if not plan_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            thePlan=AgencySubscriptionPlan.objects.filter(id=plan_id).first()
            if thePlan:
                if status_data == True:
                    thePlan.status=True
                else:
                    thePlan.status=False
                thePlan.save()
            else:
                return Response({'status_code':status.HTTP_200_OK,'status_message':'Invalid plan id'})
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Success'})
        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 agencyPlanListing(APIView):
    def get(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            plan_obj = AgencySubscriptionPlan.objects.filter(end_date__isnull=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,
                    'status':plan.status,
                    'tier_type':plan.tyre_type,
                    'property_count':plan.property_number
                    

                }
                allData.append(all_data)
            return Response({'status_code':status.HTTP_200_OK,'status_message':'success','data':allData})
        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 agencyPlanDetails(APIView):
    def get(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            plan_id = self.request.query_params.get('id')
            if not plan_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            plan_obj = AgencySubscriptionPlan.objects.filter(id=plan_id).first()
            if not plan_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No plan found'},status=status.HTTP_400_BAD_REQUEST)
            alldata = {
                "id":plan_obj.id,
                "plan_name":plan_obj.planName,
                "plan_validity":plan_obj.planDurationDays,
                "price":plan_obj.price,
                "plan_description":plan_obj.description,
                'tier_type':plan_obj.tyre_type,
                'property_count':plan_obj.property_number
            }
            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)

class purchaseAgencySubscriptionPlan(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            customerObj=Customer.objects.filter(user=uid).first()
            subscription_id = data.get('subscription_id')
            payment_token = data.get('payment_token')
            if not subscription_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Subscription plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            if not payment_token:
                return Response({'message':'payment_token is required'},status=status.HTTP_400_BAD_REQUEST)
            sub_obj = AgencySubscriptionPlan.objects.filter(id=subscription_id).first()
            today = datetime.date.today()
            expiry_date = sub_obj.planDurationDays
            new_date = today + datetime.timedelta(days=int(expiry_date))

            stripe.api_key =settings.STRIPE_SECRET_KEY

            charge = stripe.Charge.create(
                amount=int(sub_obj.price) * 100,
                currency='usd',
                source=payment_token,
                description='Purchase Subscription'
            )
            if charge:
                sub_data = AgencySubscriptions.objects.filter(customer_id = customerObj,is_active=True).first()
                if sub_data:
                    sub_data.is_active = False
                    sub_data.save()
                new_data = AgencySubscriptions.objects.create(customer=customerObj,plan=sub_obj,sub_start_date= today,sub_expiry_date=new_date,is_active=True)
                
                customerObj.has_subscription = True
                customerObj.can_add_property_count = sub_obj.can_add_property_count
                customerObj.save()

                # ads = [BussinessForSale, HouseWantedForRent, InvestmentMyProject, InvestmentMyCompany, PropertyProject, SaleProperty, RentProperty]
                # for ad in ads:
                # 	ad.objects.filter(customerId=customerObj, end_date__isnull=True).update(subscription_type=sub_obj.tyre_type)

                data = {'customer_name': str(customerObj.firstName) + str(customerObj.lastName),'customer_address':customerObj.address,'customer_number':customerObj.phoneNumber,'invoice_id':new_data.id,'invoice_date': datetime.datetime.now(),'amount': new_data.plan.price,'subscription_name':new_data.plan.planName,'description':new_data.plan.description}
                template = get_template('eipo-agency-invoice.html')
                html = template.render(data)

                pdf_file = HttpResponse(content_type='application/pdf')
                pdf_file['Content-Disposition'] = 'attachment; filename="file.pdf"'
                
                pisa.CreatePDF(html, dest=pdf_file)
                subject = 'Invoice'
                message = 'Your subscription is purchased successfully.Please find attached your invoice.'
                from_email = settings.EMAIL_HOST_USER
                recipient_list = ['test132@yopmail.com']

                email_message = EmailMessage(
                    subject=subject,
                    body=message,
                    from_email=from_email,
                    to=recipient_list,
                )
                email_message.attach(filename='file.pdf', content=pdf_file.getvalue(), mimetype='application/pdf')
                email_message.send()
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Subscription purchased 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 agencyMySubscriptionPlan(APIView):
    def get(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            customerObj=Customer.objects.filter(user=uid).first()
            sub_obj = AgencySubscriptions.objects.filter(customer=customerObj,is_active="True").order_by('-id')
            if not sub_obj:
                return Response({'status_code':status.HTTP_200_OK,'status_message':'No active subscription found.','data':[]},status=status.HTTP_200_OK)
            all_Data = []
            for i in sub_obj:
                all_data = {
                    'id': i.id,
                    'plan_id':i.plan.id,
                    'plan_name':i.plan.planName,
                    'sub_start_date':i.sub_start_date,
                    'sub_expiry_date':i.sub_expiry_date,
                    'is_active':i.is_active,
                    'plan_description':i.plan.description,
                    'price':i.plan.price,
                    'plan_validity':i.plan.planDurationDays,
                    'status':i.plan.status
                }
                all_Data.append(all_data)
            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 agencyMySubscriptionPlanDetails(APIView):
    def get(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            customerObj = Customer.objects.filter(user=uid).first()
            subscription_id = data.get('subscription_id')
            if not subscription_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Subscription Id is required'},status=status.HTTP_400_BAD_REQUEST)
            sub_obj = AgencySubscriptions.objects.filter(id= subscription_id).first()
            if not sub_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No subscription plan found'},status=status.HTTP_400_BAD_REQUEST)
            all_data = {
                'id':sub_obj.id,
                'plan_name' :sub_obj.planName,
                'plan_validity':sub_obj.planDurationDays,
                'price':sub_obj.price,
                'plan_description':sub_obj.description,
                'status':sub_obj.status
            }
            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 agencySubscriptionRenew(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            customerObj=Customer.objects.filter(user=uid).first()
            subscription_id = data.get('subscription_id')
            if not subscription_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Subscription Id is required'},status=status.HTTP_400_BAD_REQUEST)
            subscription_obj = AgencySubscriptionPlan.objects.filter(id=subscription_id).first()
            if subscription_obj.planDurationDays == '30':
                today = datetime.date.today()
                new_date = today + datetime.timedelta(days=30)
            elif subscription_obj.planDurationDays == '60':
                today = datetime.date.today()
                new_date = today + datetime.timedelta(days=60)
            else:
                today = datetime.date.today()
                new_date = today + datetime.timedelta(days=90)
            if not subscription_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No subscription package found'},status=status.HTTP_400_BAD_REQUEST)
            cust_sub = AgencySubscriptions.objects.filter(customer=customerObj ).first()
            cust_sub.plan = subscription_obj
            cust_sub.sub_start_date = today
            cust_sub.sub_expiry_date = new_date
            cust_sub.is_active = True
            cust_sub.save()
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Subscription renewed 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 agencyDeleteSubscription(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            customerObj=Customer.objects.filter(user=uid).first()
            customerObj.has_subscription = False
            customerObj.save()
            return Response({'status_code':status.HTTP_200_OK,'status_message':'success'})
        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 BuyBasicAgencyPlan(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            customerObj=Customer.objects.filter(user=uid).first()
            subscription_id = data.get('subscription_id')
            if not subscription_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Subscription plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            sub_data = AgencySubscriptions.objects.filter(customer_id = customerObj,is_active=True).first()
            sub_obj = AgencySubscriptionPlan.objects.filter(id=subscription_id).first()
            today = datetime.date.today()
            expiry_date = sub_obj.planDurationDays
            new_date = today + datetime.timedelta(days=int(expiry_date))
            if sub_data:
                sub_data.is_active = False
                sub_data.save()
            new_data = AgencySubscriptions.objects.create(customer=customerObj,plan=sub_obj,sub_start_date= today,sub_expiry_date=new_date,is_active=True)
            
            customerObj.has_subscription = True
            customerObj.save()
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Subscription purchased 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 agencyMakePayment(APIView):
    def post(self, request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            customerObj=Customer.objects.filter(user=uid).first()
            subscription_id = data.get('subscription_id')
            if not subscription_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Subscription plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            sub_obj = AgencySubscriptionPlan.objects.filter(id=subscription_id).first()
            payment = paypalrestsdk.Payment({
                "intent": "sale",
                "payer": {
                    "payment_method": "paypal",
                },
                "redirect_urls": {
                    "return_url":"http://54.225.243.254:9007/subscription-api/agency-payment-success-paypal?subscription_id="+str(subscription_id)+"&customer_id="+str(uid),
                    "cancel_url": "http://vipankumar.in:4016/",
                },
                "transactions": [
                    {
                        "amount": {
                            "total": sub_obj.price,  
                            "currency": "USD",
                        },
                        "description": "Payment for Subscription",
                    }
                ],
            })

            if payment.create():
                return Response({"payment_url": payment.links[1].href})
            else:
                return Response({"error": "Payment creation failed"}, status=status.HTTP_400_BAD_REQUEST)

        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 agencyPaymentSuccessPaypal(APIView):
    def get(self, request):
        try:
            customer_id = self.request.query_params.get('customer_id')
            customerObj=Customer.objects.filter(user=customer_id).first()

            subscription_id = self.request.query_params.get('subscription_id')
            if not subscription_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Subscription plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            sub_obj = AgencySubscriptionPlan.objects.filter(id=subscription_id).first()

            today = datetime.date.today()
            expiry_date = sub_obj.planDurationDays
            new_date = today + datetime.timedelta(days=int(expiry_date))

            sub_data = AgencySubscriptions.objects.filter(customer_id = customerObj,is_active=True).first()
            if sub_data:
                sub_data.is_active = False
                sub_data.save()
            new_data = AgencySubscriptions.objects.create(customer=customerObj,plan=sub_obj,sub_start_date= today,sub_expiry_date=new_date,is_active=True)
            
            customerObj.has_subscription = True
            customerObj.save()
            data = {'customer_name': str(customerObj.firstName) + str(customerObj.lastName),'customer_address':customerObj.address,'customer_number':customerObj.phoneNumber,'invoice_id':new_data.id,'invoice_date': datetime.datetime.now(),'amount': new_data.plan.price,'subscription_name':new_data.plan.planName,'description':new_data.plan.description}
            template = get_template('eipo-invoice.html')
            html = template.render(data)
            pdf_file = HttpResponse(content_type='application/pdf')
            pdf_file['Content-Disposition'] = 'attachment; filename="file.pdf"'
            
            pisa.CreatePDF(html, dest=pdf_file)
            subject = 'Invoice'
            message = 'Your subscription is purchased successfully.Please find attached your invoice.'
            from_email = settings.EMAIL_HOST_USER
            recipient_list = ['test132@yopmail.com']

            email_message = EmailMessage(
                subject=subject,
                body=message,
                from_email=from_email,
                to=recipient_list,
            )
            email_message.attach(filename='file.pdf', content=pdf_file.getvalue(), mimetype='application/pdf')
            email_message.send()
            return redirect ('http://vipankumar.in:4016?paymentpalsuccess=true')


        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 agencyInitatePayment(APIView):
    def post(self, request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            customerObj = Customer.objects.filter(user=uid).first()
            subscription_id = request.data.get('subscription_id')
            if not subscription_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Subscription plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            sub_obj = AgencySubscriptionPlan.objects.filter(id=subscription_id).first()
            amount = sub_obj.price

            order_id = data.get('orderId')

            vipps_client_id = 'YOUR_CLIENT_ID'
            vipps_client_secret = 'YOUR_CLIENT_SECRET'

            vipps_payment_request = {
                "merchantInfo": {
                    "merchantSerialNumber": vipps_client_id
                },
                "customerInfo": {
                    "mobileNumber": "12345678" 
                },
                "transaction": {
                    "orderId": order_id,
                    "amount": amount,
                    "transactionText": "Payment description"
                }
            }
            
            vipps_response = requests.post('https://api.vipps.no/paymentapi/v2/payment', json=vipps_payment_request, auth=(vipps_client_id, vipps_client_secret))

            vipps_data = vipps_response.json()
            vipps_url = vipps_data.get('url')

            return Response({'status_code':status.HTTP_200_OK,'data':vipps_url})
    
        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 addLawyerPlan(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            plan_name = data.get('plan_name')
            plan_description= data.get('plan_description')
            price = data.get('price')
            plan_validity = data.get('plan_validity')
            total_contract = data.get('total_contract')

            if not plan_name:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan name is required'},status=status.HTTP_400_BAD_REQUEST)
            if not plan_description:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan description is required'},status=status.HTTP_400_BAD_REQUEST)
            if not price:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'price is required'},status=status.HTTP_400_BAD_REQUEST)
            if not plan_validity:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan validity is required'},status=status.HTTP_400_BAD_REQUEST)
            if not total_contract:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'total contract is required'},status=status.HTTP_400_BAD_REQUEST)
            
            ifExist = LawyerSubscriptionPlan.objects.filter(planName=plan_name).first()
            if ifExist:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Plan name already in use'},status=status.HTTP_400_BAD_REQUEST)

            planObj = LawyerSubscriptionPlan.objects.create(planName=plan_name)
            planObj.planDurationDays = plan_validity
            planObj.price = price
            planObj.description = plan_description
            planObj.total_contract = total_contract
            planObj.save()
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Plan created successfully'})
        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 editLawyerPlan(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            plan_id = data.get('id')
            plan_name = data.get('plan_name')
            plan_description= data.get('plan_description')
            price = data.get('price')
            plan_validity = data.get('plan_validity')
            total_contract = data.get('total_contract')
            
            if not plan_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            if not plan_name:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan name is required'},status=status.HTTP_400_BAD_REQUEST)
            if not plan_description:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan description is required'},status=status.HTTP_400_BAD_REQUEST)
            if not price:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'price is required'},status=status.HTTP_400_BAD_REQUEST)
            if not plan_validity:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan validity is required'},status=status.HTTP_400_BAD_REQUEST)
            if not total_contract:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'total contract is required'},status=status.HTTP_400_BAD_REQUEST)

            ifExist = LawyerSubscriptionPlan.objects.filter(planName=plan_name).exclude(id=plan_id)
            if ifExist:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Plan name already in use'},status=status.HTTP_400_BAD_REQUEST)

            planObj = LawyerSubscriptionPlan.objects.filter(id=plan_id).first()
            planObj.planName=plan_name
            planObj.planDurationDays = plan_validity
            planObj.price = price
            planObj.description = plan_description
            planObj.total_contract = total_contract
            planObj.save()
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Plan updated successfully'})
        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 lawyerChangePlanStatus(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            plan_id = data.get('id')
            status_data = data.get('status')
            if not plan_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            thePlan=LawyerSubscriptionPlan.objects.filter(id=plan_id).first()
            if thePlan:
                if status_data == True:
                    thePlan.status=True
                else:
                    thePlan.status=False
                thePlan.save()
            else:
                return Response({'status_code':status.HTTP_200_OK,'status_message':'Invalid plan id'})
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Success'})
        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 lawyerPlanListing(APIView):
    def get(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            plan_obj = LawyerSubscriptionPlan.objects.filter(end_date__isnull=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,
                    'status':plan.status,
                    'total_contract':plan.total_contract
                }
                allData.append(all_data)
            return Response({'status_code':status.HTTP_200_OK,'status_message':'success','data':allData})
        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 lawyerPlanDetails(APIView):
    def get(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            plan_id = self.request.query_params.get('id')
            if not plan_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            plan_obj = LawyerSubscriptionPlan.objects.filter(id=plan_id).first()
            if not plan_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No plan found'},status=status.HTTP_400_BAD_REQUEST)
            alldata = {
                "id":plan_obj.id,
                   "plan_name":plan_obj.planName,
                "plan_validity":plan_obj.planDurationDays,
                "price":plan_obj.price,
                "plan_description":plan_obj.description,
                'total_contract':plan_obj.total_contract
            }
            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)

import datetime

class purchaselawyerSubscriptionPlan(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            customerObj=Customer.objects.filter(user=uid).first()
            subscription_id = data.get('subscription_id')
            payment_token = data.get('payment_token')
            if not subscription_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Subscription plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            if not payment_token:
                return Response({'message':'payment_token is required'},status=status.HTTP_400_BAD_REQUEST)
            sub_obj = LawyerSubscriptionPlan.objects.filter(id=subscription_id).first()
            today       = datetime.datetime.today()         # use datetime.datetime
            expiry_days = int(sub_obj.planDurationDays)
            new_date    = today + datetime.timedelta(days=expiry_days)

            stripe.api_key =settings.STRIPE_SECRET_KEY

            charge = stripe.Charge.create(
                amount=int(sub_obj.price) * 100,
                currency='usd',
                source=payment_token,
                description='Purchase Subscription'
            )
            if charge:
                sub_data = LawyerSubscriptions.objects.filter(customer_id = customerObj,is_active=True).first()
                if sub_data:
                    sub_data.is_active = False
                    sub_data.save()
                new_data = LawyerSubscriptions.objects.create(customer=customerObj,plan=sub_obj,sub_start_date= today,sub_expiry_date=new_date,is_active=True)
                
                customerObj.has_subscription = True
                customerObj.total_hire_count = sub_data.total_hiring_requests
                customerObj.save()
                data = {'customer_name': str(customerObj.firstName) + str(customerObj.lastName),'customer_address':customerObj.address,'customer_number':customerObj.phoneNumber,'invoice_id':new_data.id,'invoice_date': datetime.datetime.now(),'amount': new_data.plan.price,'subscription_name':new_data.plan.planName,'description':new_data.plan.description}
                template = get_template('eipo-agency-invoice.html')
                html = template.render(data)

                pdf_file = HttpResponse(content_type='application/pdf')
                pdf_file['Content-Disposition'] = 'attachment; filename="file.pdf"'
                
                pisa.CreatePDF(html, dest=pdf_file)
                subject = 'Invoice'
                message = 'Your subscription is purchased successfully.Please find attached your invoice.'
                from_email = settings.EMAIL_HOST_USER
                recipient_list = ['test132@yopmail.com']

                email_message = EmailMessage(
                    subject=subject,
                    body=message,
                    from_email=from_email,
                    to=recipient_list,
                )
                email_message.attach(filename='file.pdf', content=pdf_file.getvalue(), mimetype='application/pdf')
                email_message.send()
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Subscription purchased 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 lawyerMySubscriptionPlan(APIView):
    def get(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            customerObj=Customer.objects.filter(user=uid).first()
            sub_obj = LawyerSubscriptions.objects.filter(customer=customerObj).order_by('-id')
            if not sub_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No active subscription found.'},status=status.HTTP_400_BAD_REQUEST)
            all_Data = []
            for i in sub_obj:
                all_data = {
                    'id': i.id,
                    'plan_id':i.plan.id,
                    'plan_name':i.plan.planName,
                    'sub_start_date':i.sub_start_date,
                    'sub_expiry_date':i.sub_expiry_date,
                    'is_active':i.is_active,
                    'plan_description':i.plan.description,
                    'price':i.plan.price,
                    'plan_validity':i.plan.planDurationDays,
                    'status':i.plan.status
                }
                all_Data.append(all_data)
            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 lawyerMySubscriptionPlanDetails(APIView):
    def get(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            plan_id = self.request.query_params.get('id')
            if not plan_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            plan_obj = LawyerSubscriptions.objects.filter(id=plan_id).first()
            if not plan_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No plan found'},status=status.HTTP_400_BAD_REQUEST)
            alldata = {
                "id":plan_obj.id,
                   "plan_name":plan_obj.planName,
                "plan_validity":plan_obj.planDurationDays,
                "price":plan_obj.price,
                "plan_description":plan_obj.description,
                'total_contract':plan_obj.total_contract
            }
            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)


class lawyerSubscriptionRenew(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            customerObj=Customer.objects.filter(user=uid).first()
            subscription_id = data.get('subscription_id')
            if not subscription_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Subscription Id is required'},status=status.HTTP_400_BAD_REQUEST)
            subscription_obj = LawyerSubscriptionPlan.objects.filter(id=subscription_id).first()
            if subscription_obj.planDurationDays == '30':
                today = datetime.date.today()
                new_date = today + datetime.timedelta(days=30)
            elif subscription_obj.planDurationDays == '60':
                today = datetime.date.today()
                new_date = today + datetime.timedelta(days=60)
            else:
                today = datetime.date.today()
                new_date = today + datetime.timedelta(days=90)
            if not subscription_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No subscription package found'},status=status.HTTP_400_BAD_REQUEST)
            cust_sub = LawyerSubscriptions.objects.filter(customer=customerObj ).first()
            cust_sub.plan = subscription_obj
            cust_sub.sub_start_date = today
            cust_sub.sub_expiry_date = new_date
            cust_sub.is_active = True
            cust_sub.save()
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Subscription renewed 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 lawyerDeleteSubscription(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            customerObj=Customer.objects.filter(user=uid).first()
            customerObj.has_subscription = False
            customerObj.save()
            return Response({'status_code':status.HTTP_200_OK,'status_message':'success'})
        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 BuyBasicLawyerPlan(APIView):
    def post(self,request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            customerObj=Customer.objects.filter(user=uid).first()
            subscription_id = data.get('subscription_id')
            if not subscription_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Subscription plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            sub_data = LawyerSubscriptions.objects.filter(customer_id = customerObj,is_active=True).first()
            sub_obj = LawyerSubscriptionPlan.objects.filter(id=subscription_id).first()
            today = datetime.date.today()
            expiry_date = sub_obj.planDurationDays
            new_date = today + datetime.timedelta(days=int(expiry_date))
            if sub_data:
                sub_data.is_active = False
                sub_data.save()
            new_data = LawyerSubscriptions.objects.create(customer=customerObj,plan=sub_obj,sub_start_date= today,sub_expiry_date=new_date,is_active=True)
            
            customerObj.has_subscription = True
            customerObj.save()
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Subscription purchased 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 lawyerMakePayment(APIView):
    def post(self, request):
        try:
            try:
                uid = authenticated(request)
            except Exception as e:
                return Response({'message':str(e)},status=status.HTTP_401_UNAUTHORIZED)
            data = request.data
            customerObj=Customer.objects.filter(user=uid).first()
            subscription_id = data.get('subscription_id')
            if not subscription_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Subscription plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            sub_obj = LawyerSubscriptionPlan.objects.filter(id=subscription_id).first()
            payment = paypalrestsdk.Payment({
                "intent": "sale",
                "payer": {
                    "payment_method": "paypal",
                },
                "redirect_urls": {
                    "return_url":"http://54.225.243.254:9007/subscription-api/lawyer-payment-success-paypal?subscription_id="+str(subscription_id)+"&customer_id="+str(uid),
                    "cancel_url": "http://vipankumar.in:4016/",
                },
                "transactions": [
                    {
                        "amount": {
                            "total": sub_obj.price,  # Total amount in USD (replace with your desired amount)
                            "currency": "USD",
                        },
                        "description": "Payment for Subscription",
                    }
                ],
            })

            if payment.create():
                return Response({"payment_url": payment.links[1].href})
            else:
                return Response({"error": "Payment creation failed"}, status=status.HTTP_400_BAD_REQUEST)

        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 lawyerPaymentSuccessPaypal(APIView):
    def get(self, request):
        try:
            customer_id = self.request.query_params.get('customer_id')
            customerObj=Customer.objects.filter(user=customer_id).first()

            subscription_id = self.request.query_params.get('subscription_id')
            if not subscription_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Subscription plan id is required'},status=status.HTTP_400_BAD_REQUEST)
            sub_obj = LawyerSubscriptionPlan.objects.filter(id=subscription_id).first()

            today = datetime.date.today()
            expiry_date = sub_obj.planDurationDays
            new_date = today + datetime.timedelta(days=int(expiry_date))

            sub_data = LawyerSubscriptions.objects.filter(customer_id = customerObj,is_active=True).first()
            if sub_data:
                sub_data.is_active = False
                sub_data.save()
            new_data = LawyerSubscriptions.objects.create(customer=customerObj,plan=sub_obj,sub_start_date= today,sub_expiry_date=new_date,is_active=True)
            
            customerObj.has_subscription = True
            customerObj.save()
            data = {'customer_name': str(customerObj.firstName) + str(customerObj.lastName),'customer_address':customerObj.address,'customer_number':customerObj.phoneNumber,'invoice_id':new_data.id,'invoice_date': datetime.datetime.now(),'amount': new_data.plan.price,'subscription_name':new_data.plan.planName,'description':new_data.plan.description}
            template = get_template('eipo-invoice.html')
            html = template.render(data)
            pdf_file = HttpResponse(content_type='application/pdf')
            pdf_file['Content-Disposition'] = 'attachment; filename="file.pdf"'
            
            pisa.CreatePDF(html, dest=pdf_file)
            subject = 'Invoice'
            message = 'Your subscription is purchased successfully.Please find attached your invoice.'
            from_email = settings.EMAIL_HOST_USER
            recipient_list = ['test132@yopmail.com']

            email_message = EmailMessage(
                subject=subject,
                body=message,
                from_email=from_email,
                to=recipient_list,
            )
            email_message.attach(filename='file.pdf', content=pdf_file.getvalue(), mimetype='application/pdf')
            email_message.send()
            return redirect ('http://vipankumar.in:4016?paymentpalsuccess=true')
        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)