from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from panel_apis.models import *

import random
from datetime import datetime,timedelta,date
from django.conf import settings
from passlib.hash import django_pbkdf2_sha256 as handler
import json
from admin_panel.models import *
from rest_framework.authentication import get_authorization_header
import jwt
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.backends import TokenBackend
from django.core.mail import EmailMultiAlternatives
from rest_framework import exceptions
from django.shortcuts import render, redirect
from django.core import mail
from django.template.loader import render_to_string
import math, random, pytz, string
from django.contrib import messages
from admin_panel.functions import *
from django.utils.timesince import timesince
from django.db.models import Max
from django.db.models import Q
import ast
import stripe
import openai
from newsapi import NewsApiClient
import requests
import yfinance as yf
import pandas as pd
import requests
from bs4 import BeautifulSoup
import csv
import pandas as pd
from . import forms





# Create your views here.

class UploadImages(APIView):
	def post(self, request):
		try:
			data = request.data
			images = data.getlist('images')
			image_urls = []
			for image in images:
				image_path = uploadTheImages(image)
				image_urls.append(image_path)
			return Response({'status_code':status.HTTP_200_OK,'status_message':'Success','data':image_urls})
		except Exception as e:
			return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class getPrivacyPolicy(APIView):
    def get(self,request):
        try:
            page_type_param =  self.request.query_params.get('page_type_param')
            if page_type_param == 'Privacy':
                data_obj = ContentPages.objects.filter(page_type='Privacy').first()
            else:
                data_obj = ContentPages.objects.filter(page_type='Terms').first()
            if not data_obj:
                all_data={}
            else:
                all_data = {
                    'id':data_obj.id,
                    'title':data_obj.title,
                    'content':data_obj.content
                }
            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 getTermsConditions(APIView):
    def get(self,request):
        try:
            terms_obj = ContentPages.objects.filter(page_type='Terms').first()
            if not terms_obj:
                all_data={}
            else:
                all_data = {
                    'id':terms_obj.id,
                    'title':terms_obj.title,
                    'content':terms_obj.content
                }
            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 faqListing(APIView):
    def get(self,request):
        try:
            faq_obj = Faq.objects.filter(end_date__isnull =True).order_by('-id')
            all_Data =[]
            for faq in faq_obj:
                all_data = {
                    'id':faq.id,
                    'title':faq.title,
                    'content':faq.content
                }
                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 userRegister(APIView):
    def get(self, request):
        job_function = JobFunctions.objects.filter(end_date__isnull=True)
        job_Data = []
        for func in job_function:
            job_data = {
                'id':func.id,
                'title':func.title,
            }
            job_Data.append(job_data)
        job_level = JobLevel.objects.filter(end_date__isnull = True)
        job_Level = []
        for level in job_level:
            job_level = {
                'id':level.id,
                'title':level.title,
            }
            job_Level.append(job_level)

        return Response({'status_code':status.HTTP_200_OK,'status_message':'Success','job_function':job_Data,'job_level':job_Level})


    def post(self,request):
        try:
            username = request.data.get('username')
            if not username:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'username is required'},status=status.HTTP_400_BAD_REQUEST)
            
            job_level = request.data.get('job_level')
            if not job_level:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'job_level is required'},status=status.HTTP_400_BAD_REQUEST)
            job_function = request.data.get('job_function')
            if not job_function:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'job_function is required'},status=status.HTTP_400_BAD_REQUEST)
            email = request.data.get('email').lower()
            if not email:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Email is required'},status=status.HTTP_400_BAD_REQUEST)
            check_email = User.objects.filter(email=email).first()
            if check_email:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'This email is already registered with us.'},status=status.HTTP_400_BAD_REQUEST)
            password = request.data.get('password')
            if not password:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Password is required'},status=status.HTTP_400_BAD_REQUEST)
            confirm_password = request.data.get('confirm_password')
            if not confirm_password:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Confirm Password is required'},status=status.HTTP_400_BAD_REQUEST)
            if password != confirm_password:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Password and Confirm Password are not same.'},status=status.HTTP_400_BAD_REQUEST)
           
            fcmToken = request.data.get('fcmToken')
            if not fcmToken:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'fcmToken is required '},status=status.HTTP_400_BAD_REQUEST)

            deviceToken = request.data.get('deviceToken')
            if not deviceToken:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'deviceToken is required '},status=status.HTTP_400_BAD_REQUEST)

            deviceType = request.data.get('deviceType')
            if not deviceType:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'deviceType is required '},status=status.HTTP_400_BAD_REQUEST)

            function_obj =  JobFunctions.objects.get(id = job_function)
            level_obj =  JobLevel.objects.get(id = job_level)

            string_password =  confirm_password
            final_password = handler.hash(string_password)
            theotp=random.randrange(1000, 9999, 5)
            # first_last = str(first_name) +' '+ str(last_name)
            customerObj = User.objects.filter(email = email).first()
            if customerObj:
                customerObj.register_otp=theotp
                customerObj.otp_created_at = datetime.now()
                customerObj.save()
            else:
                customerObj=User.objects.create(password = final_password,email=email,username=username,job_level=level_obj,job_function=function_obj,is_user = True,device_token = deviceToken,device_type = deviceType,fcm_token = fcmToken )
                customerObj.register_otp=theotp
                customerObj.otp_created_at = datetime.now()
                customerObj.save()

            to_emails = customerObj.email
            subject = "Verify Account"
            html_message = render_to_string('email_verifcation.html', {'otp': theotp})
            plain_message = html_message
            from_email = 'testsingh28@gmail.com'
            to = email
            mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message)
            AdminNotifications.objects.create(message=customerObj.username+ ' has been successfully registered with us.',type='new_user')
            return Response({'status_code':status.HTTP_200_OK,'status_message':'You have been successfully registered with us.Please verify your email.','otp':theotp})
        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 otpVerification(APIView):
    def post(self,request):
            try:
                email = request.data.get('email')
                if not email:
                    return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Email is required'},status=status.HTTP_400_BAD_REQUEST)
                otp = request.data.get('otp')
                if not otp:
                    return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Otp is required'},status=status.HTTP_400_BAD_REQUEST)

                check_email = User.objects.filter(email=email).first()
                if not check_email:
                    return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Email not exist'},status=status.HTTP_400_BAD_REQUEST)

                user_obj = User.objects.filter(email=email,register_otp = otp).first()
                if user_obj:
                    user_obj.is_otp_verified = 1
                    user_obj.user_stripe_id = generate_strip_id()
                    user_obj.save()
                    return Response({'status_code':status.HTTP_200_OK,'status_message':'Successfully Verified'})
                else:
                    return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Invalid otp'})
            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 userResendOtp(APIView):
    def post(self, request):
        try:
            email =  request.data.get('email')
            if not email:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Email is required'},status=status.HTTP_400_BAD_REQUEST)
            user_obj = User.objects.filter(email =email).last()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Phone number not exist'})
            else:
                theotp=random.randrange(1000, 9999, 5)
                user_obj.register_otp=theotp
                user_obj.save()
                subject = "Verify Account"
                html_message = render_to_string('email_verifcation.html', {'otp': theotp})
                plain_message = html_message
                from_email = 'testsingh28@gmail.com'
                to = email
                mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message)
                return Response({'status_code':status.HTTP_200_OK,'status_message':'Otp Send successfully','otp':theotp})
        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 userLogin(APIView):
    def post(self,request):
        try:
            email = request.data.get('email').lower()
            if not email:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Email is required'},status=status.HTTP_400_BAD_REQUEST) 
            password = request.data.get('password')
            if not password:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Password is required'},status=status.HTTP_400_BAD_REQUEST)  
            user  = User.objects.filter(email=email).count()
            if user == 0:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'This email does not exist in our database, please register'},status=status.HTTP_400_BAD_REQUEST)
            userObj  = User.objects.filter(email=email).first()
            if not userObj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No account found'},status=status.HTTP_400_BAD_REQUEST)
            check_otp_verified = User.objects.filter(email=email,is_otp_verified=False).first()
            if check_otp_verified :
                theotp=random.randrange(1000, 9999, 5)
                userObj.register_otp=theotp
                userObj.save()
                subject = "Verify Account"
                html_message = render_to_string('email_verifcation.html', {'otp': theotp})
                plain_message = html_message
                from_email = 'testsingh28@gmail.com'
                to = email
                mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message)
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Please verify your email.'},status=status.HTTP_400_BAD_REQUEST)

            fcmToken = request.data.get('fcmToken')
            if not fcmToken:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'fcmToken is required '},status=status.HTTP_400_BAD_REQUEST)

            deviceToken = request.data.get('deviceToken')
            if not deviceToken:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'deviceToken is required '},status=status.HTTP_400_BAD_REQUEST)

            deviceType = request.data.get('deviceType')
            if not deviceType:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'deviceType is required '},status=status.HTTP_400_BAD_REQUEST)
            if userObj.end_date is not None:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'This account is deleted. '},status=status.HTTP_400_BAD_REQUEST)

            userObj.device_token = deviceToken
            userObj.device_type = deviceType
            userObj.fcm_token = fcmToken

            userObj.save()
            new_pass = userObj.password
            check = handler.verify(request.data.get('password'),new_pass)
            if check:
                refresh_token = RefreshToken.for_user(userObj)
                allData={'id':userObj.id,
                    'email':userObj.email,
                    'username':userObj.username,
                    'device_token':userObj.device_token,
                    'has_subscription':userObj.has_subscription,
                    'refresh': str(refresh_token),
					'access': str(refresh_token.access_token),
                    
                   }
                return Response({'status_code':status.HTTP_200_OK,'status_message':'Login Successfully','data':allData})
            else:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Invalid password'},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 userForgetPassword(APIView):
    def post(self,request):
                email = request.data.get('email').lower()
                if not email:
                    return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Email is required'},status=status.HTTP_400_BAD_REQUEST)
                user  = User.objects.filter(email=email).count()
                if user == 0:
                    return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'This email does not exist in our database, please enter the valid email address.'},status=status.HTTP_400_BAD_REQUEST)
                userObj  = User.objects.filter(email=email).first()

                if userObj:
                    ran_num = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(12)])
                    baselink =  '/api-panel/forgoten/' + str(userObj.email) + '/' + ran_num
                    completelink = str(settings.BASE_URL) + baselink
                    userObj.forgot_password_link = baselink
                    userObj.save()
                    subject = 'Forgot Password'
                    html_message = render_to_string('user_forget_password_email.html', {'link': completelink})
                    plain_message = html_message
                    from_email = 'testeresfera@gmail.com'
                    to = email
                    mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message)
                    return Response({'status_code':status.HTTP_200_OK,'status_message':'Reset password link has been sent to this email address.'})
                else:
                    return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Email not exists'},status=status.HTTP_400_BAD_REQUEST)


class forgetPasswordVerification(APIView):
    def get(self,request):
        link = str(self.request.path)
        print(link)
        user_email = link.split('/')[-2]
        link_expiry = User.objects.filter(email = user_email).first()
        if link_expiry.forgot_password_link == "LinkExpiry":
            return render(request,'link-expire.html')
        user_obj = User.objects.filter(email = user_email, forgot_password_link = link).first()
        
        if user_obj:
            print('True')
            valid = True
        else:
            print('False')
            valid = False
        return render(request,'forgot.html',{'valid':valid})	

    def post(self,request):
        form = forms.forgetverification(request.POST)
        if form.is_valid():
            new_password = form.cleaned_data.get('new_password')
            confirm_new_password = form.cleaned_data.get('confirm_new_password')
            link = str(self.request.path)
            user_email = link.split('/')[-3]
            print(user_email)
            user_obj = User.objects.filter(email = user_email).first()
            if user_obj:
                user_obj.set_password(new_password)
                user_obj.forgot_password_link = "LinkExpiry"
                user_obj.save()
                messages.success(request, "Changed successfully")
                return render(request,'password_success.html')
        else:
            return render(request, 'forgot.html', {'form': form})

class userUpdateProfile(APIView):
    def get(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            job_function = JobFunctions.objects.filter(end_date__isnull=True)
            job_Data = []
            for func in job_function:
                job_data = {
                    'id':func.id,
                    'title':func.title,
                }
                job_Data.append(job_data)
            job_level = JobLevel.objects.filter(end_date__isnull = True)
            job_Level = []
            for level in job_level:
                job_level = {
                    'id':level.id,
                    'title':level.title,
                }
                job_Level.append(job_level)
            all_data = {
                'user_id':user_obj.id,
                'avatar':user_obj.avatar,
                'email':user_obj.email,
                'phone_number':user_obj.phone_number,
                'username':user_obj.username,
                'job_level_id':user_obj.job_level.id,
                'job_level':user_obj.job_level.title,
                'job_function_id':user_obj.job_function.id,
                'job_function':user_obj.job_function.title,
                'has_subscription':user_obj.has_subscription,
            }
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Success','data':all_data,'job_function':job_Data,'job_level':job_Level})
        except Exception as e:
            print(e)
            return Response({'status_code':status.HTTP_500_INTERNAL_SERVER_ERROR,'status_message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def post(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            username = request.data.get('username')
            if not username:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Username is required'},status=status.HTTP_400_BAD_REQUEST)
            email = request.data.get('email')
            if not email:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Email is required'},status=status.HTTP_400_BAD_REQUEST)
            email_check = User.objects.filter(email = email).exclude(id=user_obj.id)
            if email_check:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'This email is already associated with some account.'},status=status.HTTP_400_BAD_REQUEST)
            phone_number = request.data.get('phone_number')
            if not phone_number:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Phone number is required'},status=status.HTTP_400_BAD_REQUEST)
            job_function =  request.data.get('job_function')
            if not job_function:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'job_function is required'},status=status.HTTP_400_BAD_REQUEST)
            function_obj =  JobFunctions.objects.get(id = job_function)
            job_level =  request.data.get('job_level')
            if not job_level:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'job_level is required'},status=status.HTTP_400_BAD_REQUEST)
            level_obj =  JobLevel.objects.get(id = job_level)
            avatar = request.data.get('avatar')
            user_obj.username = username
            user_obj.email = email
            user_obj.avatar = avatar
            user_obj.phone_number = phone_number
            user_obj.job_function = function_obj
            user_obj.job_level = level_obj
            user_obj.save()
            all_data = {
                'user_id':user_obj.id,
                'avatar':user_obj.avatar,
                'email':user_obj.email,
                'username':user_obj.username,
                'job_level_id':user_obj.job_level.id,
                'job_level':user_obj.job_level.title,
                'job_function_id':user_obj.job_function.id,
                'job_function':user_obj.job_function.title,
                'phone_number':user_obj.phone_number,

            }
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Profile updated successfully','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 userChangePassword(APIView):
    def post(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            old_password = request.data.get('old_password')
            if not old_password:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'old password is required'},status=status.HTTP_400_BAD_REQUEST)
            new_password = request.data.get('new_password')
            if not new_password:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'new password is required'},status=status.HTTP_400_BAD_REQUEST)
            new_confirm_password = request.data.get('new_confirm_password')
            if not new_confirm_password:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'new confirm password is required'},status=status.HTTP_400_BAD_REQUEST)
            
            if user_obj.check_password(old_password) == False:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Does not match with the old password'},status=status.HTTP_400_BAD_REQUEST)
            if user_obj.check_password(old_password) == new_confirm_password:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'New password should not be same as old password.'},status=status.HTTP_400_BAD_REQUEST)

            password = new_confirm_password
            user_obj.set_password(password)
            user_obj.save()
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Password Changed 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 userDeleteAccount(APIView):
    def post(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            user_obj.end_date = datetime.now()
            user_obj.save()
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Account deleted 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 getCustomerNotifications(APIView):
    def get(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            notify_obj = CustomerNotifications.objects.filter(user=user_obj.id,end_date__isnull = True).order_by('-id')
            allData=[]
            for notify in notify_obj:
                alldata = {
                    'id':notify.id,
                    'message': notify.message,
                    'notification_type' : notify.notification_type,
                    'start_date':timesince(notify.start_date)+' ago',
                }
                allData.append(alldata)
            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 deleteCustomerNotifications(APIView):
     def post(self,request):
        token = get_authorization_header(request)
        if token is None or token == "null" or token.strip() == "":
            raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
        decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
        user_id = decoded['user_id']
        user_obj =  User.objects.filter(id = user_id,is_user=1).first()
        if not user_obj:
            return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
        notification_id =  request.data.get('notification_id')
        if not notification_id:
            return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Notification Id is required'},status=status.HTTP_400_BAD_REQUEST)
        CustomerNotifications.objects.filter(id=notification_id).update(end_date=datetime.now())
        return Response({'status_code':status.HTTP_200_OK,'status_message':'Notification Deleted Successfully'})

class HelpSupportUser(APIView):
    def post(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            title = request.data.get('title')
            if not title:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'title is required'},status=status.HTTP_400_BAD_REQUEST)
            description = request.data.get('description')
            if not description:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'description is required'},status=status.HTTP_400_BAD_REQUEST)
            HelpSupport.objects.create(title=title,description=description,user_id=user_obj.id)
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Help & Support Send 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 SendServiceFeedback(APIView):
    def post(self, request):
        try:
            first_name =  request.data.get('first_name')
            if not first_name:
                    return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'first_name is required'},status=status.HTTP_400_BAD_REQUEST)
            last_name = request.data.get('last_name')
            if not last_name:
                    return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'last_name is required'},status=status.HTTP_400_BAD_REQUEST)
            quality =  request.data.get('quality')
            if not quality:
                    return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'quality is required'},status=status.HTTP_400_BAD_REQUEST)
            comment = request.data.get('comment')
            if not comment:
                    return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'comment is required'},status=status.HTTP_400_BAD_REQUEST)
            ServiceFeedback.objects.create(first_name=first_name,last_name=last_name,quality=quality,comment=comment)
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Service Feedback Send 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 GetSubscriptionList(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            sub_obj  = SubscriptionPlans.objects.filter(end_date__isnull=True)
            all_Data = []
            for sub in sub_obj:
                all_data = {
                    'id':sub.id,
                    'subscription_name':sub.subscription_name,
                    'subscription_description':sub.subscription_description,
                    'duration':sub.duration,
                    'price':sub.price,
                    'unlock_real':sub.unlock_real,
                    'investment_tool':sub.investment_tool,
                    'status':sub.status,
                }
                all_Data.append(all_data)
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Success','data':all_Data})
        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 getAllBlogs(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            category_id = request.data.get('category_id')
            if category_id:
                blog_obj = Blogs.objects.filter(category= category_id ,end_date__isnull = True,status = 1)
            else:
                 blog_obj = Blogs.objects.filter(end_date__isnull = True,status = 1)
            if not blog_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No blog found'},status=status.HTTP_400_BAD_REQUEST)

            cat_obj =  BlogsCategory.objects.filter(end_date__isnull=True)
            cat_Data = []
            for cat in cat_obj:
                cat_data = {
                    'id': cat.id,
                    'category_name': cat.name,
                }
                cat_Data.append(cat_data)
            all_Data = []
            for blog in blog_obj:
                all_data = {
                    'id':blog.id,
                    'title':blog.title,
                    'uploaded_by':blog.user.username,
                    'blog_image':blog.blog_image,
                    'content':blog.content,
                    'created_at':blog.start_date,
                }
                all_Data.append(all_data)
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Success','data':all_Data,'cat_Data':cat_Data})
        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)

    def post(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            category_id = request.data.get('category_id')
            if not category_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'category id is required'},status=status.HTTP_400_BAD_REQUEST)
                
            blog_obj = Blogs.objects.filter(category= category_id ,end_date__isnull = True,status = 1)
            if not blog_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No blog found'},status=status.HTTP_400_BAD_REQUEST)

            all_Data = []
            for blog in blog_obj:
                all_data = {
                    'id':blog.id,
                    'title':blog.title,
                    'blog_image':blog.blog_image,
                    'content':blog.content,
                    'created_at':blog.start_date,
                    'uploaded_by':blog.user.username,
                }
                all_Data.append(all_data)
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Success','data':all_Data})
        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 getBlogCategories(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            cat_obj =  BlogsCategory.objects.filter(end_date__isnull=True)
            all_Data = []
            for cat in cat_obj:
                all_data = {
                    'id': cat.id,
                    'category_name': cat.name,
                }
                all_Data.append(all_data)
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Success','data':all_Data})
        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 getBlogDetails(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            blog_id = request.query_params.get('blog_id')
            if not blog_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Blog id is required'},status=status.HTTP_400_BAD_REQUEST)
                
            blog_obj = Blogs.objects.filter(id = blog_id).first()
            if not blog_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No blog found'},status=status.HTTP_400_BAD_REQUEST)

            all_data = {
                'id':blog_obj.id,
                'title':blog_obj.title,
                'blog_image':blog_obj.blog_image,
                'content':blog_obj.content,
            }
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Success','data':all_data})
        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 addBlogBookmark(APIView):
    def post(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            blog_id = request.data.get('blog_id')
            if not blog_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'blog id is required'},status=status.HTTP_400_BAD_REQUEST)
            blog_obj = Blogs.objects.filter(id = blog_id).first()
            if not blog_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Blog not found'},status=status.HTTP_400_BAD_REQUEST)
            bookmark_post, created = BlogsBookmarks.objects.get_or_create(blog=blog_obj,user=user_obj,is_bookmarked=1)
            if not created:
                bookmark_post.delete()
                return Response({'status_code':status.HTTP_200_OK,'status_message':'Removed from bookmark list'})
            else: 
                bookmark_post.save()
                return Response({'status_code':status.HTTP_200_OK,'status_message':'Added to bookmark list.'})
        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 bookmarkList(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)

            blog_obj = BlogsBookmarks.objects.filter(user = user_obj.id)
            blog_Data = []
            for blog in blog_obj:
                blog_data = {
                    'id':blog.blog_id,
                    'blog_title':blog.blog.title,
                    'blog_image':blog.blog.blog_image,
                    'content':blog.blog.content,
                    'start_date':blog.blog.start_date,
                    'type':'blog',
                }
                blog_Data.append(blog_data)    
        
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Success','data':blog_Data})
        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 addUserCard(APIView):
	def post(self,request):
		try:
			token = get_authorization_header(request)
			if token is None or token == "null" or token.strip() == "":
				raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
			decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
			user_id = decoded['user_id']
			user_obj =  User.objects.filter(id = user_id,is_user=1).first()
			if not user_obj:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
			card_id = request.data.get('card_id')
			if not card_id:
				return Response({'message': 'card_id is required'}, status=status.HTTP_400_BAD_REQUEST)
			if not user_obj.user_stripe_id:
				user_obj.user_stripe_id = generate_strip_id()
				user_obj.save()
			if user_obj.user_stripe_id:
				user_id = user_obj.user_stripe_id
				stripe.api_key = settings.STRIPE_SECRET_KEY
				createCard = stripe.Customer.create_source(user_id,source=card_id)
				if createCard:
					cardObj = UserCards.objects.create(user=user_obj,card_id=createCard['id'],exp_month=createCard['exp_month'],exp_year=createCard['exp_year'],the_user_stripe=createCard['customer'],last_digits=createCard['last4'])
					alldata = {
						'id':cardObj.id,
						'user_id':cardObj.user_id,
						'card_id':cardObj.card_id,
						'exp_month':cardObj.exp_month,
						'exp_year':cardObj.exp_year,
						'the_user_stripe':cardObj.the_user_stripe,
						'last_digits':cardObj.last_digits,
						'is_default':cardObj.is_default,
					} 
			return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success','data':alldata}) 
		except Exception as e:
			return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
		

class getUserCard(APIView):  
	def get(self,request):
		try:
			token = get_authorization_header(request)
			if token is None or token == "null" or token.strip() == "":
				raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
			decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
			user_id = decoded['user_id']
			user_obj =  User.objects.filter(id = user_id,is_user=1).first()
			if not user_obj:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
			
			card_obj = UserCards.objects.filter(user = user_obj)
			all_Data = []
			for card in card_obj:
				all_data = {
					'id':card.id,
					'user_id':card.user_id,
					'card_id':card.card_id,
					'exp_month':card.exp_month,
					'exp_year':card.exp_year,
					'the_user_stripe':card.the_user_stripe,
					'last_digits':card.last_digits,
					'is_default':card.is_default,
				}
				all_Data.append(all_data)
			return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success','data':all_Data}) 
		except Exception as e:
			return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
		

class deleteUserCard(APIView):
	def post(self,request):
		try:
			token = get_authorization_header(request)
			if token is None or token == "null" or token.strip() == "":
				raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
			decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
			user_id = decoded['user_id']
			user_obj =  User.objects.filter(id = user_id,is_user=1).first()
			if not user_obj:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
			card_id = request.data.get('card_id')
			if not card_id:
				return Response({'message': 'card_id is required'}, status=status.HTTP_400_BAD_REQUEST)
			card_obj = UserCards.objects.filter(id=card_id).first()
			if not card_obj:
				return Response({'message': 'No card found'}, status=status.HTTP_400_BAD_REQUEST)
			stripe.api_key = settings.STRIPE_SECRET_KEY
			stripe.Customer.delete_source(
				card_obj.the_user_stripe,
				card_obj.card_id
			)
			card_obj.delete()
			return Response({'message': 'Success'})
		except Exception as e:
			return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
		


class getCommunityListing(APIView):
    def get(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            community_obj = Community.objects.filter(end_date__isnull=True)
            all_Data = []
            for community in community_obj:
                total_comments =  Comments.objects.filter(Community = community.id).count()
                total_likes =  Likes.objects.filter(Community = community.id).count()
                total_dislikes =  Dislikes.objects.filter(Community = community.id).count()

                all_data = {
                     'id':community.id,
                     'user_id':community.user.id,
                     'user_name':community.user.username,
                     'user_avatar':community.user.avatar,
                     'content':community.content,
                     'created_at':community.start_date,
                     'total_comments':total_comments,
                     'total_likes':total_likes,
                     'total_dislikes':total_dislikes,

                }
                all_Data.append(all_data)
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success','data':all_Data}) 
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        


class addCommunity(APIView):
    def post(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            community_content = request.data.get('community_content')
            if not community_content:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'community_content is requried'},status=status.HTTP_400_BAD_REQUEST)
            Community.objects.create(user = user_obj,content=community_content)  
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success'}) 
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        


class myCommunityListing(APIView):
     def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            community_obj = Community.objects.filter(user= user_obj,end_date__isnull=True)
            all_Data = []
            for community in community_obj:
                all_data = {
                     'id':community.id,
                     'user_id':community.user.id,
                     'user_name':community.user.username,
                     'user_avatar':community.user.avatar,
                     'content':community.content,
                     'created_at':community.start_date,
                }
                all_Data.append(all_data)
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success','data':all_Data}) 

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

class editCommunity(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            community_id = self.request.query_params.get('community_id')
            if not community_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'community_id is required'},status=status.HTTP_400_BAD_REQUEST)

            community_obj = Community.objects.filter(id = community_id).first()
            if not community_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No community data found'},status=status.HTTP_400_BAD_REQUEST)
                 
            all_data = {
                 'id':community_obj.id,
                 'content':community_obj.content,
            } 
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success','data':all_data})     
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def post(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            community_id = request.data.get('community_id')
            if not community_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'community_id is required'},status=status.HTTP_400_BAD_REQUEST)

            community_content = request.data.get('community_content')
            if not community_content:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'community_content is requried'},status=status.HTTP_400_BAD_REQUEST)
            
            Community.objects.filter(id=community_id).update(user = user_obj,content=community_content)  
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success'})     
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class deleteCommunity(APIView):
    def post(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            community_id = request.data.get('community_id')
            if not community_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'community_id is required'},status=status.HTTP_400_BAD_REQUEST)
            
            community_obj = Community.objects.filter(id = community_id).first()
            if not community_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No community data found'},status=status.HTTP_400_BAD_REQUEST) 
            community_obj.delete()
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success'})     
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        

class likeCommunity(APIView):
    def post(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            community_id = request.data.get('community_id')
            if not community_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'community_id is required'},status=status.HTTP_400_BAD_REQUEST)
                 
            comm_obj = Community.objects.filter(id=community_id).first()
            if not comm_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No community found'})
            
            liked_post, created = Likes.objects.get_or_create(Community=comm_obj,user=user_obj,is_liked=1)
            if not created:
                liked_post.delete()
                return Response({'status_code':status.HTTP_200_OK,'status_message':'Community post is unlike'})
            else: 
                liked_post.save()
                return Response({'status_code':status.HTTP_200_OK,'status_message':'Community post is liked'})
        
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) 
        

class dislikeCommunity(APIView):
    def post(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            community_id = request.data.get('community_id')
            if not community_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'community_id is required'},status=status.HTTP_400_BAD_REQUEST)
            comm_obj = Community.objects.filter(id=community_id).first()
            if not comm_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No community found'})
            disliked_post, created = Dislikes.objects.get_or_create(Community=comm_obj,user=user_obj,is_disliked=1)
            if not created:
                disliked_post.delete()
                return Response({'status_code':status.HTTP_200_OK,'status_message':'Disliked is removed'})
            else: 
                disliked_post.save()
                return Response({'status_code':status.HTTP_200_OK,'status_message':'Community post is disliked'})
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) 
        

class commentCommunity(APIView):
    def post(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            community_id = request.data.get('community_id')
            if not community_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'community_id is required'},status=status.HTTP_400_BAD_REQUEST)

            community_obj = Community.objects.filter(id=community_id).first()
            if not community_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No community found'})
            
            comment = request.data.get('comment')
            if not comment:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'comment is required'})
            Comments.objects.create(content=comment,Community=community_obj,user=user_obj)
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Comment added successfully'})
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) 
        

class editCommentCommunity(APIView):
    def post(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            comment_id = request.data.get('comment_id')
            if not comment_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'comment_id is required'},status=status.HTTP_400_BAD_REQUEST)
            community_id = request.data.get('community_id')
            if not community_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'community_id is required'},status=status.HTTP_400_BAD_REQUEST)
            content = request.data.get('content')
            if not content:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'content is required'},status=status.HTTP_400_BAD_REQUEST)
            Comments.objects.filter(id= comment_id,Community_id=community_id,user_id=user_obj.id).update(content=content)
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Comment edit successfully'})
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) 



class deleteCommentCommunity(APIView):
    def post(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            comment_id = request.data.get('comment_id')
            if not comment_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'comment_id is required'},status=status.HTTP_400_BAD_REQUEST)
            post_id = request.data.get('post_id')
            if not post_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'post_id is required'},status=status.HTTP_400_BAD_REQUEST)
            Comments.objects.filter(id=comment_id,post_id=post_id,user_id=user_obj.id).delete()
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Comment deleted successfully'})
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) 
        

class viewCommunityComments(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            community_id = self.request.query_params.get('community_id')
            if not community_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'community_id is required'},status=status.HTTP_400_BAD_REQUEST)
        
            comment_obj = Comments.objects.filter(Community_id = community_id,end_date__isnull = True)
            all_Data = []
            for comment in comment_obj:
                all_data = {
                    'id':comment.id,
                    'comment':comment.content,
                    'user_name':comment.user.username,
                    'user_avatar':comment.user.avatar,
                    'created_at':comment.start_date,
                }
                all_Data.append(all_data)
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success','data':all_Data})     

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

class addBillingDetails(APIView):
    def post(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            full_name = request.data.get('full_name')
            if not full_name:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'full name is required'},status=status.HTTP_400_BAD_REQUEST)
            email = request.data.get('email')
            if not email:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'email is required'},status=status.HTTP_400_BAD_REQUEST)
            address_one = request.data.get('address_one')
            if not address_one:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'address one is required'},status=status.HTTP_400_BAD_REQUEST)
            address_two = request.data.get('address_two')
            if not address_two:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'address one is required'},status=status.HTTP_400_BAD_REQUEST)
            pin_code = request.data.get('pin_code')
            if not pin_code:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'pin code is required'},status=status.HTTP_400_BAD_REQUEST)
            state = request.data.get('state')
            if not state:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'state is required'},status=status.HTTP_400_BAD_REQUEST)
            country = request.data.get('country')
            if not country:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'country is required'},status=status.HTTP_400_BAD_REQUEST)
            CustomerBilling.objects.create(user = user_obj,full_name=full_name,email=email,address_one=address_one,address_two=address_two,pin_code=pin_code,
                                          state=state,country=country )
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success'})  
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) 
        

class getMyBillingDetails(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            billing_obj = CustomerBilling.objects.filter(user = user_obj)
            all_Data = []
            for bill in billing_obj:
                all_data = {
                    'id': bill.id,
                    'full_name':bill.full_name,
                    'email': bill.email,
                    'address_one':bill.address_one,
                    'address_two':bill.address_two,
                    'pin_code':bill.pin_code,
                    'state':bill.state,
                    'country':bill.country,
                }
                all_Data.append(all_data)

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

class purchaseSubscription(APIView):
    def post(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            payment_token = request.data.get('payment_token')
            if not payment_token:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'payment_token is required'},status=status.HTTP_400_BAD_REQUEST)

            subscription_id = request.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 = SubscriptionPlans.objects.get(id = subscription_id )
            if not subscription_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No subscription plan found'},status=status.HTTP_400_BAD_REQUEST)
            if subscription_obj.duration == 'monthly':
                expiry_date = date.today() + timedelta(days=30)
                pay_amount = subscription_obj.price
                amount = pay_amount * 100
            else:
                expiry_date = date.today() + timedelta(days=365)
                pay_amount = subscription_obj.price
                amount = pay_amount * 100
                
            stripe.api_key =settings.STRIPE_SECRET_KEY

            charge = stripe.Charge.create(
				amount=amount,
				currency='usd',
				source=payment_token,
				description='Purchase Subscription'
			)
            if charge:
                sub_data = CustomersSubscriptions.objects.filter(user =user_obj,is_active=True).first()
                if sub_data:
                    sub_data.is_active = False
                    sub_data.save()
                CustomerSubscription.objects.create(subscription = subscription_obj,user =user_obj,buyDate = datetime.datetime.now(), expiryDate = expiry_date,is_active=True)
                user_obj.has_subscription = True
                user_obj.save()
            else:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Payment failed'},status=status.HTTP_400_BAD_REQUEST)   
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) 
        

class mySubscriptionPlan(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            subscription_obj =  CustomerSubscription.objects.filter(user = user_obj,is_active = True).first()
            all_data = {
                'id': subscription_obj.id,
                'plan_id': subscription_obj.subscription.id,
                'plan_name': subscription_obj.subscription.subscription_name,
                'plan_description':subscription_obj.subscription.subscription_description,
                'duration':subscription_obj.subscription.duration,
                'price':subscription_obj.subscription.price,
                'unlock_real':subscription_obj.subscription.unlock_real,
                'investment_tool':subscription_obj.subscription.investment_tool,

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


class eduAiChat(APIView):
    def post(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            question = request.data.get('question')
            if not question:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'question is required'},status=status.HTTP_400_BAD_REQUEST)

            openai.api_key = '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'
            prompt = question
            model_engine = "gpt-3.5-turbo"
            prompt = (f"{prompt}")

            messages = [{"role": "user", "content": prompt}]

            response = openai.ChatCompletion.create(    
            model=model_engine,
            messages=messages,
            temperature=0,
            )

            message = response.choices[0].message["content"]
            # model = "gpt-3.5-turbo"
            # question = question

            # # Use the v1/chat/completions endpoint for chat models
            # response = openai.ChatCompletion.create(
            #     model=model,
            #     messages=[
            #         {"role": "system", "content": "You are a helpful assistant."},
            #         {"role": "user", "content": question}
            #     ],
            #     max_tokens=100,
            #     temperature=0.5,
            # )

            # # After getting the response from the API
            # responses = response['choices']



            # # Sort responses by length in descending order
            # sorted_responses = sorted(responses, key=lambda x: len(x['message']['content']), reverse=True)

            # # Select the longest response
            # longest_message = sorted_responses[0]['message']['content'].strip()

            # Return the longest message
            return Response({'status_code': status.HTTP_200_OK, 'status_message': 'Success', 'data': message})

            # message = response['choices'][0]['message']['content'].strip()

            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success','data':message}) 
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) 
        
class addBlog(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
          
            blog_cat =  BlogsCategory.objects.filter(end_date__isnull = True)
            category_Data = []
            for cat in blog_cat:
                cat_data = {
                    'id':cat.id,
                    'name':cat.name,
                }
                category_Data.append(cat_data)

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

    def post(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            blog_image = request.data.get('blog_image')
            if not blog_image:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Blog image is required'},status=status.HTTP_400_BAD_REQUEST)

            category = request.data.get('category')
            if not category:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'category is required'},status=status.HTTP_400_BAD_REQUEST)

            catgeory_obj = BlogsCategory.objects.get(id=category)
            if not catgeory_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'category not found'},status=status.HTTP_400_BAD_REQUEST)
            
            title = request.data.get('title')
            if not title:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'title is required'},status=status.HTTP_400_BAD_REQUEST)

            content = request.data.get('content')
            if not content:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'content is required'},status=status.HTTP_400_BAD_REQUEST)
            Blogs.objects.create(blog_image= blog_image,category = catgeory_obj,title=title,content=content,user=user_obj)
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success'}) 


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

class editBlog(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            blog_cat =  BlogsCategory.objects.filter(end_date__isnull = True)
            category_Data = []
            for cat in blog_cat:
                cat_data = {
                    'id':cat.id,
                    'name':cat.name,
                }
                category_Data.append(cat_data)
            
            blog_id = request.query_params.get('blog_id')
            if not blog_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Blog Id is required'},status=status.HTTP_400_BAD_REQUEST)
            

            blog_obj =  Blogs.objects.get(id = blog_id)
            all_data = {
                'blog_id':blog_obj.id,
                'title':blog_obj.title,
                'blog_image':blog_obj.blog_image,
                'content':blog_obj.content,

            }
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success','data':all_data,'category_Data':category_Data}) 
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) 
        
    def post(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            
            blog_id = request.data.get('blog_id')
            if not blog_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Blog Id is required'},status=status.HTTP_400_BAD_REQUEST)

            blog_image = request.data.get('blog_image')
            if not blog_image:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Blog image is required'},status=status.HTTP_400_BAD_REQUEST)

            category = request.data.get('category')
            if not category:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'category is required'},status=status.HTTP_400_BAD_REQUEST)

            catgeory_obj = BlogsCategory.objects.get(id=category)
            if not catgeory_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'category not found'},status=status.HTTP_400_BAD_REQUEST)
            
            title = request.data.get('title')
            if not title:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'title is required'},status=status.HTTP_400_BAD_REQUEST)

            content = request.data.get('content')
            if not content:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'content is required'},status=status.HTTP_400_BAD_REQUEST)
            Blogs.objects.filter(id = blog_id).update(blog_image= blog_image,category = catgeory_obj,title=title,content=content,user=user_obj)
            
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success'}) 
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) 


class myBlogListing(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            
            blog_obj  =  Blogs.objects.filter(user = user_obj)
            blog_Data = []
            for blog in blog_obj:
                blog_data = {
                    'id': blog.id,
                    'blog_image': blog.blog_image,
                    'blog_title': blog.title,
                    'category_id': blog.category.id,
                    'category': blog.category.name,
                    'content': blog.content,
                    'start_date': blog.start_date,
                }

                blog_Data.append(blog_data)

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

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


class deleteMyBlog(APIView):
    def post(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            
            blog_id = request.data.get('blog_id')
            if not blog_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'blog_id is required'},status=status.HTTP_400_BAD_REQUEST)
            
            blog_obj  =  Blogs.objects.get(id = blog_id)
            blog_obj.delete()
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success'}) 

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

class addEvent(APIView):
    def post(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            
            event_image = request.data.get('event_image')
            if not event_image:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'event image is required'},status=status.HTTP_400_BAD_REQUEST)

            event_name = request.data.get('event_name')
            if not event_name:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'event name is required'},status=status.HTTP_400_BAD_REQUEST)
            
            description = request.data.get('description')
            if not description:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'description is required'},status=status.HTTP_400_BAD_REQUEST)
            
            date = request.data.get('date')
            if not date:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'date is required'},status=status.HTTP_400_BAD_REQUEST)

            start_time = request.data.get('start_time')
            if not start_time:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'start time is required'},status=status.HTTP_400_BAD_REQUEST)

            end_time = request.data.get('end_time')
            if not end_time:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'end time is required'},status=status.HTTP_400_BAD_REQUEST)
            
            location = request.data.get('location')
            if not location:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'location is required'},status=status.HTTP_400_BAD_REQUEST)

            event_obj = Events.objects.create(event_name = event_name,description = description ,date=date,start_time=start_time,end_time=end_time,location=location,user=user_obj,event_image=event_image)
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success'}) 
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) 
        

class editEvent(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            event_id = request.GET.get('event_id')
            if not event_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'event id is required'},status=status.HTTP_400_BAD_REQUEST)

            event_obj =  Events.objects.filter(id = event_id,user_id =  user_obj).first()
            if not event_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No event found'},status=status.HTTP_400_BAD_REQUEST)


            all_data = {
                'id': event_obj.id,
                'event_image':event_obj.event_image,
                'event_name':event_obj.event_name,
                'user':event_obj.user.id,
                'description':event_obj.description,
                'date':event_obj.date,
                'start_time':event_obj.start_time,
                'end_time':event_obj.end_time,
                'location':event_obj.location,
                'created_at':event_obj.start_date,
            }


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


    def post(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            
            event_id = request.data.get('event_id')
            if not event_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'event id is required'},status=status.HTTP_400_BAD_REQUEST)

            event_image = request.data.get('event_image')
            if not event_image:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'event image is required'},status=status.HTTP_400_BAD_REQUEST)

            event_name = request.data.get('event_name')
            if not event_name:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'event name is required'},status=status.HTTP_400_BAD_REQUEST)
            
            description = request.data.get('description')
            if not description:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'description is required'},status=status.HTTP_400_BAD_REQUEST)
            
            date = request.data.get('date')
            if not date:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'date is required'},status=status.HTTP_400_BAD_REQUEST)

            start_time = request.data.get('start_time')
            if not start_time:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'start time is required'},status=status.HTTP_400_BAD_REQUEST)

            end_time = request.data.get('end_time')
            if not end_time:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'end time is required'},status=status.HTTP_400_BAD_REQUEST)
            
            location = request.data.get('location')
            if not location:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'location is required'},status=status.HTTP_400_BAD_REQUEST)

            event_obj = Events.objects.filter(id = event_id).update(event_name = event_name,description = description ,date=date,start_time=start_time,end_time=end_time,location=location,user=user_obj,event_image=event_image)
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success'}) 
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) 
        


class myEventListing(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)

            event_obj =  Events.objects.filter(user_id =  user_obj,end_date__isnull = True)
            all_Data = []
            for event in event_obj:
                all_data = {
                    'id': event.id,
                    'event_image':event.event_image,
                    'event_name':event.event_name,
                    'user':event.user.id,
                    'description':event.description,
                    'date':event.date,
                    'start_time':event.start_time,
                    'end_time':event.end_time,
                    'location':event.location,
                    'created_at':event.start_date,
                }
                all_Data.append(all_data)
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success','data':all_Data}) 
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) 
        

class deleteEvent(APIView):
    def post(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            
            event_id = request.data.get('event_id')
            if not event_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'event_id is required'},status=status.HTTP_400_BAD_REQUEST)
            
            event_obj  =  Events.objects.get(id = event_id,user = user_obj)
            if not event_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No event found'},status=status.HTTP_400_BAD_REQUEST)
            event_obj.end_date = datetime.now()
            event_obj.save()
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success'}) 

        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) 
        
    
class allEventListing(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)

            event_obj =  Events.objects.filter(end_date__isnull=True)
            all_Data = []
            for event in event_obj:
                all_data = {
                    'id': event.id,
                    'event_image':event.event_image,
                    'event_name':event.event_name,
                    'user':event.user.id,
                    'description':event.description,
                    'date':event.date,
                    'start_time':event.start_time,
                    'end_time':event.end_time,
                    'location':event.location,
                    'created_at':event.start_date,
                }
                all_Data.append(all_data)
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success','data':all_Data}) 
        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) 


class viewEventDetails(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            event_id = request.GET.get('event_id')
            if not event_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'event id is required'},status=status.HTTP_400_BAD_REQUEST)

            event_obj =  Events.objects.filter(id= event_id,end_date__isnull=True).first()
            

            all_data = {
                'id': event_obj.id,
                'event_image':event_obj.event_image,
                'event_name':event_obj.event_name,
                'user':event_obj.user.id,
                'description':event_obj.description,
                'date':event_obj.date,
                'start_time':event_obj.start_time,
                'end_time':event_obj.end_time,
                'location':event_obj.location,
                'created_at':event_obj.start_date,
            }

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

        except Exception as e:
            return Response({'message': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) 
        
class saveEvent(APIView):
    def post(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            event_id = request.data.get('event_id')
            if not event_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'event id is required'},status=status.HTTP_400_BAD_REQUEST)
            event_obj = Events.objects.filter(id = event_id).first()
            if not event_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Event not found'},status=status.HTTP_400_BAD_REQUEST)
            saved_event, created = SavedEvents.objects.get_or_create(event=event_obj,user=user_obj,is_saved=1)
            if not created:
                saved_event.delete()
                return Response({'status_code':status.HTTP_200_OK,'status_message':'Removed from saved list'})
            else: 
                saved_event.save()
                return Response({'status_code':status.HTTP_200_OK,'status_message':'Added to saved list.'})
        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 savedEventListing(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)

            saved_event  = SavedEvents.objects.filter(user_id = user_obj)

            all_Data = []
            for saved in saved_event:
                all_data = {
                    'id': saved.id,
                    'event_id': saved.event.id,
                    'event_image':saved.event.event_image,
                    'event_name':saved.event.event_name,
                    'user':saved.event.user.id,
                    'description':saved.event.description,
                    'date':saved.event.date,
                    'start_time':saved.event.start_time,
                    'end_time':saved.event.end_time,
                    'location':saved.event.location,
                    'created_at':saved.event.start_date,

                }
                all_Data.append(all_data)
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success','data':all_Data}) 
        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 getInvestmentNews(APIView):
    def get(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            
            import requests

            url = "https://newsapi.org/v2/top-headlines"
            api_key = "cab020d5af044de3851b2c8ed3955d07"

            params = {
                'country': 'us',
                'category': 'business',
                'apiKey': api_key
            }

            response = requests.get(url, params=params)
            if response.status_code == 200:
                data = response.json()
                articles = data.get('articles', [])
                return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success','data':articles}) 
            else:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':f"Error: {response.status_code} - {response.text}"},status=status.HTTP_400_BAD_REQUEST)
                
        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 saveInvestmentNews(APIView):
    def post(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)

            title =  request.data.get('title')
            if not title:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'title is required'},status=status.HTTP_400_BAD_REQUEST)

            description = request.data.get('description')
            if not description:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'description is required'},status=status.HTTP_400_BAD_REQUEST)

            url = request.data.get('url')
            if not url:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'url is required'},status=status.HTTP_400_BAD_REQUEST)

            urltoimage = request.data.get('urltoimage')
            if not urltoimage:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'urltoimage is required'},status=status.HTTP_400_BAD_REQUEST)

            published_at = request.data.get('published_at')
            if not published_at:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'published_at is required'},status=status.HTTP_400_BAD_REQUEST)

            SavedNews.objects.create(title=title,description=description,url=url,urltoimage=urltoimage,published_at=published_at,user=user_obj)
            
            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 removedSavedNews(APIView):
    def post(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            saved_id = request.data.get('saved_id')
            if not saved_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'saved id is required'},status=status.HTTP_400_BAD_REQUEST)
            news_obj = SavedNews.objects.get(id = saved_id)
            news_obj.delete()
            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 mySavedNews(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            news_obj = SavedNews.objects.filter(user_id = user_obj.id)
            all_Data = []
            for news in news_obj:
                all_data = {
                    'id':news.id,
                    'title':news.title,
                    'description':news.description,
                    'url':news.url,
                    'urltoimage':news.urltoimage,
                    'published_at': news.published_at,
                    'saved_data': news.start_date,

                }
                all_Data.append(all_data)
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success','data':all_Data}) 
        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 getInvestmentEducationCategory(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            
            category = InvestmentEducationCategory.objects.filter(end_date__isnull = True,status=1)
            all_Data = []
            for cat in category:
                all_data = {
                    'id':cat.id,
                    'name':cat.name,
                    'is_premium':cat.is_subscription,
                }
                all_Data.append(all_data)
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success','data':all_Data}) 
            
        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 getInvestmentEducationSubcategory(APIView):
    def get(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            
            main_id = request.GET.get('main_id')
            if not main_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Main id is required'},status=status.HTTP_400_BAD_REQUEST)

            sub_obj = InvestmentEducationSubCategory.objects.filter(category = main_id,end_date__isnull = True,status=1 )
            all_Data = []
            for sub in  sub_obj:
                all_data = {
                    'id':sub.id,
                    'name':sub.name,
                    'category_id':sub.category.id,
                    'category_name':sub.category.name,
                }
                all_Data.append(all_data)
            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success','data':all_Data}) 
        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 getInvestmentEducationDetails(APIView):
    def get(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            
            sub_category_id = request.GET.get('sub_category_id')
            if not sub_category_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'sub_category_id is required'},status=status.HTTP_400_BAD_REQUEST)

            content_obj = InvestmentEducationContent.objects.filter(sub_category = sub_category_id).first()
            if not content_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No content found'},status=status.HTTP_400_BAD_REQUEST)

            all_data = {
                'id':content_obj.id,
                'main_category_id':content_obj.sub_category.category.id,
                'main_category_name':content_obj.sub_category.category.name,
                'sub_category_id':content_obj.sub_category.category.id,
                'sub_category_name':content_obj.sub_category.category.name,
                'title':content_obj.title,
                'content':content_obj.content,
                'video':content_obj.video,
                'created_at':content_obj.start_date,
            }


            return Response ({'status_code':status.HTTP_200_OK,'status_message':'Success','data':all_data}) 
        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 topGainersStocks(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            
            # Get all US stock market tickers
            all_stocks_list = pd.read_html("https://finance.yahoo.com/markets/stocks/gainers/")


            # Convert each DataFrame to JSON
            stocks_json_list = [df.to_json(orient='records') for df in all_stocks_list]




            # Parse each JSON string and create a list of JSON objects
            stocks_json_objects = [json.loads(json_str) for json_str in stocks_json_list]




            # Flatten the list of lists into a single list
            flattened_stocks_list = []
            for sublist in stocks_json_objects:
                flattened_stocks_list.extend(sublist)


            return Response({
                'status_code': status.HTTP_200_OK,
                'status_message': 'Success',
                'data': flattened_stocks_list
            })
        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 topLooserStocks(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            
            # Get all US stock market tickers
            all_stocks_list = pd.read_html("https://finance.yahoo.com/markets/stocks/losers/")

            # Convert each DataFrame to JSON
            stocks_json_list = [df.to_json(orient='records') for df in all_stocks_list]

            # Parse each JSON string and create a list of JSON objects
            stocks_json_objects = [json.loads(json_str) for json_str in stocks_json_list]


            # Flatten the list of lists into a single list
            flattened_stocks_list = []
            for sublist in stocks_json_objects:
                flattened_stocks_list.extend(sublist)
            return Response({
                'status_code': status.HTTP_200_OK,
                'status_message': 'Success',
                'data': flattened_stocks_list
            })
        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 topActiveStocks(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            
            # Get all US stock market tickers
            all_stocks_list = pd.read_html("https://finance.yahoo.com/markets/stocks/most-active/")

           # Convert each DataFrame to JSON
            stocks_json_list = [df.to_json(orient='records') for df in all_stocks_list]

            # Parse each JSON string and create a list of JSON objects
            stocks_json_objects = [json.loads(json_str) for json_str in stocks_json_list]

            # Flatten the list of lists into a single list
            flattened_stocks_list = []
            for sublist in stocks_json_objects:
                flattened_stocks_list.extend(sublist)

            return Response({
                'status_code': status.HTTP_200_OK,
                'status_message': 'Success',
                'data': flattened_stocks_list
            })
        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 getAllStocks(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            
            # Get all US stock market tickers
            all_stocks_list = pd.read_html("https://in.tradingview.com/markets/stocks-united-kingdom/market-movers-all-stocks/")

           # Convert each DataFrame to JSON
            stocks_json_list = [df.to_json(orient='records') for df in all_stocks_list]

            # Parse each JSON string and create a list of JSON objects
            stocks_json_objects = [json.loads(json_str) for json_str in stocks_json_list]

            # Flatten the list of lists into a single list
            flattened_stocks_list = []
            for sublist in stocks_json_objects:
                flattened_stocks_list.extend(sublist)

            return Response({
                'status_code': status.HTTP_200_OK,
                'status_message': 'Success',
                'data': flattened_stocks_list
            })
        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 getAllCommodities(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            
            
            # Get all US stock market tickers
            all_stocks_list = pd.read_html("https://finance.yahoo.com/markets/commodities/")

            # Convert each DataFrame to JSON
            stocks_json_list = [df.to_json(orient='records') for df in all_stocks_list]

            # Parse each JSON string and create a list of JSON objects
            stocks_json_objects = [json.loads(json_str) for json_str in stocks_json_list]


            # Flatten the list of lists into a single list
            flattened_stocks_list = []
            for sublist in stocks_json_objects:
                flattened_stocks_list.extend(sublist)


            return Response({
                'status_code': status.HTTP_200_OK,
                'status_message': 'Success',
                'data': flattened_stocks_list
            })
        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 getWorldIndices(APIView):
	def get(self, request):
		try:
			token = get_authorization_header(request)
			if token is None or token == "null" or token.strip() == "":
				raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
			decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
			user_id = decoded['user_id']
			user_obj =  User.objects.filter(id = user_id,is_user=1).first()
			if not user_obj:
				return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
			# Get all US stock market tickers
			all_stocks_list = pd.read_html("https://finance.yahoo.com/markets/world-indices/")

			# Convert each DataFrame to JSON
			stocks_json_list = [df.to_json(orient='records') for df in all_stocks_list]

			# Parse each JSON string and create a list of JSON objects
			stocks_json_objects = [json.loads(json_str) for json_str in stocks_json_list]
			
			flattened_stocks_list = []
			for sublist in stocks_json_objects:
				flattened_stocks_list.extend(sublist)
            

			return Response({
				'status_code': status.HTTP_200_OK,
				'status_message': 'Success',
				'data': flattened_stocks_list
			})
		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 getTrendingTickers(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            # Get all US stock market tickers
            all_stocks_list = pd.read_html("https://finance.yahoo.com/markets/stocks/trending/")

            # Convert each DataFrame to JSON
            stocks_json_list = [df.to_json(orient='records') for df in all_stocks_list]

            # Parse each JSON string and create a list of JSON objects
            stocks_json_objects = [json.loads(json_str) for json_str in stocks_json_list]
            flattened_stocks_list = []
            for sublist in stocks_json_objects:
                flattened_stocks_list.extend(sublist)			
            
			

            return Response({
                'status_code': status.HTTP_200_OK,
                'status_message': 'Success',
                'data': flattened_stocks_list
            })
        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 getTopMutalFunds(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            
            # Get all US stock market tickers
            all_stocks_list = pd.read_html("https://finance.yahoo.com/markets/mutualfunds/gainers/")

            # Convert each DataFrame to JSON
            stocks_json_list = [df.to_json(orient='records') for df in all_stocks_list]

            # Parse each JSON string and create a list of JSON objects
            stocks_json_objects = [json.loads(json_str) for json_str in stocks_json_list]
            flattened_stocks_list = []
            for sublist in stocks_json_objects:
                flattened_stocks_list.extend(sublist)		

            return Response({
                'status_code': status.HTTP_200_OK,
                'status_message': 'Success',
                'data': flattened_stocks_list
            })
        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 getStocksDetails(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            symbol = request.GET.get('symbol')
            if not symbol:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'symbol is required'},status=status.HTTP_400_BAD_REQUEST)

            ticker_obj  = yf.Ticker(symbol)
            
            # get all stock info
            all_info = ticker_obj.info
            
            # get last month data
            hist = ticker_obj.history(period="1mo")

            hist['Date '] = hist.index.strftime('%Y-%m-%d %H:%M:%S')

            # get news 
            news = ticker_obj.news

            df = yf.download(tickers=symbol, period='1d', interval='1m')

            # Add a new column 'Datetime' to include datetime information
            df['Datetime'] = df.index.strftime('%Y-%m-%d %H:%M:%S')

            # Convert DataFrame to JSON
            data_frame_json_data = df.to_json(orient='records')

            return Response({
                'status_code': status.HTTP_200_OK,
                'status_message': 'Success',
                'stock_info': all_info,
                'history_month':hist,
                'news':news,
                'stock_data_frame':json.loads(data_frame_json_data),
            })


        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 getTopEtfs(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            
            # Get all US stock market tickers
            all_stocks_list = pd.read_html("https://finance.yahoo.com/markets/etfs/most-active/")

            # Convert each DataFrame to JSON
            stocks_json_list = [df.to_json(orient='records') for df in all_stocks_list]

            # Parse each JSON string and create a list of JSON objects
            stocks_json_objects = [json.loads(json_str) for json_str in stocks_json_list]
            
            flattened_stocks_list = []
            for sublist in stocks_json_objects:
                flattened_stocks_list.extend(sublist)	
            return Response({
                'status_code': status.HTTP_200_OK,
                'status_message': 'Success',
                'data': flattened_stocks_list
            })
        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 getCurrencies(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            # Get all US stock market tickers
            all_stocks_list = pd.read_html("https://finance.yahoo.com/markets/currencies/")

            # Convert each DataFrame to JSON
            stocks_json_list = [df.to_json(orient='records') for df in all_stocks_list]

            # Parse each JSON string and create a list of JSON objects
            stocks_json_objects = [json.loads(json_str) for json_str in stocks_json_list]
            flattened_stocks_list = []
            for sublist in stocks_json_objects:
                flattened_stocks_list.extend(sublist)	


            return Response({
                'status_code': status.HTTP_200_OK,
                'status_message': 'Success',
                'data': flattened_stocks_list
            })
        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 saveStocksAndOthers(APIView):
    def post(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            market_type = request.data.get('market_type')
            if not market_type:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Market type is required'},status=status.HTTP_400_BAD_REQUEST)
            symbol = request.data.get('symbol')
            if not symbol:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Symbol is required'},status=status.HTTP_400_BAD_REQUEST)
            name = request.data.get('name')
            if not name:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Name is required'},status=status.HTTP_400_BAD_REQUEST)
            SavedMarkets.objects.create(market_type = market_type,symbol=symbol,name=name,user = user_obj)


            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 unsaveStocksAndOthers(APIView):
    def get(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)

            stock_id = request.data.get('stock_id') 
            if not stock_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'stock_id is required'},status=status.HTTP_400_BAD_REQUEST)            
            saved_obj =  SavedMarkets.objects.filter(id = stock_id,user = user_obj).first()
            if not saved_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No data found'},status=status.HTTP_400_BAD_REQUEST)            

            saved_obj.delete()

            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 mySavedMarketData(APIView):
     def get(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)

            market_type = request.GET.get('market_type')
            if not market_type:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'market_type is required'},status=status.HTTP_400_BAD_REQUEST)

            
            saved_stock = SavedMarkets.objects.filter(market_type = market_type,user = user_obj.id )
            if not saved_stock:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No data found'},status=status.HTTP_400_BAD_REQUEST)            

            all_Data = []
            for saved in saved_stock:
                all_data = {
                    'id':saved.id,
                    'symbol':saved.symbol,
                    'name':saved.name,
                    'market_type':saved.market_type,
                    'created_at':saved.start_date
                }
                all_Data.append(all_data)

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

        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 giveRatingAndFeedback(APIView):
    def post(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            rating = request.data.get('rating')
            if not rating:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'rating is required'},status=status.HTTP_400_BAD_REQUEST)

            feedback =  request.data.get('feedback')
            if not feedback:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'feedback is required'},status=status.HTTP_400_BAD_REQUEST)

            section_name = request.data.get('section_name')
            if not section_name:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'section_name is required'},status=status.HTTP_400_BAD_REQUEST)
            
            RatingAndFeedback.objects.create(ratings = rating,feedback= feedback,section_name=section_name,user=user_obj)
            
            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 myRatingAndFeedback(APIView):
     def get(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)

            rating_obj  = RatingAndFeedback.objects.filter(user = user_obj.id,end_date__isnull=True)
            all_Data = []
            for rating in rating_obj:
                all_data = {
                    'id': rating.id,
                    'ratings': rating.ratings,
                    'feedback': rating.feedback,
                    'section_name ': rating.section_name,
                    'created_at': rating.start_date,
                }
                all_Data.append(all_data)

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

        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 deleteRatingAndFeedback(APIView):
    def post(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)

            rating_id = request.data.get('rating_id')
            if not rating_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'rating_id is required'},status=status.HTTP_400_BAD_REQUEST)

            rating_obj  = RatingAndFeedback.objects.get(id = rating_id )
            rating_obj.delete()

            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 editRatingAndFeedback(APIView):
    def get(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            
            rating_id =  request.GET.get('rating_id')
            if not rating_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'rating_id is required'},status=status.HTTP_400_BAD_REQUEST)

            rating_obj = RatingAndFeedback.objects.get(id=rating_id)
            if not rating_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'No data found'},status=status.HTTP_400_BAD_REQUEST)

            all_data = {
                'id': rating_obj.id,
                'ratings': rating_obj.ratings,
                'feedback': rating_obj.feedback,
                'section_name ': rating_obj.section_name,
                'created_at': rating_obj.start_date,
            }

            return Response({
                            'status_code': status.HTTP_200_OK,
                            'status_message': 'Success',
                            'data':all_data
                        })   
        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)
        

    def post(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            
            rating_id = request.data.get('rating_id')
            if not rating_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'rating_id is required'},status=status.HTTP_400_BAD_REQUEST)


            rating = request.data.get('rating')
            if not rating:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'rating is required'},status=status.HTTP_400_BAD_REQUEST)

            feedback =  request.data.get('feedback')
            if not feedback:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'feedback is required'},status=status.HTTP_400_BAD_REQUEST)

            section_name = request.data.get('section_name')
            if not section_name:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'section_name is required'},status=status.HTTP_400_BAD_REQUEST)
            
            RatingAndFeedback.objects.filter(id = rating_id).update(ratings = rating,feedback= feedback,section_name=section_name,user=user_obj)
            
            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 stockScreener(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            

            # Retrieve query parameters
            market_cap_more_than = request.GET.get('marketCapMoreThan')
            market_cap_lower_than = request.GET.get('marketCapLowerThan')
            price_more_than = request.GET.get('priceMoreThan')
            price_lower_than = request.GET.get('priceLowerThan')
            beta_more_than = request.GET.get('betaMoreThan')
            beta_lower_than = request.GET.get('betaLowerThan')
            volume_more_than = request.GET.get('volumeMoreThan')
            volume_lower_than = request.GET.get('volumeLowerThan')
            dividend_more_than = request.GET.get('dividendMoreThan')
            dividend_lower_than = request.GET.get('dividendLowerThan')
            is_etf = request.GET.get('isEtf')
            is_actively_trading = request.GET.get('isActivelyTrading')
            sector = request.GET.get('sector')
            industry = request.GET.get('industry')
            country = request.GET.get('country')
            exchange = request.GET.get('exchange')
            limit = request.GET.get('limit')

        
            # Prepare the request parameters
            params = {
                'apikey': settings.FMP_KEY,
                'marketCapMoreThan': market_cap_more_than,
                'marketCapLowerThan': market_cap_lower_than,
                'priceMoreThan': price_more_than,
                'priceLowerThan': price_lower_than,
                'betaMoreThan': beta_more_than,
                'betaLowerThan': beta_lower_than,
                'volumeMoreThan': volume_more_than,
                'volumeLowerThan': volume_lower_than,
                'dividendMoreThan': dividend_more_than,
                'dividendLowerThan': dividend_lower_than,
                'isEtf': is_etf,
                'isActivelyTrading': is_actively_trading,
                'sector': sector,
                'industry': industry,
                'country': country,
                'exchange': exchange,
                'limit': limit,
            }

            # Make the API request
            response = requests.get('https://financialmodelingprep.com/api/v3/stock-screener', params=params)

            # Check for successful response
            if response.status_code != 200:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Failed to fetch data'},status=status.HTTP_400_BAD_REQUEST)

            # Parse the JSON response
            result_stocks = response.json()
        
            return Response({
                    'status_code': status.HTTP_200_OK,
                    'status_message': 'Success',
                    'data': result_stocks
                })      
        
        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 getQuizQuestions(APIView):
    def get(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            all_Data = []

            quiz_obj = QuizModel.objects.all()
            for quiz in quiz_obj:
                all_data = {
                    'id':quiz.id,
                    'question':quiz.question,
                    'option_one':quiz.op1,
                    'option_two':quiz.op2,
                    'option_three':quiz.op3,
                    'option_four':quiz.op4,
                    'answer':quiz.ans,
                }
                all_Data.append(all_data)

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

        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 getInvestResearchListing(APIView):
    def get(self,request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            invest_obj  =  InvestmentResearch.objects.filter(end_date__isnull = True)
            all_Data = []
            for invest in invest_obj:
                all_data = {
                    'id':invest.id,
                    'research_image':invest.research_image,
                    'title':invest.title,
                    'created_at':invest.start_date,
                }

                all_Data.append(all_data)
            return Response({
                    'status_code': status.HTTP_200_OK,
                    'status_message': 'Success',
                    'data': all_Data,
                })
        
        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 getInvestResearchDetails(APIView):
    def get(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            research_id = request.GET.get('research_id')
            if not research_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'research_id is required'},status=status.HTTP_400_BAD_REQUEST)
            if user_obj.has_subscription == False:
                if user_obj.investment_research_count == 100:
                    return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Buy subscription plan to read more content'},status=status.HTTP_400_BAD_REQUEST)
                else:
                    invest_obj  =  InvestmentResearch.objects.filter(id = research_id ,end_date__isnull = True).first()
                    all_data = {
                        'id':invest_obj.id,
                        'research_image':invest_obj.research_image,
                        'title':invest_obj.title,
                        'video':invest_obj.video,
                        'created_at':invest_obj.start_date,
                        'content':invest_obj.content,
                    }
                    user_obj.investment_research_count += 1
                    user_obj.save()
                    return Response({
                            'status_code': status.HTTP_200_OK,
                            'status_message': 'Success',
                            'data': all_data,
                        })
            else:
                invest_obj  =  InvestmentResearch.objects.filter(id = research_id ,end_date__isnull = True).first()
                all_data = {
                    'id':invest_obj.id,
                    'research_image':invest_obj.research_image,
                    'title':invest_obj.title,
                    'video':invest_obj.video,
                    'created_at':invest_obj.start_date,
                    'content':invest_obj.content,
                }
                return Response({
                        'status_code': status.HTTP_200_OK,
                        'status_message': 'Success',
                        'data': all_data,
                    })

        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 addResearchBookmark(APIView):
    def post(self, request):
        try:
            token = get_authorization_header(request)
            if token is None or token == "null" or token.strip() == "":
                raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
            decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
            user_id = decoded['user_id']
            user_obj =  User.objects.filter(id = user_id,is_user=1).first()
            if not user_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
            research_id = request.GET.get('research_id')
            if not research_id:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'research_id is required'},status=status.HTTP_400_BAD_REQUEST)
            invest_obj  =  InvestmentResearch.objects.filter(id = research_id ,end_date__isnull = True).first()

            if not invest_obj:
                return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'Investment research not found'},status=status.HTTP_400_BAD_REQUEST)
            
            bookmark_post, created = InvestmentEducationCategory.objects.get_or_create(research=invest_obj,user=user_obj,is_bookmarked=1)
            if not created:
                bookmark_post.delete()
                return Response({'status_code':status.HTTP_200_OK,'status_message':'Removed from bookmark list'})
            else: 
                bookmark_post.save()
                return Response({'status_code':status.HTTP_200_OK,'status_message':'Added to bookmark list.'})

        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 getHomePage(APIView):
    def get(self, request):
        # try:
        token = get_authorization_header(request)
        if token is None or token == "null" or token.strip() == "":
            raise exceptions.AuthenticationFailed('Authorization Header or Token is missing on Request Headers')
        print(settings.SECRET_KEY)
        decoded = jwt.decode(token, settings.SECRET_KEY,algorithms=['HS256'])
        print(decoded)
        user_id = decoded['user_id']
        user_obj =  User.objects.filter(id = user_id,is_user=1).first()
        if not user_obj:
            return Response({'status_code':status.HTTP_400_BAD_REQUEST,'status_message':'User does not exists.'},status=status.HTTP_400_BAD_REQUEST)
        #----------------------active stocks------------------------------#
        active_stocks_list = pd.read_html("https://finance.yahoo.com/markets/stocks/most-active/")
        active_stocks_df = active_stocks_list[0].head(6)
        active_stocks_json = active_stocks_df.to_json(orient='records')
        active_stocks_json_objects = json.loads(active_stocks_json)

        #-----------------------gainers stocks-----------------------------#
        gainer_stocks_list = pd.read_html("https://finance.yahoo.com/markets/stocks/gainers/")
        gainer_stocks_df = gainer_stocks_list[0].head(6)
        gainer_stocks_json = gainer_stocks_df.to_json(orient='records')
        gainer_stocks_json_objects = json.loads(gainer_stocks_json)


        #-----------------------loosers stocks---------------------------#
        looser_stocks_list = pd.read_html("https://finance.yahoo.com/markets/stocks/losers/")
        looser_stocks_df = looser_stocks_list[0].head(6)
        looser_stocks_json = looser_stocks_df.to_json(orient='records')
        looser_stocks_json_objects = json.loads(looser_stocks_json)





        #-----------------------------Blogs----------------------------------#
        blog_category =  BlogsCategory.objects.filter(end_date__isnull=True)
        category_Data = []
        for cat in blog_category:
            cat_data = {
                'id': cat.id,
                'category_name': cat.name,
            }
            category_Data.append(cat_data)
        blog_category_id = request.GET.get('blog_category_id')
        if blog_category_id:
            blog_obj =  Blogs.objects.filter(end_date__isnull=True,categrory_id = blog_category_id).order_by('-id')[:5]
        else:
            blog_obj =  Blogs.objects.filter(end_date__isnull=True).order_by('-id')[:5]
        blog_Data = []
        for blog in blog_obj:
            blog_data = {
                'id':blog.id,
                'title':blog.title,
                'uploaded_by':blog.user.username,
                'blog_image':blog.blog_image,
                'content':blog.content,
                'created_at':blog.start_date,
            }
            blog_Data.append(blog_data)


        #------------------------------News------------------------------------#
        import requests

        url = "https://newsapi.org/v2/top-headlines"
        api_key = "cab020d5af044de3851b2c8ed3955d07"

        params = {
            'country': 'us',
            'category': 'business',
            'apiKey': api_key
        }

        response = requests.get(url, params=params)
        if response.status_code == 200:
            data = response.json()
            articles = data.get('articles', [])
            # Process articles here
        else:
            print("Failed to fetch top headlines:", response.text)
                    
        #---------------------------Events---------------------------------------#
            
        event_obj =  Events.objects.filter(end_date__isnull=True).order_by('-id')[:5]
        all_Data = []
        for event in event_obj:
            all_data = {
                'id': event.id,
                'event_image':event.event_image,
                'event_name':event.event_name,
                'start_time':event.start_time,
                'end_time':event.end_time,
                'location':event.location,
                'created_at':event.start_date,
            }
            all_Data.append(all_data)

        return Response({
            'status_code': status.HTTP_200_OK,
            'status_message': 'Success',
            'active_stocks': active_stocks_json_objects,
            'gainers_stocks': gainer_stocks_json_objects,
            'loosers_stocks': looser_stocks_json_objects,
            'blog_category':category_Data,
            'blog_data': blog_Data,
            'news_data': articles,
            'events_data': all_Data,
        })
        
        # 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)
        