<<<<<<< HEAD
from urllib import request
=======
>>>>>>> d56746e (first commit)
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth.hashers import make_password, check_password
from admin_panel.models import *
<<<<<<< HEAD
from django.contrib.auth import authenticate  
from user_panel.models import *
from admin_panel.authentication import authenticated_admin
from admin_panel.functions import *
from user_panel.models import EndUser
from user_panel.models import ChatBot, EndUser
from admin_panel.models import Subscription
from django.utils.timezone import now


=======
from django.contrib.auth import authenticate  # ✅ Import the correct one

from user_panel.models import *
from .authentication import authenticated
from admin_panel.functions import *
from user_panel.models import EndUser
>>>>>>> d56746e (first commit)


class AdminLogIn(APIView):
    def post(self, request):
        try:
            email = request.data.get("email")
            password = request.data.get("password")

            if not email or not password:
                return Response({"message": "Email and password are required"}, status=status.HTTP_400_BAD_REQUEST)

            user = authenticate(username=email, password=password)
            
            if user:
                refresh = RefreshToken.for_user(user)

                return Response({
                    "message": "Login successful",
                    "access": str(refresh.access_token),
                    "refresh": str(refresh),
                    "user_id": user.id,
                    "email": user.email,
                    "is_staff": user.is_staff
                }, status=status.HTTP_200_OK)
            else:
                return Response({"message": "Invalid email or password"}, status=status.HTTP_401_UNAUTHORIZED)

        except Exception as e:
            return Response({"message": f"Login failed: {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



class AdminRegister(APIView):
    def post(self, request):
        try:
            email = request.data.get("email")
            password = request.data.get("password")

            if not email or not password:
                return Response({"message": "Email and password are required"}, status=status.HTTP_400_BAD_REQUEST)

            if User.objects.filter(email=email).exists():
                return Response({"message": "User with this email already exists"}, status=status.HTTP_400_BAD_REQUEST)

            user = User.objects.create_user(
                username=email,  
                email=email,
                password=password
            )

            super_admin = SuperAdmin.objects.create(
                user=user,
                email=email,
                password=make_password(password)  
            )

            refresh = RefreshToken.for_user(user)

            return Response({
                "message": "Admin registered successfully",
                "access": str(refresh.access_token),
                "refresh": str(refresh),
                "user_id": user.id,
                "email": user.email
            }, status=status.HTTP_201_CREATED)

        except Exception as e:
            return Response({"message": f"Registration failed: {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



<<<<<<< HEAD
class AdminTermsConditions(APIView):
    # permission_classes = [IsAdminUser] 

    def get(self, request):
        terms_list = ContentPages.objects.filter(page_type='Terms', user_type='User')

        data = []
        for term in terms_list:
            data.append({
                "id": term.id,
                "title": term.title,
                "content": term.content,
                "start_date": term.start_date.isoformat() if term.start_date else None,
                "end_date": term.end_date.isoformat() if term.end_date else None,
                "created_at": term.created_at.strftime('%Y-%m-%d %H:%M:%S') if hasattr(term, 'created_at') else None,
                "updated_at": term.updated_at.strftime('%Y-%m-%d %H:%M:%S') if hasattr(term, 'updated_at') else None,
            })

        if not data:
            return Response({"message": "No Terms and Conditions found."}, status=status.HTTP_404_NOT_FOUND)
        
        return Response({"terms": data}, status=status.HTTP_200_OK)

    def post(self, request):
        title = request.data.get('title')
        content = request.data.get('content')
        start_date = request.data.get('start_date') 
        end_date = request.data.get('end_date')      

        if not title or not content:
            return Response(
                {"error": "Title and content are required."},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        try:
            if start_date:
                start_date_obj = datetime.strptime(start_date, '%Y-%m-%d').date()
            else:
                start_date_obj = None
            
            if end_date:
                end_date_obj = datetime.strptime(end_date, '%Y-%m-%d').date()
            else:
                end_date_obj = None
        except ValueError:
            return Response(
                {"error": "Invalid date format. Use YYYY-MM-DD."},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        existing = ContentPages.objects.filter(page_type='Terms', user_type='User').first()
        
        if existing:
            existing.title = title
            existing.content = content
            existing.start_date = start_date_obj
            existing.end_date = end_date_obj
            existing.save()
            message = "Terms and Conditions updated successfully."
        else:
            ContentPages.objects.create(
                title=title,
                content=content,
                page_type='Terms',
                user_type='User',
                start_date=start_date_obj,
                end_date=end_date_obj
            )
            message = "Terms and Conditions created successfully."
        
        return Response({"message": message}, status=status.HTTP_200_OK)

        
=======
>>>>>>> d56746e (first commit)
class AdminProfile(APIView):
    def get(self,request):
        try:
            try:
<<<<<<< HEAD
                uid = authenticated_admin(request)
=======
                uid = authenticated(request)
>>>>>>> d56746e (first commit)
            except Exception as e:
                return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)
            
            user_obj = User.objects.filter(id=uid).first()


            if not user_obj:
                
                return Response({'message': 'user not found'}, status=status.HTTP_404_NOT_FOUND)

            admin_obj  = SuperAdmin.objects.all().first()
            if not admin_obj:
                return Response({"message":'Your account has been Inactive, Please contact to admin.',"email":admin_obj.email},status=status.HTTP_406_NOT_ACCEPTABLE)
            
            all_data ={

                "firstName":admin_obj.firstName,
                "gender":admin_obj.gender,
                "phoneNumber":admin_obj.phoneNumber,
                "image":admin_obj.image
            }
            return Response({'status_code':status.HTTP_200_OK,'status_message':'Fetched Successfully','all_data':all_data})
        except Exception as e:
            return Response({'message':str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)
<<<<<<< HEAD
=======
        

>>>>>>> d56746e (first commit)


    def post(self,request):
        try:
            try:
<<<<<<< HEAD
                uid = authenticated_admin(request)
            except Exception as e:
                return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)
            
=======
                uid = authenticated(request)
            except Exception as e:
                return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)
>>>>>>> d56746e (first commit)
            user_obj = User.objects.filter(id = uid).first()

            if not user_obj:
                return Response({'message': 'user not found'}, status=status.HTTP_404_NOT_FOUND)
            
            admin_obj = SuperAdmin.objects.filter(user=user_obj).first()
            if not admin_obj:
                return Response({'message': 'Admin not found'}, status=status.HTTP_404_NOT_FOUND)
            
            firstName = request.data.get("firstName")
            gender = request.data.get("gender")
            phoneNumber =request.data.get("phoneNumber")
            image = request.data.get("image")

            admin_obj.firstName = firstName
            admin_obj.gender = gender
            admin_obj.phoneNumber = phoneNumber
            admin_obj.image = image
            admin_obj.save()
            print("user_obj",admin_obj)

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


class AdminUploadImages(APIView):
    def post(self,request):
        try:
            data = request.data
            images = data.getlist('image')
            image_urls = []
            for image in images:
                image_path = uploadTheDocument(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 AdminChatBotListing(APIView):

    def get(self, request):
        try:
            try:
<<<<<<< HEAD
                uid = authenticated_admin(request)
            except Exception as e:
                return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)

            user_obj = SuperAdmin.objects.filter(user_id=uid).first()



            if not user_obj:
                return Response({'message': 'User not found'}, status=status.HTTP_404_NOT_FOUND)
            
            admin_obj = SuperAdmin.objects.filter(user=user_obj.user).first()
            if not admin_obj:
                return Response({'message': 'Admin not found'}, status=status.HTTP_404_NOT_FOUND)
            
            chatBots = ChatBot.objects.all()
            
            chatbot_listing = []
            for bot in chatBots:
                chatbot_listing.append({

                    "id":bot.id,
					"user_id":bot.user_id,
					"chatbot_name":bot.chatbot_name,
					"business_types":bot.business_types,
					"business_logo":bot.business_logo,
					"business_name":bot.business_name,
					"business_pdf":bot.business_pdf,
					"chatbot_color":bot.chatbot_color,
					"chatbot_style":bot.chatbot_style,
=======
                uid = authenticated(request)
                print("---",uid)
            except Exception as e:
                return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)

            user_obj = EndUser.objects.filter(enduser_id=uid).first()
            print("=======1===",user_obj)
            if not user_obj:
                return Response({'message': 'User not found'}, status=status.HTTP_404_NOT_FOUND)

            if user_obj.is_admin:
                chatBots = chatBot_setting.objects.all()
            else:
                chatBots = chatBot_setting.objects.filter(user=user_obj)  

            chatbot_listing = []
            for bot in chatBots:
                chatbot_listing.append({
                    "id": bot.id,
                    "chatbot_name": bot.chatbot_name,
                    "categories_name": bot.categories_name,
                    "description": bot.description,
                    "pdf_data": bot.pdf_data,
>>>>>>> d56746e (first commit)
                    "created_at": bot.created_at.isoformat()
                })

            return Response({'message': 'Success', 'data': chatbot_listing}, status=status.HTTP_200_OK)

        except Exception as e:
            return Response({'message': 'Internal server error', 'details': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
<<<<<<< HEAD


class AdminSubscritpion(APIView):

    def get(self, request):
        try:
            try:
                admin_id = authenticated_admin(request)
            except Exception as e:
                return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)
            
            
            subscriptions = Subscription.objects.all()
            subscription_list = []
            for sub in subscriptions:
                subscription_list.append({
                    'id': sub.id,
                    'plane_name': sub.plane_name,
                    'description': sub.description,
                    'price': sub.price,
                    'start_date': sub.start_date,
                    'end_date': sub.end_date,
                    'durations': sub.durations,
                    'is_active': sub.is_active,
                    'type': sub.type,
                    'created_at': sub.created_at,
                    'updated_at': sub.updated_at,
                })

            return Response({'message': 'Success', 'data': subscription_list}, status=status.HTTP_200_OK)

        except Exception as e:
            return Response({'message': 'Internal server error', 'details': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def post(self, request):
        try:
            try:
                admin_id = authenticated_admin(request)
            except Exception as e:
                return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)
            
            data = request.data
            plane_name = data.get('plane_name')
            price = data.get('price')
            description = data.get('description', '')
            start_date = data.get('start_date')
            end_date = data.get('end_date')
            durations = data.get('durations')
            is_active = data.get('is_active', True)
            type = data.get('type')

            if not plane_name or not price or not start_date or not end_date:
                return Response({'message': 'plane_name, price, start_date and end_date are required.'},
                                status=status.HTTP_400_BAD_REQUEST)

            subscription = Subscription.objects.create(
                plane_name=plane_name,
                price=price,
                description=description,
                start_date=start_date,
                end_date=end_date,
                durations=durations,
                is_active=is_active,
                type=type
            )

            return Response({'message': 'Subscription created successfully.', 'id': subscription.id},
                            status=status.HTTP_201_CREATED)

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

class AdminSubscriptionEdit(APIView):
    def put(self, request, id):
        try:
            try:
                admin_id = authenticated_admin(request)
            except Exception as e:
                return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)

            subscription = Subscription.objects.filter(id=id).first()
            if not subscription:
                return Response({'message': 'Subscription not found'}, status=status.HTTP_404_NOT_FOUND)

            data = request.data

            plane_name = data.get('plane_name')
            price = data.get('price')
            description = data.get('description', '')
            start_date = data.get('start_date')
            end_date = data.get('end_date')
            durations = data.get('durations')
            is_active = data.get('is_active', True)
            type = data.get('type')

            subscription.plane_name = plane_name
            subscription.price = price
            subscription.description = description
            subscription.start_date = start_date
            subscription.end_date = end_date
            subscription.durations = durations
            subscription.is_active = is_active
            subscription.type = type

            subscription.save()

            return Response({'message': 'Subscription updated successfully'}, status=status.HTTP_200_OK)

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



class AdminDashboard(APIView):
    def get(self, request):
        try:
            try:
                admin_id = authenticated_admin(request)
            except Exception as e:
                return Response({'message': str(e)}, status=status.HTTP_401_UNAUTHORIZED)
            
            total_agents = ChatBot.objects.count()
            
            # active_agents = ChatBot.objects.filter(id).count()
            
            total_leads = UserLeads.objects.count()
            
            today = now().date()
            new_leads_today = UserLeads.objects.filter(created_at__date=today).count()

            return Response({
                'message': 'Dashboard data fetched successfully',
                'data': {
                    'total_agents': total_agents,
                    # 'active_agents': active_agents,
                    'total_leads': total_leads,
                    'new_leads_today': new_leads_today,
                }
            }, status=status.HTTP_200_OK)
        
        except Exception as e:
            return Response({'message': 'Internal server error', 'details': str(e)},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)
=======
>>>>>>> d56746e (first commit)
