from django.conf import settings
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import Policy,Ticket,Ticketlog,Quotelog,Auctionlog, Profiles,Otp,Product,Vendor,Enquiry,Vendorquote,Auction,Message,Payment, Paymenthistory, Notification
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.exceptions import NotFound
from django.contrib.auth import authenticate, login
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import User
from django.utils import timezone as djtz
from django.utils import timezone
from datetime import date, datetime, timedelta
import requests
from django.utils import timezone
import pandas as pd
from django.http import HttpResponse
import pyodbc
import base64
from django.db.models import Q
import razorpay
import pandas as pd
from rest_framework.generics import RetrieveAPIView, ListAPIView
from .serializers import UserSerializer
from rest_framework.permissions import IsAuthenticated
from datetime import datetime, time
import json
from django.core.mail import EmailMessage
from school.settings import BASE_DIR
import pdfkit
from django.core.exceptions import ObjectDoesNotExist
# import openai
import re
from django.conf import settings
import threading
# import pywhatkit
from django.core.mail import send_mail
from django.utils.crypto import get_random_string



client = razorpay.Client(auth=(settings.RAZORPAY_API_KEY, settings.RAZORPAY_API_SECRET))

# Razorpay supported currencies
RAZORPAY_SUPPORTED_CURRENCIES = [
    "USD","EUR","GBP","SGD","AED","AUD","CAD","CHF","HKD","JPY",
    "MYR","NZD","SAR","QAR","OMR","KWD","BHD","THB","ZAR","SEK",
    "NOK","DKK","CNY","INR","MXN","PHP","IDR","TWD","HUF","PLN",
    "CZK","TRY","ILS","KRW","BRL","EGP","NGN","PKR","BDT","LKR",
    "KES","GHS","TZS","UGX","RWF","XOF","XAF","MAD","TND"
]


class OrderAPIView(APIView):
    """
    International Payments enabled.
    Frontend sends: amount (smallest unit), currency (user's currency or USD fallback).
    Razorpay gets: native currency amount.
    """
    def post(self, request):
        try:
            amount   = request.data.get('amount')
            currency = request.data.get('currency', 'INR').upper()

            if not amount:
                return Response({
                    "error": True,
                    "message": "Amount is required"
                }, status=status.HTTP_400_BAD_REQUEST)

            # Safety check — fallback to USD if not supported
            if currency not in RAZORPAY_SUPPORTED_CURRENCIES:
                currency = "USD"

            order = client.order.create({
                "amount":          int(amount),   # smallest unit
                "currency":        currency,
                "payment_capture": 1
            })

            return Response({
                "order_id": order["id"],
                "amount":   amount,
                "currency": currency,
            }, status=status.HTTP_200_OK)

        except Exception as e:
            return Response({
                "error":   True,
                "message": str(e)
            }, status=status.HTTP_400_BAD_REQUEST)


class VerifyAPIView(APIView):
    """
    Verify Razorpay payment signature.
    Save correct human-readable amount in user's currency to DB.

    Example DB values:
      India  → payment_amount=824.82, currency=INR  (with 18% GST)
      Oman   → payment_amount=2.87,   currency=OMR
      USA    → payment_amount=8.40,   currency=USD
      Kuwait → payment_amount=2.58,   currency=KWD
      Japan  → payment_amount=1260,   currency=JPY
    """
    permission_classes = (IsAuthenticated,)

    def post(self, request):
        try:
            razorpay_order_id   = request.data.get('razorpay_order_id')
            razorpay_payment_id = request.data.get('razorpay_payment_id')
            razorpay_signature  = request.data.get('razorpay_signature')
            payment_amount      = request.data.get('payment_amount')  # human readable
            currency            = request.data.get('currency', 'INR') # user's currency
            payment_status      = request.data.get('cases')           # e.g. "basicMonth"

            # ── Validate ──────────────────────────────────────────
            if not all([razorpay_order_id, razorpay_payment_id, razorpay_signature]):
                return Response({
                    "error":   True,
                    "message": "Missing payment details"
                }, status=status.HTTP_400_BAD_REQUEST)

            if payment_amount is None:
                return Response({
                    "error":   True,
                    "message": "Payment amount is required"
                }, status=status.HTTP_400_BAD_REQUEST)

            # ── Verify Razorpay signature ─────────────────────────
            params = {
                'razorpay_order_id':   razorpay_order_id,
                'razorpay_payment_id': razorpay_payment_id,
                'razorpay_signature':  razorpay_signature,
            }
            client.utility.verify_payment_signature(params)
            from datetime import date

            # ── Save to DB ────────────────────────────────────────
            amount_to_save = float(payment_amount)

            if Payment.objects.filter(user_id=request.user.id).exists():
                payme = Payment.objects.get(user_id=request.user.id)
                payme.payment_amount = amount_to_save
                payme.payment_status = payment_status
                payme.payment_date   = date.today()  # ✅ 2025-09-07 format

                payme.save()
            else:
                Payment.objects.create(
                    payment_amount=amount_to_save,
                    payment_status=payment_status,
                    user_id=request.user.id,
                    payment_date=date.today(),       # ✅ 2025-09-07 format

                    created_by_id=request.user.id,
                )

            # History எப்பவும் save பண்ணு
            Paymenthistory.objects.create(
                payment_amount=amount_to_save,
                payment_status=payment_status,
                user_id=request.user.id,
                created_by_id=request.user.id,
            )

            return Response({
                "status":  {"code": 200, "response": "success"},
                "error":   None,
                "message": "Payment verified successfully",
            }, status=status.HTTP_200_OK)

        except razorpay.errors.SignatureVerificationError:
            return Response({
                "error":   True,
                "message": "Invalid payment signature"
            }, status=status.HTTP_400_BAD_REQUEST)

        except Exception as e:
            return Response({
                "error":   True,
                "message": str(e)
            }, status=status.HTTP_400_BAD_REQUEST)
# client = razorpay.Client(auth=(settings.RAZORPAY_API_KEY, settings.RAZORPAY_API_SECRET))

# class OrderAPIView(APIView):
#     def post(self, request):
#         data = request.data
#         try:
#             # Extract payment data from the frontend (such as amount)
#             amount = data['amount'] # Amount in paise (100 paise = 1 INR)
#             currency = data['currency'] # Amount in paise (100 paise = 1 INR)

            
#             # Create Razorpay Order
#             order = client.order.create(dict(
#                 amount=amount,
#                 currency=currency,
#                 payment_capture='1'
#             ))
            
         
#             return Response({
#                 'order_id': order['id'],
#                 'amount': amount
#             })

#         except Exception as e:
#             return Response({
#             "status": {"code": status.HTTP_404_NOT_FOUND, "response": "Failed"},
#             'error': True,
#             "message": "Company not found"
#             })


# class VerifyAPIView(APIView):
#     permission_classes = (IsAuthenticated,)

#     def post(self, request):
#         try:
#             razorpay_order_id = request.data.get('razorpay_order_id')
#             razorpay_payment_id = request.data.get('razorpay_payment_id')
#             razorpay_signature = request.data.get('razorpay_signature')
#             amount = request.data.get('payment_amount')
#             payment_status = request.data.get('cases')

#             van  = amount

#             params = {
#                 'razorpay_order_id': razorpay_order_id,
#                 'razorpay_payment_id': razorpay_payment_id,
#                 'razorpay_signature': razorpay_signature
#             }

#             client.utility.verify_payment_signature(params)






            

#             if Payment.objects.filter(user_id=request.user.id).exists():
#                 payme = Payment.objects.get(user_id=request.user.id)
#                 payme.payment_amount = van
#                 payme.payment_status = payment_status
#                 payme.save()

#                 pays = Paymenthistory(payment_amount=van, payment_status=payment_status, user_id=request.user.id, created_by_id=request.user.id)
#                 pays.save()
#             else:
#                 pay = Payment(payment_amount=van, payment_status=payment_status, user_id=request.user.id, created_by_id=request.user.id)
#                 pay.save()

#                 pays = Paymenthistory(payment_amount=van, payment_status=payment_status, user_id=request.user.id, created_by_id=request.user.id)
#                 pays.save()


#             return Response({
#             "status": {"code": status.HTTP_200_OK, "response": "success"},
#             "error": None,
#             "message": "Payment verified successfully",
            
#             })

#         except razorpay.errors.SignatureVerificationError:
#             return Response({
#             "status": {"code": status.HTTP_404_NOT_FOUND, "response": "Failed"},
#             'error': True,
#             "message": "Payment verification failed"
#             })
        


# class LoginAPIView(APIView):

#     def post(self, request):
#         data = request.data
#         user = authenticate(username=data["username"], password=data["password"])

#         if user:
#             login(request, user)
#             token = RefreshToken.for_user(user)

#             try:
#                 profile = Profiles.objects.get(user_id=user.id)
                
#                 if profile.status == 2:  # Check if the profile status is 2
#                     return Response({
#                         "status": {"code": status.HTTP_403_FORBIDDEN, "response": "failed"},
#                         "error": "Inactive user",
#                         "message": "You are inactive. Contact Admin",
#                         "data": None
#                     }, status=status.HTTP_403_FORBIDDEN)

#                 if profile.profiles:
#                     pro = profile.profiles.url  # Assuming 'url' is the field where the profile URL is stored
#                 else:
#                     pro = "../static/dummy.png"
                    
#             except ObjectDoesNotExist:
#                 pro = "../static/dummy.png"

#             return Response({
#                 "status": {"code": status.HTTP_200_OK, "response": "success"},
#                 "error": None,
#                 "message": "Login success",
#                 "data": {
#                     "name": user.first_name,
#                     "id": user.id,
#                     "username": user.username,
#                     "email": user.email,
#                     "isSuper": user.is_superuser,
#                     "refresh": str(token),
#                     "token": str(token.access_token),
#                     "profile": pro,
#                     "role": profile.role,
                    
#                 }
#             })
#         else:
#             return Response({
#                 "status": {"code": status.HTTP_401_UNAUTHORIZED, "response": "error"},
#                 "error": "Authentication failed",
#                 "message": "Invalid username or password",
#                 "data": None
#             }, status=status.HTTP_401_UNAUTHORIZED)

from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView
from django.core.exceptions import ObjectDoesNotExist
from rest_framework_simplejwt.tokens import RefreshToken
import re












class GoogleLoginAPIView(APIView):

    def post(self, request):

        email = request.data.get("email")

        name = request.data.get("name")

        if not email:

            return Response({
                "message": "Email required"
            }, status=400)

        # CHECK USER EXISTS
        user = User.objects.filter(email=email).first()

        # CREATE USER
        if not user:

            username = email.split("@")[0]

            user = User.objects.create_user(
                username=username,
                email=email,
                password=None
            )

            # CREATE PROFILE
            Profiles.objects.create(
                user=user,
                role=0,
                phone="",
                status=1
            )

        # LOGIN
        login(request, user)

        token = RefreshToken.for_user(user)

        profile = Profiles.objects.get(user=user)

        pro = "../static/dummy.png"
        com = "../static/dummy.png"


        return Response({

            "status": {
                "code": status.HTTP_200_OK,
                "response": "success"
            },

            "message": "Google Login Success",



            "data": {

                "id": user.id,
                "username": user.username,
                "email": user.email,
                "token": str(token.access_token),
                "refresh": str(token),
                "role": profile.role,
                "profile" : pro,
                "companylogo" : com

            }

        })


class LoginAPIView(APIView):

    def post(self, request):

        data = request.data

        username_or_email = data.get("username")
        password = data.get("password")

        user = None

        # LOGIN WITH EMAIL
        if re.match(r"[^@]+@[^@]+\.[^@]+", username_or_email):

            try:
                get_user = User.objects.get(email=username_or_email)

                user = authenticate(
                    request,
                    username=get_user.username,
                    password=password
                )

            except User.DoesNotExist:
                user = None

        else:

            # LOGIN WITH USERNAME
            user = authenticate(
                request,
                username=username_or_email,
                password=password
            )

        # CHECK LOGIN SUCCESS
        if user is not None:

            login(request, user)

            token = RefreshToken.for_user(user)

            try:

                profile = Profiles.objects.get(user_id=user.id)

                # INACTIVE USER
                if profile.status == 2:

                    return Response({
                        "status": {
                            "code": status.HTTP_403_FORBIDDEN,
                            "response": "error"
                        },
                        "error": "Inactive user",
                        "message": "You are inactive. Contact Admin",
                        "data": None
                    }, status=status.HTTP_403_FORBIDDEN)

                # DEFAULT PROFILE IMAGE
                try:
                    pro = profile.profiles.url
                except:
                    pro = "../static/dummy.png"

                companyname = profile.name

                # DEFAULT COMPANY LOGO
                com = "../static/dummy.png"

                # VENDOR
                if profile.role == 2:

                    try:

                        created_company = Vendor.objects.get(
                            user_id=profile.user_id
                        )

                        company_creator_profile = Profiles.objects.get(
                            user_id=created_company.created_by_id
                        )

                        if company_creator_profile.companylogo:
                            com = company_creator_profile.companylogo.url

                        companyname = company_creator_profile.servicename

                    except ObjectDoesNotExist:
                        pass

                else:

                    if profile.companylogo:
                        com = profile.companylogo.url

                    companyname = profile.servicename

            except ObjectDoesNotExist:

                pro = "../static/dummy.png"
                com = "../static/dummy.png"
                profile = None

            return Response({

                "status": {
                    "code": status.HTTP_200_OK,
                    "response": "success"
                },

                "error": None,

                "message": "Login success",

                "data": {

                    "name": user.username,

                    "country": profile.alteremail if profile else "",
                    "currency": profile.alteremail1 if profile else "",
                    "symbol": profile.alteremail2 if profile else "",
                    "phone": profile.phone if profile else "",

                    "id": user.id,
                    "username": user.username,
                    "email": user.email,
                    "isSuper": user.is_superuser,

                    "refresh": str(token),
                    "token": str(token.access_token),

                    "profile": pro,
                    "companylogo": com,
                    "companyname": companyname,

                    "role": profile.role if profile else 1,
                }

            })

        else:

            return Response({

                "status": {
                    "code": status.HTTP_401_UNAUTHORIZED,
                    "response": "error"
                },

                "error": "Authentication failed",

                "message": "Invalid username or password",

                "data": None

            }, status=status.HTTP_401_UNAUTHORIZED)



class UserAPIView(RetrieveAPIView):
    permission_classes = (IsAuthenticated,)
    serializer_class = UserSerializer
    

    def get_object(self):
        return self.request.user

    def post(self, request):
        data = request.data

        user = User.objects.get(email=data["email"])
        profile = Profiles.objects.get(user=user)

        

        return Response({
            "status": {"code": status.HTTP_200_OK, "response": "success"},
            "error": True,
            "data": {
                "username": user.username,
                "email": user.email,
                "role": profile.role.id,
                "profile": profile.profiles.url,
            }
        })
    

def send_otp_email(email, otp):
    subject = 'Your One-Time  (OTP) for Verification'
    message = f'''Dear User,

    Your One-Time  (OTP) for verification is:

    {otp}

    Please enter this code to proceed. This OTP is valid for the next 1 minutes.

    If you did not request this code, please ignore this email.

    Thank you,  
    
    '''
    try:
        send_mail(
            subject,
            message,
            settings.DEFAULT_FROM_EMAIL,
            [email],
            fail_silently=False,
        )
    except Exception as e:
        print(f"Error sending email: {e}")
def send_otp_emails(email, otp):
   
    subject = 'Your One-Time  (OTP) for Verification'
    message = f'''Dear User,

    Your One-Time  (OTP) for verification is:

    {otp}

    Please enter this code to proceed. This OTP is valid for the next 1 minutes.

    If you did not request this code, please ignore this email.

    Thank you,  
    
        '''
    try:
        send_mail(
            subject,
            message,
            settings.DEFAULT_FROM_EMAIL,
            [email],
            fail_silently=False,
        )
    except Exception as e:
        print(f"Error sending email: {e}")

# class VendorbulkuploadAPIView(APIView):
#     permission_classes = (IsAuthenticated,)

#     def post(self, request):

#         data = request.data

#         try:

#             uploaded_file = request.FILES['file']
          

#             df = pd.read_excel(uploaded_file, sheet_name='Sheet1')

#             for index, row in df.iterrows():
#                 vendorname = row['Vendor Name']
#                 email = row['Email']
#                 address = row['Address 1']
#                 phone = row['Phone']
#                 gst = row['GST Number']
#                 pincode = row['Pincode']

#                 country = row['Address 2']
#                 state = row['State']
#                 city = row['City']

#                 if Vendor.objects.filter(
#                     Q(email=email) | Q(phone=phone) | Q(gst=gst)
#                 ).exists():
#                     return Response({
#                         "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
#                         "error": True,
#                         "message": f"Vendor already exists with email: {email}, phone: {phone}, or GST: {gst}"
#                     })




#                 password = "12345"
#                 hashed_password = make_password(password)

#                 # Create a new User
#                 datas = User(username=vendorname, password=hashed_password, email=email)
#                 datas.save()

#                 # Fetch the User instance's ID
#                 user_instance = datas.id

#                 # Create a new Profile with the user_id
#                 profile_data = Profiles(
#                     name=vendorname, 
#                     phone=phone, 
#                     role=2, 
#                     email=email, 
#                     address=address, 
#                     password=password, 
#                     user_id=user_instance  # Pass the user ID
#                 )
#                 profile_data.save()

#                 # Create a new Vendor with the user_id
#                 vendor_data = Vendor(
#                     vendorname=vendorname, 
#                     phone=phone, 
#                     email=email, 
#                     address=address, 
#                     pincode=pincode,
#                     gst=gst,
#                     city = city,
#                     state=state,
#                     country=country,
#                     user_id=user_instance,  # Pass the user ID
#                     created_by_id= request.user.id
#                 )
#                 vendor_data.save()



#             return Response({
#                     "status": {"code": status.HTTP_201_CREATED, "response": "success"},
#                     "error": None,
#                     "message": "Vendor created successfully"
#                 })
#         except KeyError as e:
#             return Response({
#                 "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
#                 "error": True,
#                 "message": f"Missing required field: {e}"
#             })
class VendorbulkuploadAPIView(APIView):
    permission_classes = (IsAuthenticated,)

    def post(self, request):
        try:
            company_id = request.user.id

            uploaded_file = request.FILES['file']
            df = pd.read_excel(uploaded_file, sheet_name='Sheet1')

            duplicate_vendors = []
            success_count = 0

            for index, row in df.iterrows():
                try:
                    vendorname = row['Vendor Name']
                    email = row['Email']
                    address = row['Address 1']
                    phone = str(row['Phone Number']).strip()
                    gst = str(row['GST Number']).strip()
                    pincode = str(row['Pincode']).strip()
                    country = row['Address 2']
                    state = row['State']
                    city = row['City']
                    remarks = row['Remarks']

                    exists = Vendor.objects.filter(
                        Q(vendorname=vendorname) | Q(email=email), 
                        created_by_id=company_id
                    ).exists()


                    if exists:
                        duplicate_vendors.append({
                            "vendor": vendorname,
                            "email": email,
                            "reason": "Vendor Name or Email already exists for this company."
                        })
                        continue

                    # Check if vendor already exists
                    # if User.objects.filter(Q(email=email) | Q(username=vendorname)).exists():
                    #     duplicate_vendors.append({
                    #         "vendor": vendorname,
                    #         "email": email,
                           
                    #     })
                    #     continue

                    # Create user
                    default_password = vendorname + "@123"
                    hashed_password = make_password(default_password)

                    user = User.objects.create(
                        username=vendorname,
                        email=email,
                        password=hashed_password
                    )

                    Profiles.objects.create(
                        name=vendorname,
                        phone=phone,
                        role=2,
                        email=email,
                        address=address,
                        password=default_password,
                        user_id=user.id,
                        gst=gst
                    )

                    Vendor.objects.create(
                        vendorname=vendorname,
                        phone=phone,
                        email=email,
                        address=address,
                        pincode=pincode,
                        gst=gst,
                        city=city,
                        state=state,
                        country=country,
                        user_id=user.id,
                        remarks=remarks,
                        created_by_id=request.user.id
                    )

                    success_count += 1

                except KeyError as e:
                    return Response({
                        "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                        "error": True,
                        "message": f"Missing column in Excel: {e}"
                    })
                except Exception as e:
                    return Response({
                        "status": {"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "response": "failed"},
                        "error": True,
                        "message": f"Error processing row {index + 2}: {str(e)}"
                    })

            return Response({
                "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                "error": None,
                "message": f"{success_count} vendor(s) uploaded successfully",
                "duplicates": duplicate_vendors
            })

        except KeyError as e:
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": f"Missing uploaded file: {e}"
            })
        except Exception as e:
            return Response({
                "status": {"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "response": "failed"},
                "error": True,
                "message": str(e)
            })
        


class ProductbulkuploadAPIView(APIView):
    permission_classes = (IsAuthenticated,)

    def post(self, request):

        data = request.data

        try:

            uploaded_file = request.FILES['file']
          

            df = pd.read_excel(uploaded_file, sheet_name='Sheet1')

            for index, row in df.iterrows():
                name = row['Product Name']
                code = row['Material Code']

                description = row['Remarks']
                specification = row['Specification']
                


                # Create a new User
                datas = Product(name=name, description=description,code =code, specification=specification,created_by=request.user)
                datas.save()




            return Response({
                    "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                    "error": None,
                    "message": "Product created successfully"
                })
        except KeyError as e:
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": f"Missing required field: {e}"
            })


    def put(self, request, *args, **kwargs):
        id = kwargs.get("id")  # Extract 'id' from kwargs
        data = request.data

        try:
            company = Product.objects.get(id=id)
            company.sfile = data.get("files", company.sfile)
            company.save()

            return Response({
                "status": {"code": status.HTTP_200_OK, "response": "success"},
                "error": None,
                "message": "File added successfully"
            })
        except Product.DoesNotExist:
            return Response({
                "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                "error": True,
                "message": "No data found"
            })
        except Exception as e:
            print(e)
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": "Something went wrong"
            })


class ContentemailAPIView(APIView):

    def send_em(self, subject, message, from_email, to_email, pdf_file=None):
        try:
            email_message = EmailMessage(
                subject=subject,
                body=message,
                from_email=from_email,
                to=[to_email],
            )
            email_message.content_subtype = "html"  # Mark body as HTML

            

            email_message.send()
        except Exception as e:
            print(f"Error sending email: {e}")

    def post(self, request):
        try:
            # Get values from the form-data
            message = request.POST.get("message")
            to_email = "vinothraj170@gmail.com"

            subject = 'Auction Quote List Details'
            from_email = settings.EMAIL_HOST_USER

            # Use threading to send email asynchronously
            email_thread = threading.Thread(
                target=self.send_em,
                args=(subject, message, from_email, to_email)
            )
            email_thread.start()

            return Response({
                "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                "error": None,
                "message": "Email is being sent in the background."
            })
        except Exception as e:
            return Response({
                "status": {"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "response": "failed"},
                "error": True,
                "message": str(e)
            })
        


class EmailfunctionAPIView(APIView):

    def send_emailsss(self, subject, message, from_email, to_email, pdf_file):
        try:
            email_message = EmailMessage(
                subject=subject,
                body=message,
                from_email=from_email,
                to=[to_email],
            )

            email_message.attach(pdf_file.name, pdf_file.read(), 'application/pdf')

            email_message.send()
        except Exception as e:
            print(f"Error sending email: {e}")

    

    def post(self, request):
        try:
            pdf_file = request.FILES['pdfFile']
            email = request.data.get('email')

            if not email:
                return Response({
                    "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                    "error": True,
                    "message": "Email is required."
                })

            subject = 'Enquiry Details'
            message = 'Hello,  anywhere your Enquiry details Sir.'
            from_email = settings.EMAIL_HOST_USER

            email_thread = threading.Thread(
                target=self.send_emailsss,
                args=(subject, message, from_email, email, pdf_file)
            )
            email_thread.start()

            return Response({
                "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                "error": None,
                "message": "Email is being sent in the background."
            })
        except Exception as e:
            return Response({
                "status": {"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "response": "failed"},
                "error": True,
                "message": str(e)
            })
    
# class SendotpAPIView(APIView):
#     def post(self, request):
#         data  = request.data
#         try:
#             print('Received data:', data)
#             # email = data['email']
#             email = data.get('params', {}).get('email', None)
#             print('emailjkjjjjjjj',email)
#             user = Otp.objects.create(email=email)
#             otp = get_random_string(length=6, allowed_chars='1234567890')
#             user.otp = otp
#             user.otp_created_at = timezone.now()
#             user.save()

#             threading.Thread(target=send_otp_email, args=(email, otp)).start()

           
#             return Response({
#                         "status": {"code": status.HTTP_200_OK, "response": "Success"},
#                         "error": None,
#                         "data": data
#                     })
#         except ObjectDoesNotExist:
#             return Response({
#                 "status": {"code": status.HTTP_404_NOT_FOUND, "response": "Failed"},
#                 'error': True,
#                 "message": "Company not found"
#             })
        
from django.contrib.auth import get_user_model
User = get_user_model()

class SendotpAPIView(APIView):
    def post(self, request):
        data = request.data
        try:
            username = data.get('params', {}).get('email', None)
            print('Received email:', username)

            # ✅ Step 1: Check if email exists in registered users
            if not User.objects.filter(username=username).exists():
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "Email not found"},
                    "error": True,
                    "message": "User name not registered"
                })


            back = User.objects.get(username=username)
            # ✅ Step 2: Create OTP record and send OTP
            user = Otp.objects.create(email=back.email)
            otp = get_random_string(length=6, allowed_chars='1234567890')
            user.otp = otp
            user.otp_created_at = timezone.now()
            user.save()
            email = back.email
            threading.Thread(target=send_otp_email, args=(email, otp)).start()

            return Response({
                "status": {"code": status.HTTP_200_OK, "response": "Success"},
                "error": None,
                "data": {"email": email}
            })
        except Exception as e:
            print("Error:", e)
            return Response({
                "status": {"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "response": "Internal Server Error"},
                'error': True,
                "message": str(e)
            })


class SendotpsAPIView(APIView):
    def post(self, request):
        data = request.data
        try:
            email = data.get('email', None)
            print('Received email:', email)

            # If this is registration
            # if User.objects.filter(email=email).exists() & Profiles.objects.filter(role=1).exists():
            if Profiles.objects.filter(email=email, role=0).exists():

                return Response({
                    "status": {"code": status.HTTP_409_CONFLICT, "response": "Email already registered"},
                    "error": True,
                    "message": "This email is already registered. Please use another email."
                })

            otp = get_random_string(length=6, allowed_chars='1234567890')
            user = Otp.objects.create(email=email, otp=otp, otp_created_at=timezone.now())

            threading.Thread(target=send_otp_emails, args=(email, otp)).start()

            return Response({
                "status": {"code": status.HTTP_200_OK, "response": "Success"},
                "error": None,
                "data": {"email": email}
            })
        except Exception as e:
            return Response({
                "status": {"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "response": "Internal Server Error"},
                'error': True,
                "message": str(e)
            })
        


from datetime import timedelta
from django.utils import timezone

class VerifyotpsAPIView(APIView):
    def get(self, request):
        email = request.query_params.get('email')
        otp_entered = request.query_params.get('otp')

        try:
            user_otp = Otp.objects.filter(email=email).latest('otp_created_at')

            # Expiry time check (30 seconds)
            expiration_time = user_otp.otp_created_at + timedelta(seconds=60)
            if timezone.now() > expiration_time:
                return Response({
                    "status": 401,
                    "message": "OTP expired. Please request a new one.",
                    "error": True
                }, status=status.HTTP_200_OK) 

            if otp_entered == user_otp.otp:
                return Response({
                    "status": 200,
                    "message": "OTP Verified",
                    "error": False
                }, status=status.HTTP_200_OK)
            else:
                return Response({
                    "status": 400,
                    "message": "Invalid OTP",
                    "error": True
                }, status=status.HTTP_200_OK)

        except Otp.DoesNotExist:
            return Response({
                "status": 404,
                "message": "OTP not found",
                "error": True
            }, status=status.HTTP_200_OK)


from datetime import timedelta
from django.utils import timezone

class VerifyotpAPIView(APIView):
    def get(self, request):
        username = request.query_params.get('email')
        dosai  = User.objects.get(username=username)  

        email = dosai.email   

        print(email,'sdsdfdsfsdfsdfsdfsdfdsfdsfdfdsfdsfdfsdssdsd')   
        otp_entered = request.query_params.get('otp')

        try:
            user_otp = Otp.objects.filter(email=email).latest('otp_created_at')

            # Expiry time check (30 seconds)
            expiration_time = user_otp.otp_created_at + timedelta(seconds=60)
            if timezone.now() > expiration_time:
                return Response({
                    "status": 401,
                    "message": "OTP expired. Please request a new one.",
                    "error": True
                }, status=status.HTTP_200_OK) 

            if otp_entered == user_otp.otp:
                return Response({
                    "status": 200,
                    "message": "OTP Verified",
                    "error": False
                }, status=status.HTTP_200_OK)
            else:
                return Response({
                    "status": 400,
                    "message": "Invalid OTP",
                    "error": True
                }, status=status.HTTP_200_OK)

        except Otp.DoesNotExist:
            return Response({
                "status": 404,
                "message": "OTP not found",
                "error": True
            }, status=status.HTTP_200_OK)




    def delete(self, request, id):
        if id is not None:
            try:
                profile = Profiles.objects.get(user_id=id)

                # Delete the image file from storage (optional)
                if profile.profiles:  # replace 'image' with your actual image field name
                    profile.profiles.delete(save=False)  # Deletes the file from MEDIA folder
                    profile.profiles = None
                    profile.save()

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "message": "Profile image deleted successfully"
                })

            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": None,
                    "message": "Profile not found"
                })

        return Response({
            "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
            "error": "ID not provided",
            "message": "User ID is required"
        })


# class VerifyotpAPIView(APIView):
#     def get(self, request):
#         data = request.data



#         otp_entered = request.query_params.get('otp', None)

#         print('Received OTP:', otp_entered)



#         try:
#             # Fetch the latest OTP from the database (replace this with your own logic)
#             user_otp = Otp.objects.latest('otp_created_at')

#             # Check if the entered OTP matches the stored OTP
#             if otp_entered == user_otp.otp:
#                 return Response({
#                     "status": 200,
#                     "message": "OTP Verified",
#                     "error": False
#                 }, status=status.HTTP_200_OK)
#             else:
#                 return Response({
#                     "status": 400,
#                     "message": "Invalid OTP",
#                     "error": True
#                 }, status=status.HTTP_400_BAD_REQUEST)

#         except Otp.DoesNotExist:
#             return Response({
#                 "status": 500,
#                 "message": "No OTP found",
#                 "error": True
#             }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
#         except ObjectDoesNotExist:
#             return Response({
#                 "status": {"code": status.HTTP_404_NOT_FOUND, "response": "Failed"},
#                 'error': True,
#                 "message": "Company not found"
#             })

class ProfileupdateAPIView(APIView):
    
    permission_classes = (IsAuthenticated,)

    def get(self, request, **kwargs):
        id = kwargs.get('id')


        if id is not None:
            try:
                user = User.objects.get(id=id)
                company = Profiles.objects.get(user_id=user.id)
                if company.profiles and company.profiles.url != "../static/dummy.png":
                    pr = company.profiles.url
                else:
                    pr = "../static/dummy.png"

                data = {
                    'name': company.name,
                    'email': company.email,
                    'phone': company.phone,
                    'f_name': user.first_name,
                    'l_name': user.last_name,

                    'profile' : pr,
                    'id': user.id   
                }



                

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "Success"},
                    "error": None,
                    "data": data
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "Failed"},
                    'error': True,
                    "message": "Company not found"
                })

    def post(self, request):
        data = request.data
        try:


            pho = data.get("prof_photo")
            # name = data.get("username")

            take = Profiles.objects.get(user_id=request.user.id)
            take.profiles = pho

            take.save()
            # # Create User instance
            # van = User(username=name, email=email, password=hashed_password)
            # van.save()

           

            return Response({
                "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                "error": None,
                "message": "Profile updated successfully"
            })

        except KeyError as e:
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": f"Missing required field: {str(e)}"
            })
        except Exception as e:
            return Response({
                "status": {"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "response": "failed"},
                "error": True,
                "message": f"An error occurred: {str(e)}"
            })


    def put(self, request, id):
        data = request.data
        prof_photo = request.data.get('prof_photo')
        phone_no = request.data.get('phone_no')
        email_id = request.data.get('email_id')
        first_name = request.data.get('first_name')


    
        if User.objects.filter(username__iexact=first_name).exclude(id=id).exists():
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": "The username you entered already exists."
            }, status=status.HTTP_400_BAD_REQUEST)

       
        try:


            mm = Profiles.objects.get(user_id=id)
            sd = User.objects.get(id=id)


            # vendor = Vendor.objects.get(user_id=id)


            sd.username = data["first_name"]
            sd.first_name = data["first_names"]
            sd.last_name = data["last_name"]


            
            sd.email = data["email_id"]
            sd.save()

            
            mm.email = data["email_id"]
            mm.phone = data["phone_no"]
            mm.name = data["first_name"]
            mm.save()

            vendor = Vendor.objects.get(user_id=mm.user_id)

            vendor.vendorname  =  data["first_name"]
            vendor.email = data["email_id"]
            vendor.phone = data["phone_no"]


            vendor.save()



            return Response({
                "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                "error": None,
                "message": "User updated successfully"
            })
        except ObjectDoesNotExist:
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": "Something went wrong"
            })



class CompanyreportAPIView(APIView):
    def get(self, request, **kwargs):
        id = kwargs.get('id')


        if id is not None:
            try:
                user = User.objects.get(id=id)
                company = Profiles.objects.get(user=user.id)
                if company.profiles and company.profiles.url != "../static/dummy.png":
                    pr = str(company.profiles)
                else:
                    pr = "../static/dummy.png"

                data = {
                    'name': company.name,
                    'email': company.email,
                    'phone': company.phone,
                    'address': company.address,
                    'pincode': company.pincode,
                    'profile' : pr,
                   
                    'firstname': user.first_name,
                    'lastname': user.last_name,
                    'gender': company.gender,
                
                    'doj': company.doj,
                    'password': company.password,
                    


                    'id': user.id   
                }

                

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "Success"},
                    "error": None,
                    "data": data
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "Failed"},
                    'error': True,
                    "message": "Company not found"
                })
        else:

            val = request.GET.get('val')
            print(val)
            try:
                data = []


                username = request.query_params.get('vendorname', '').strip()  # Uncomment this line
                pincode = request.query_params.get('pincode', '').strip()  # Uncomment this line

                email = request.query_params.get('email', '').strip()  # Uncomment this line
                phone = request.query_params.get('phone', '').strip()  # Uncomment this line

                

                status_param = request.query_params.get('status', '').strip()

                if val == '2':
                    companies = Profiles.objects.filter(status=2,role=0)
                else:
                    companies = Profiles.objects.filter(status=1,role=0)


                if username:
                  
                    companies = companies.filter(name__icontains=username) 

                if email:
                  
                    companies = companies.filter(email__icontains=email) 
                if phone:
                  
                    companies = companies.filter(phone__icontains=phone) 

                if pincode:
                  
                    companies = companies.filter(pincode__icontains=pincode) 
                if status_param:
                    try:
                        status_int = int(status_param)
                        if status_int in [1, 2]:
                            companies = companies.filter(status=status_int)
                    except ValueError:
                        pass

                for company in companies:
                        

                    vendorcount = Vendor.objects.filter(created_by_id=company.user_id).count()
                    auctioncount = Auction.objects.filter(created_by_id=company.user_id, status=2).count()


                        

                    users  = User.objects.get(id=company.user_id) 

                    if company.profiles:
                        pro = company.profiles.url
                    else:
                        pro = "../static/dummy.png"

                    company_data = {
                    
                        'name': company.name,
                        'id': company.user_id,
                        'phone': company.phone,
                        'gstnumber': company.gstnumber,
                        'pincode': company.pincode,
                        'vendorcount' : vendorcount,
                        'auctioncount' : auctioncount,

                        'gst': company.gst.url,
                        'email': company.email,
                        'address': company.address,
                        'profile': pro,
                        'phone': company.phone,
                        'status' : company.status,


                    }
                    data.append(company_data)
                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "Success"},
                    "error": None,
                    "data": data
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "Failed"},
                    "error": True,
                    "message": "Something went wrong"
                })

class RegisterAPIView(APIView):
    def get(self, request, **kwargs):
        id = kwargs.get('id')


        if id is not None:
            try:
                user = User.objects.get(id=id)
                company = Profiles.objects.get(user=user.id)
                if company.profiles and company.profiles.url != "../static/dummy.png":
                    pr = company.profiles.url
                else:
                    pr = "../static/dummy.png"

                data = {
                    'name': company.name,
                    'email': company.email,
                    'phone': company.phone,
                    'address': company.address,
                    'pincode': company.pincode,
                    'profile' : pr,
                   
                    'firstname': user.first_name,
                    'lastname': user.last_name,
                    'gender': company.gender,
                
                    'doj': company.doj,
                    'password': company.password,
                    


                    'id': user.id   
                }

                

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "Success"},
                    "error": None,
                    "data": data
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "Failed"},
                    'error': True,
                    "message": "Company not found"
                })
        else:

            val = request.GET.get('val')
            print(val)
            try:
                data = []


                username = request.query_params.get('vendorname', '').strip()  # Uncomment this line
                pincode = request.query_params.get('pincode', '').strip()  # Uncomment this line

                email = request.query_params.get('email', '').strip()  # Uncomment this line
                phone = request.query_params.get('phone', '').strip()  # Uncomment this line

                

                status_param = request.query_params.get('status', '').strip()

                if val == '2':
                    companies = Profiles.objects.filter(status=2,role=0).order_by('-user_id')
                else:
                    companies = Profiles.objects.filter(status=1,role=0).order_by('-user_id')


                if username:
                  
                    companies = companies.filter(name__icontains=username) 

                if email:
                  
                    companies = companies.filter(email__icontains=email) 
                if phone:
                  
                    companies = companies.filter(phone__icontains=phone) 

                if pincode:
                  
                    companies = companies.filter(pincode__icontains=pincode) 
                if status_param:
                    try:
                        status_int = int(status_param)
                        if status_int in [1, 2]:
                            companies = companies.filter(status=status_int)
                    except ValueError:
                        pass

                for company in companies:
                        


                        

                    users  = User.objects.get(id=company.user_id) 

                    if company.profiles:
                        pro = company.profiles.url
                    else:
                        pro = "../static/dummy.png"


                    if company.gst:
                        ero = company.gst.url
                    else:
                        ero = "No file"

                    company_data = {
                    
                        'name': company.name,
                        'id': company.user_id,
                        'phone': company.phone,
                        'gstnumber': company.gstnumber,
                        'pincode': company.pincode,

                        'gst': ero,
                        'email': company.email,
                        'address': company.address,
                        'profile': pro,
                        'phone': company.phone,
                        'status' : company.status,


                    }
                    data.append(company_data)
                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "Success"},
                    "error": None,
                    "data": data
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "Failed"},
                    "error": True,
                    "message": "Something went wrong"
                })

    def post(self, request):
        data = request.data
        try:
            # Collect data from request
            servicename = data.get("servicename")
            name = data.get("username")
            f_name = data.get("first_name")
            l_name = data.get("last_names")

            email = data.get("email_id")
            phone = data.get("ph_no")
            address = data.get("address")
            pincode = data.get("pincode")
            gstnumber = data.get("gstnumber")
            state = data.get("state")


            role = data.get("role")
            gst = data.get("gst")
            doj = data.get("doj")  
            profiles = data.get("prof_photo")
            pan = data.get("pan")
            gender = data.get("gender")
            alteremail = data.get("country")
            alteremail1 = data.get("currency")
            symbol = data.get("symbol")



            password = data.get("password")
            companylogo = data.get("companyprofile")
           
            pro = "../static/dummy.png"

            if not profiles:
                profiles = pro

            hashed_password = make_password(password)

            van = User(first_name=f_name, last_name=l_name, username=name, email=email, password=hashed_password)
            van.save()

            Notification.objects.create(
                    type="newuser",
                    message="A new user has registered",
                    user_id = van.id
                )


            profile_data = Profiles(
                password=password, profiles=profiles,gst=gst, servicename=servicename,gender=state,
                 pan=pan, name=name, email=email, alteremail2=symbol,
                phone=phone, address=address, user=van,doj=doj,pincode=pincode, gstnumber=gstnumber,
                companylogo = companylogo, alteremail=alteremail, alteremail1=alteremail1
            )
            profile_data.save()

            return Response({
                "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                "error": None,
                "message": "New User Registered successfully"
            })

        except KeyError as e:
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": f"Missing required field: {str(e)}"
            })
        except Exception as e:
            return Response({
                "status": {"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "response": "failed"},
                "error": True,
                "message": f"An error occurred: {str(e)}"
            })

    def put(self, request, id):
        val = request.GET.get('val')
        data = request.data
        ctc = request.data.get('ctc')

        if val == '1':
            po = Profiles.objects.get(user_id=id)
            if po.wfh == 1:
                po.wfh = 2
            else:
                po.wfh = 1
            po.save()

            return Response({
                "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                "error": None,
                "message": "WFH updated successfully"
            })
        elif val == '2':
            po = Profiles.objects.get(user_id=id)
            if po.status == 1:
                po.status = 2
            else:
                po.status = 1
            po.save()

            return Response({
                "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                "error": None,
                "message": "Inactive updated successfully"
            })
        elif ctc:
            meow = Profiles.objects.get(user_id=id)
            meow.ctc = data['ctc']
            meow.gross = data['gross']
            meow.pt = data['pt']
            meow.uan = data['uan']
            meow.pan = data['pan']
            meow.account = data['account']
            meow.reim = data['reim']


            meow.save()

            return Response({
                "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                "error": None,
                "message": "Salary details updated successfully"
            })
        else:
            try:
                mm = Profiles.objects.get(user_id=id)
                sd = User.objects.get(id=id)

                mm.name = data["name"]
                mm.pemail = data["pemail"]
                mm.shift = data["shift"]
                mm.marriedstatus = data["marriedstatus"]
                mm.gender = data["gender"]
                mm.email = data["email"]
                mm.phone = data["phone"]
                mm.address = data["address"]
                mm.city = data["city"]
                mm.state = data["state"]
                mm.country = data["country"]
                mm.pincode = data["pincode"]
                mm.department_id = data["department"]
                mm.designation_id = data["designation"]
                mm.role = data["role"]
                mm.authority_id = data["authority"]
                mm.doj = data["doj"]
                mm.profiles = data["profiles"]
                mm.empcode = data["empcode"]
                mm.password = data["password"]
                mm.save()

                sd.username = data["name"]
                sd.first_name = data["firstname"]
                sd.last_name = data["lastname"]
                sd.email = data["email"]
                sd.password = make_password(data["password"])
                sd.save()

                return Response({
                    "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                    "error": None,
                    "message": "User updated successfully"
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                    "error": True,
                    "message": "Something went wrong"
                })

    def delete(self,  *args, **kwargs):
        company_id = kwargs.get('id')

        try:

            pr  = Profiles.objects.get(user_id =company_id)
            pr.delete()
            company = User.objects.get(id=company_id)
            company.delete()

            return Response({
                "status": {"code": status.HTTP_200_OK, "response": "success"},
                "error": None,
                "message": "Company deleted successfully"
            })
        except ObjectDoesNotExist:
            return Response({
                "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                "error": True,
                "message": "No data found"
            })


class TimeAPIView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request, id=None):
        if id is not None:
            try:
                company = Auction.objects.get(en_id_id=id)

                duration = company.duration

                # Convert duration into total seconds
                minutes, seconds = map(int, duration.split(":"))
                total_seconds = minutes * 60 + seconds
         
                data = {
                    'id': company.id,
                    'starttime' : company.end_time,
                    'startdate' : company.end_date,
                    'duration': total_seconds,
                    'status': company.status
                }

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": data
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })
            


class AuctionexpireAPIView(APIView):
    permission_classes = (IsAuthenticated,)

    def put(self, request, id):
        data = request.data
        try:
            company = Auction.objects.get(en_id_id=id)

            company.status = 2
            company.save()

            

            return Response({
            "status": {"code": status.HTTP_200_OK, "response": "success"},
            "error": None,
            "message": "Department updated successfully"
            }   )
        except ObjectDoesNotExist:
            return Response({
                "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                "error": True,
                "message": "No data found"
            })
        except Exception as e:
            print(e)
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": "Something went wrong"
            })
        

class CompanydashboardAPIView(APIView):
    # permission_classes = (IsAuthenticated,)

    def get(self, request):
        
        try:
            from django.utils.timezone import now

            op = request.user.id

            totalenquiry = Enquiry.objects.filter(created_by_id=op).count()

            from django.utils.timezone import now
            from datetime import timedelta

            # Get current user ID
            op = request.user.id

            # Get current date
            current_date = now()

            # Total enquiries by user
            total_enquiry = Enquiry.objects.filter(created_by_id=op).count()

            # Current month enquiry count
            current_month_enquiry = Enquiry.objects.filter(
                created_by_id=op,
                created_at__year=current_date.year,
                created_at__month=current_date.month
            ).count()

            # Calculate last month and handle year change
            if current_date.month == 1:
                last_month = 12
                last_month_year = current_date.year - 1
            else:
                last_month = current_date.month - 1
                last_month_year = current_date.year

            # Last month enquiry count
            last_month_enquiry = Enquiry.objects.filter(
                created_by_id=op,
                created_at__year=last_month_year,
                created_at__month=last_month
            ).count()
           

          

            current_date = now()


            last_month_enquiry = Enquiry.objects.filter(
                created_by_id=op,
                created_at__year=last_month_year,
                created_at__month=last_month
            ).count()

            current_month_enquiry = Enquiry.objects.filter(
                created_by_id=op,
                created_at__year=current_date.year,
                created_at__month=current_date.month
            ).count()



            last_month_auction = Auction.objects.filter(
                created_by_id=op,
                created_at__year=last_month_year,
                created_at__month=last_month
            ).count()

            current_month_auction = Auction.objects.filter(
                created_by_id=op,
                created_at__year=current_date.year,
                created_at__month=current_date.month
            ).count()


            last_month_product = Product.objects.filter(
                created_by_id=op,
                created_at__year=last_month_year,
                created_at__month=last_month
            ).count()

            current_month_product = Product.objects.filter(
                created_by_id=op,
                created_at__year=current_date.year,
                created_at__month=current_date.month
            ).count()

            current_date = now().date()
            totalenquirytodaydate = Enquiry.objects.filter(
                created_by_id=op,
                created_at__date=current_date
            ).count()

            activevendor = Vendor.objects.filter(status=2, created_by_id=op).count()
            inactivevendor = Vendor.objects.filter(status = 1, created_by_id=op).count()

            import calendar
            from datetime import datetime
            monthdata = []
            current_year = datetime.now().year
            current_month = datetime.now().month
            bak = current_month+1


            # Loop from January (1) to May (5)
            for month in range(1, bak):
                month_name = calendar.month_abbr[month]  # 'Jan', 'Feb', etc.

                enquiry_count = Enquiry.objects.filter(
                    created_at__year=current_year,
                    created_at__month=month,
                    created_by_id=op
                ).count()

                monthdata.append({
                    'monthname': month_name,
                    'counts': enquiry_count
                })

           




            totalvendor = 0
            tota = Vendor.objects.filter(created_by_id=op)
            for i in tota:
                totalvendor+= 1

            now = timezone.now()

            # Last month start and end
            first_day_of_current_month = now.replace(day=1)
            last_month_end = first_day_of_current_month - timedelta(days=1)
            last_month_start = last_month_end.replace(day=1)

            # Filter vendors created in last month
            last_month_vendors = Vendor.objects.filter(
                created_by_id=op,
                created_at__gte=last_month_start,
                created_at__lte=last_month_end
            )

            totalvendorlastmonth = last_month_vendors.count()
            data = {
                "totalenquiry": totalenquiry,
                "totalvendor": totalvendor,
                "totalenquirytodaydate": totalenquirytodaydate,
                "activevendor" : activevendor,
                "inactivevendor" : inactivevendor,
                "monthdata" : monthdata,
                "totalvendorlastmonth" :totalvendorlastmonth,
                "current_month_enquiry" : current_month_enquiry,
                "last_month_enquiry" : last_month_enquiry,
                "current_month_auction" : current_month_auction,
                "last_month_auction" : last_month_auction,
                "current_month_product" : current_month_product,
                "last_month_product" : last_month_product

            }

            return Response({
                "status": {"code": status.HTTP_200_OK, "response": "success"},
                "error": None,
                "data": data
            })
        except ObjectDoesNotExist:
            return Response({
                "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                "error": True,
                "message": "No data found",
            })
        



import json



class VendordashboardAPIView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        try:
            op = request.user.id
            enquiry_id = []
            submitcount = 0
            avlcount = 0
            rejectcount = 0  # make sure it's defined even if no quotes found

            enquiries = Enquiry.objects.all()

            for enquiry in enquiries:
                try:
                    vendor_data = enquiry.vendor

                    # Safely handle vendor field whether it's JSON string or list
                    vendor_list = json.loads(vendor_data) if isinstance(vendor_data, str) else vendor_data

                    if str(op) in map(str, vendor_list):
                        avlcount += 1
                        enquiry_id.append(enquiry.id)

                        quote_count = Vendorquote.objects.filter(vendor_id=op, enquiry_id=enquiry.id).count()
                        submitcount += quote_count

                        # Optional reject count logic
                        rejectcount += Vendorquote.objects.filter(
                            vendor_id=op,
                            enquiry_id=enquiry.id,
                            status=3
                        ).count()

                except Exception as e:
                    print(f"Error in enquiry ID {enquiry.id}: {e}")

            # Collect upcoming auctions
            auction = []
            auc = Message.objects.filter(created_by_id=op)
            today = date.today()
            current_date_and_time = datetime.now()   

            for kl in auc:
                try:
                    rp = Auction.objects.get(en_id_id=kl.enq_id_id)

                    
                    end_date = datetime.strptime(rp.end_date, "%Y-%m-%d").date() if isinstance(rp.end_date, str) else rp.end_date
                    end_time = datetime.strptime(rp.end_time, "%H:%M").time() if isinstance(rp.end_time, str) else rp.end_time
                    auction_end = datetime.combine(end_date, end_time)



                    if auction_end > current_date_and_time:
                        auction.append({'auctiondate': end_date})

                except Auction.DoesNotExist:
                    continue

            # Build detailed enquiry info
            datas = []

            for r in enquiry_id:
                try:
                    enquiry = Enquiry.objects.get(id=r)

                    # Build product info
                    pro = []
                    for product_id in enquiry.product:
                        try:
                            rp = Product.objects.get(id=product_id)
                            pro.append({'id': rp.id, 'label': rp.name})
                        except Product.DoesNotExist:
                            continue

                    # Build quantity info
                    quan = [{'label': q} for q in enquiry.quantity]

                    datas.append({
                        'id': enquiry.id,
                        'enq_id': '#ENQ-000'+str(enquiry.auto_id),
                        'date': enquiry.created_at.date(),
                        'deliverylocation': enquiry.deliverylocation,
                        'deliverydate': enquiry.deliverydate,
                        'product': pro,
                        'quantity': quan
                    })

                except Exception as e:
                    print(f"Error processing enquiry ID {r}: {e}")

            data = {
                "avlcount": avlcount,
                "submitcount": submitcount,
                "pendingcount": avlcount - submitcount,
                "rejectcount": rejectcount,
            }

            return Response({
                "status": {"code": status.HTTP_200_OK, "response": "success"},
                "error": None,
                "data": data,
                "datas": datas,
                "datass": auction
            })

        except ObjectDoesNotExist:
            return Response({
                "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                "error": True,
                "message": "No data found",
            })




class AdmindashboardAPIView(APIView):
    # permission_classes = (IsAuthenticated,)

    def get(self, request):
        
        try:
            from django.utils.timezone import now

            op = request.user.id

            current_date = now()
            

            activecompany = Profiles.objects.filter(status=1, role=0).count()
            inactivecompany = Profiles.objects.filter(status = 2, role=0).count()

            import calendar
            from datetime import datetime
            monthdata = []
            current_year = datetime.now().year
            current_month = datetime.now().month
            bak = current_month+1
            from django.db.models import Sum

            # Loop from January (1) to May (5)
            for month in range(1, bak):
                month_name = calendar.month_abbr[month]  # 'Jan', 'Feb', etc.

                payment = Paymenthistory.objects.filter(
                    created_at__year=current_year,
                    created_at__month=month
            
                ).aggregate(total_amount=Sum('payment_amount'))['total_amount'] or 0

                monthdata.append({
                    'monthname': month_name,
                    'counts': payment
                })

            




            totalcompany = Profiles.objects.filter(role=0).count()
            paidcompany = Payment.objects.all().count()
            unpaidcompany  = 0

            qp = Profiles.objects.filter(role=0)
            for b in qp:
                try:
                    Payment.objects.get(user_id=b.user_id)
                    # User has payment → skip
                except Payment.DoesNotExist:
                    unpaidcompany += 1  
                        

            
            

            
                
            data = {
                "paidcompany": paidcompany,
                "unpaidcompany": unpaidcompany,

                "totalcompany": totalcompany,
               
                "activecompany" : activecompany,
                "inactivecompany" : inactivecompany,
                "monthdata" : monthdata
            }
            return Response({
                "status": {"code": status.HTTP_200_OK, "response": "success"},
                "error": None,
                "data": data
            })
        except ObjectDoesNotExist:
            return Response({
                "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                "error": True,
                "message": "No data found",
            })


class CheckAPIView(APIView):
    # permission_classes = (IsAuthenticated,)

    def get(self, request, id=None):
        phone = request.query_params.get('phone')
        email = request.query_params.get('email')
        gst = request.query_params.get('gst')

        if phone or email or gst:
            exists = Vendor.objects.filter(
                Q(phone=phone) | Q(email=email) | Q(gst=gst)
            ).exists()

            return Response({
                "status": {"code": status.HTTP_200_OK, "response": "success"},
                "error": None,
                "exists": exists
            })

        return Response({
            "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
            "error": True,
            "message": "No phone, email, or GST provided."
        }, status=status.HTTP_400_BAD_REQUEST)
    



class CheckcompanyAPIView(APIView):
    def get(self, request, id=None):
        phone = request.query_params.get('phone')
        email = request.query_params.get('email')
        name = request.query_params.get('username')

       
        gstnumber = request.query_params.get('gstnumber') or request.query_params.get('gst')



        print("Check Params:", phone, email, gstnumber)

        if phone or email or gstnumber or name:
            query = Q()
            if name:
                query |= Q(name=name)
            if phone:
                # query |= Q(phone=phone)
                query &= Q(phone=phone) & Q(role=0)
            if email:
                # query |= Q(email=email)
                query &= Q(email=email) & Q(role=0)


                # query |= Q(email=email) | Q(role=1) 
            if gstnumber:
                # query |= Q(gstnumber=gstnumber)
                query &= Q(gstnumber=gstnumber) & Q(role=0)


            exists = Profiles.objects.filter(query).exists()

            return Response({
                "status": {"code": status.HTTP_200_OK, "response": "success"},
                "error": None,
                "exists": exists
            })

        return Response({
            "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
            "error": True,
            "message": "No phone, email, or GST provided."
        }, status=status.HTTP_400_BAD_REQUEST)
    

class CheckvendorAPIView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request, id=None):
        phone = request.query_params.get('phone')
        email = request.query_params.get('email')
        name = request.query_params.get('username')

       
        gstnumber = request.query_params.get('gstnumber') or request.query_params.get('gst')

        company_id = request.user.id

        if phone or email or gstnumber or name:
            query = Q()
            if name:
                query |= Q(name=name)
            if phone:
                query |= Q(phone=phone)
            if email:
                query |= Q(email=email) 


            if gstnumber:
                query |= Q(gstnumber=gstnumber)

            exists = Vendor.objects.filter(query, created_by_id = company_id).exists()

            return Response({
                "status": {"code": status.HTTP_200_OK, "response": "success"},
                "error": None,
                "exists": exists
            })

        return Response({
            "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
            "error": True,
            "message": "No phone, email, or GST provided."
        }, status=status.HTTP_400_BAD_REQUEST)



class ProductAPIView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request, id=None):
        if id is not None:
            try:
                company = Product.objects.get(id=id)

                try:
                    fl = company.sfile.url if company.sfile else None
                except ValueError:
                    fl = None 
                data = {
                    'id': company.id,
                    'name': company.name,
                    'code': company.code,

                    'description': company.description,
                    'specification':company.specification,
                    'sfile': fl,
                    'status': company.status

                }

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": data
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })
        else:
            try:

                index = 0
                companies = []

                user_id = request.query_params.get('user_id')
             
                name = request.query_params.get('name', '').strip()  # Uncomment this line
                status_param = request.query_params.get('status', '').strip()

                if user_id:
                    products = Product.objects.filter(created_by_id=user_id)
                else:
                    products = Product.objects.filter(created_by_id=request.user.id)

                

                if name:
                  
                    products = products.filter(name__icontains=name) 
                if status_param:
                    try:
                        status_int = int(status_param)
                        if status_int in [1, 2]:
                            products = products.filter(status=status_int)
                    except ValueError:
                        pass # Or return an error response if invalid status is critical

                for company in products:
                    index += 1

                    try:
                        fl = company.sfile.url if company.sfile else None
                    except ValueError:
                        fl = None 

                    companies.append({
                        'row': index,
                        'id': company.id,
                        'name': company.name,
                        'code': company.code,

                        'specification': company.specification,
                        'sfile': fl,
                        'status': company.status,

                        'description': company.description,
                    })


                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": companies
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })

    def post(self, request):
        data = request.data

        try:
            company = Product.objects.create(
                name=data["name"],
                code=data["code"],

                description=data["description"],
                specification =data["specification"],
                status =data["status"],

                sfile = data.get("sfile"),
                created_by=request.user
            )
            company.save()

            return Response({
                "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                "error": None,
                "message": "Product created successfully"
            })
        except KeyError as e:
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": f"Missing required field: {e}"
            })





    def put(self, request, id):
        data = request.data

        try:

            ve =data.get("sfile")

            company = Product.objects.get(id=id)
            company.name = data.get("name", company.name)
            company.code = data.get("code", company.code)

            company.description = data.get("description", company.description)
            company.specification = data.get("specification", company.specification)
            company.sfile = data.get("sfile", company.sfile) 
            company.status = data.get("status", company.status)
            company.save()

            return Response({
                "status": {"code": status.HTTP_200_OK, "response": "success"},
                "error": None,
                "message": "Product updated successfully"
            })
        except ObjectDoesNotExist:
            return Response({
                "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                "error": True,
                "message": "No data found"
            })
        except Exception as e:
            print(e)
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": "Something went wrong"
            })

   


    def delete(self, request, id):
        if id is not None:
            try:
                product_id_str = str(id)
                is_used = Enquiry.objects.filter(product__contains=[product_id_str]).exists()

                if is_used:
                    return Response({
                        "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                        "error": "Product is used in enquiry",
                        "message": "Cannot delete product. It's used in one or more enquiries."
                    })

                # If not used, delete the product
                product = Product.objects.get(id=id)
                product.delete()

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "message": "Product deleted successfully"
                })

            except Product.DoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": None,
                    "message": "No product found"
                })
            




class FpAPIView(APIView):

    

    def post(self, request):
        data = request.data

        try:
            
            params = data.get('params', {})

            # Now retrieve 'email' and 'password' from the 'params' dictionary
            username = params.get('email')  # Access the 'email' field
            password = params.get('password')  # Access the 'password' field

            
            # Hash the password
            hashed_password = make_password(password)

            man = User.objects.get(username=username)

            man.password = hashed_password

            man.save()



            return Response({
                "status": {"code": status.HTTP_200_OK, "response": "success"},
                "error": None,
                "message": "Password reset successfully"
            })
        except KeyError as e:
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": f"Missing required field: {e}"
            })



class NotificationAPIView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request, id=None):
        if id is not None:
            # Fetch a specific vendor by ID
            try:
                company = Vendor.objects.get(id=id)
                data = {
                    'id': company.id,
                    'vendorname': company.vendorname,
                    'phone': company.phone,
                    
                }

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": data
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })

        else:
            # Return all notifications of type 'newuser' or 'paymentuser'
            # else:
            from django.utils.timesince import timesince
            from django.utils.timezone import now

            try:
                index = 0
                note = []
                op = request.user.id

                profile = Profiles.objects.get(user_id=op)

                if profile.role == 1:
                    notifications = Notification.objects.filter(
                        type__in=["newuser", "paymentuser"]
                    ).order_by("-created_at")

                    for n in notifications:
                        index += 1
                        try:
                            username = n.user.username if n.user else "Unknown"
                        except User.DoesNotExist:
                            username = "Unknown"

                        if n.type == "newuser":
                            message = f"New Company Registered: {username}"
                        elif n.type == "paymentuser":
                            message = f"{username} made a payment"
                        else:
                            message = "Unknown notification type"

                        note.append({
                            'row': index,
                            'id': n.id,
                            'type': n.type,
                            'message': message,
                            'created_at': n.created_at,
                            'time_ago': timesince(n.created_at, now()) + " ago", 

                        })

                    return Response({
                        "status": {"code": status.HTTP_200_OK, "response": "success"},
                        "error": None,
                        "data": note,
                        "count": len(note), 
                    })

                else:
                    # ✅ Non-admin user — return permission denied
                    return Response({
                        "status": {"code": status.HTTP_403_FORBIDDEN, "response": "forbidden"},
                        "error": True,
                        "message": "You do not have permission to view notifications.",
                        "data": []
                    })

            except Exception as e:
                return Response({
                    "status": {"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "response": "failed"},
                    "error": True,
                    "message": str(e),
                })

    def delete(self, request, id=None):
        try:
            if id is not None:
                # Delete a specific notification
                notification = Notification.objects.get(id=id)
                notification.delete()
                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "message": "Notification deleted successfully"
                })
            else:
                # Delete all notifications
                op = request.user.id

                Notification.objects.filter(user_id=op).delete()
                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "message": "All notifications deleted successfully"
                })
        except ObjectDoesNotExist:
            return Response({
                "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                "error": True,
                "message": "Notification not found"
            })
        except Exception as e:
            return Response({
                "status": {"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "response": "failed"},
                "error": True,
                "message": str(e)
            })


    

class VendorAPIView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request, id=None):
        if id is not None:
            try:
                company = Vendor.objects.get(id=id)
                data = {
                    'id': company.id,
                    'vendorname': company.vendorname,
                    'phone': company.phone,
                    'email': company.email,
                    'address': company.address,
                    'gst': company.gst,
                    'address1': company.country,
                    'city': company.city,
                    'state': company.state,
                    'vendor_company_name': company.vendor_company_name,
                    'plan': company.plan,
                    'plan_details': company.plan_details,
                    'remarks': company.remarks,
                    'registered_date': company.registered_date,
                    'status': company.status,




                    'pincode': company.pincode

                }



                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": data
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })
        else:
            try:

                index = 0
                companies = []

                user_id = request.query_params.get('user_id')
                vendorname = request.query_params.get('vendorname', '').strip() 
                email = request.query_params.get('email', '').strip() 
                phone = request.query_params.get('phone', '').strip()  

                status_param = request.query_params.get('status', '').strip()

                if user_id:
                    vendors = Vendor.objects.filter(created_by_id=user_id)
                else:
                    vendors = Vendor.objects.filter(created_by_id=request.user.id)


                if vendorname:
                  
                    vendors = vendors.filter(vendorname__icontains=vendorname) 

                if email:
                  
                    vendors = vendors.filter(email__icontains=email) 
                if phone:
                  
                    vendors = vendors.filter(phone__icontains=phone) 
                if status_param:
                    try:
                        status_int = int(status_param)
                        if status_int in [1, 2]:
                            vendors = vendors.filter(status=status_int)
                    except ValueError:
                        pass 

                for company in vendors:
                    index += 1

                    companies.append({
                        'row': index,
                        'id': company.id,
                        'name': company.vendorname,
                        'email': company.email,
                        'phone': company.phone,
                        'address': company.address,
                        'pincode': company.pincode,
                        'gst': company.gst,
                        'status': company.status,
                        'user_id': company.user_id,




                    })

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": companies
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })

    def post(self, request):
        data = request.data

        try:

            name = data.get("username")
            email = data.get("email")
            phone = data.get("phone")
            address = data.get("address")
            # gst = data.get("gst")
            # pincode = data.get("pincode")
            address1 = data.get("address1")
            state = data.get("state")
            city = data.get("city")
            vendor_company_name = data.get("vendor_company_name")
            plan = data.get("plan")
            plan_details = data.get("plan_details")
            registered_date = data.get("registered_date")
            remarks = data.get("remarks")
            stat = data.get("status")






            password = name + "@123"
            
            hashed_password = make_password(password)

            # Create a new User
            datas = User(username=name, password=hashed_password, email=email)
            datas.save()

            # Fetch the User instance's ID
            user_instance = datas.id

            # Create a new Profile with the user_id
            profile_data = Profiles(
                name=name, 
                phone=phone, 
                role=2, 
                email=email, 
                address=address, 
                password=password, 
                user_id=user_instance, # Pass the user ID
                status = stat,
                # gstnumber = gst
            )
            profile_data.save()

            # Create a new Vendor with the user_id
            vendor_data = Vendor(
                vendorname=name, 
                phone=phone, 
                email=email, 
                # pincode=pincode,
                state=state,
                city=city,
                country=address1,
                # gst = gst,
                address=address, 
                vendor_company_name = vendor_company_name,
                plan = plan,
                plan_details= plan_details,
                registered_date = registered_date,
                remarks = remarks,
                user_id=user_instance,  # Pass the user ID
                created_by_id= request.user.id,
                status = stat
            )
            vendor_data.save()

            return Response({
                "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                "error": None,
                "message": "Vendor created successfully"
            })
        except KeyError as e:
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": f"Missing required field: {e}"
            })

    def put(self, request, id):
        data = request.data

        try:


            company = Vendor.objects.get(id=id)
            company.vendorname = data["name"]
            company.address = data["address"]
            company.email = data["email"]
            company.phone = data["phone"]
            # company.gst = data["gst"]
            # company.pincode = data["pincode"]
            company.country = data["address1"]
            company.state = data["state"]
            company.city = data["city"]
            # company.plan = data["plan"]
            # company.plan_details = data["plan_details"]
            # company.registered_date = data["registered_date"]
            # company.vendor_company_name = data["vendor_company_name"]
            company.status = data["status"]
            company.remarks = data["remarks"]





            company.save()

            companies = Vendor.objects.get(id=id)


            use = User.objects.get(id=companies.user_id)

            use.username = data["name"]
            use.email = data["email"]

            use.save()


            pro =Profiles.objects.get(user_id=companies.user_id)

            pro.name = data["name"]
            pro.email = data["email"]
            pro.gstnumber = data["gst"]
            pro.save()


            # ven = Vendor.objects.get(user_id=company.user_id)

            # ven.vendorname = data["name"]
            # ven.email = data["email"]
            # ven.address = data["address"]
            # ven.gst = data["gst"]
            # ven.pincode = data["pincode"]
            # ven.country = data["address1"]
            # ven.city = data["city"]
            # ven.state = data["state"]



            # ven.save()


            return Response({
                "status": {"code": status.HTTP_200_OK, "response": "success"},
                "error": None,
                "message": "Vendor updated successfully"
            })
        except ObjectDoesNotExist:
            return Response({
                "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                "error": True,
                "message": "No data found"
            })
        except Exception as e:
            print(e)
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": "Something went wrong"
            })

    def delete(self, request, id):
        if id is not None:
            try:
                company = Vendor.objects.get(id=id)
                company.delete()


                ven = Profiles.objects.get(user_id=company.user_id)
                ven.delete()

                use = User.objects.get(id=company.user_id)
                use.delete()

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "message": "Vendor deleted successfully"
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": None,
                    "message": "No data found"
                })
            

class GetproductAPIView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request, id=None):
        if id is not None:
            try:
                company = Vendor.objects.filter(id=id)
                data = {
                    'id': company.id,
                    'vendorname': company.vendorname,
                    'phone': company.phone,
                    'email': company.email,
                    'address': company.address
                }

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": data
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })
        else:
            try:

                ven = []
                unique_user_ids = set()

                # Fetch profiles with role=2
                fp = Profiles.objects.filter(role=2)

                # Loop through each profile
                for profile in fp:
                    er = Vendor.objects.filter(created_by_id=request.user.id,status=1)
                    
                    for vendor in er:
                        if vendor.user_id not in unique_user_ids:
                            ven.append({
                                'id': vendor.user_id,
                                'name': vendor.vendorname
                            })
                            # Mark this user_id as added
                            unique_user_ids.add(vendor.user_id)

                index = 0
                companies = []

                for company in Product.objects.filter(created_by_id=request.user.id,status=1):
                    index += 1

                    companies.append({
                        'row': index,
                        'id': company.id,
                        'name': company.name,
                        'vens': ven,
                        'specification': company.specification


                    })

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": companies
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })


class GetenquirysAPIView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request, id=None):
        if id is not None:
            try:
                company = Vendor.objects.filter(id=id)
                data = {
                    'id': company.id,
                    'vendorname': company.vendorname,
                    'phone': company.phone,
                    'email': company.email,
                    'address': company.address
                }

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": data
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })
        else:
            try:

                

                index = 0
                companies = []

                for company in Enquiry.objects.filter(created_by_id=request.user.id, expirestatus=2):
                    index += 1

                    

                    companies.append({
                        'row': index,
                        'id': company.id,
                        'auto_id' : '#ENQ-000'+str(company.auto_id),

                    })

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": companies
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })




class GetallenquiryAPIView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request, id=None):
        if id is not None:
            try:



                
                    data = {
                        'id': '2'
                        
                    }

                    return Response({
                        "status": {"code": status.HTTP_200_OK, "response": "success"},
                        "error": None,
                        "data": data
                    })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })
        else:
            try:

                

                
                op = request.user.id


                enquiry_id = []
                

                enquiries = Enquiry.objects.all()

                for enquiry in enquiries:
                    try:
                        vendor_data = enquiry.vendor

                        if isinstance(vendor_data, str):
                            vendor_list = json.loads(vendor_data)
                        else:
                            vendor_list = vendor_data

                        if str(op) in map(str, vendor_list):
                             enquiry_id.append({
                            'id': enquiry.id,
                            'auto_id' : '#ENQ-000'+str(enquiry.auto_id),
                            })

                            

                    except Exception as e:
                        print(f"Error in enquiry ID {enquiry.id}: {e}")
                  
                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": enquiry_id
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })
    

class GetenquiryAPIView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request, id=None):
        if id is not None:
            try:
                company = Vendor.objects.filter(id=id)
                data = {
                    'id': company.id,
                    'vendorname': company.vendorname,
                    'phone': company.phone,
                    'email': company.email,
                    'address': company.address
                }

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": data
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })
        else:
            try:
                index = 0
                companies = []

                

                enquiries = Enquiry.objects.filter(created_by_id=request.user.id, expirestatus=2)
                for company in enquiries:
                    has_status_4 = Vendorquote.objects.filter(enquiry_id=company.id, status=4).exists()

                    # Check if auction exists for this enquiry
                    auction_exists = Auction.objects.filter(en_id_id=company.id).exists()

                    # Append only if NO auction and NO vendorquote with status=4
                    if not auction_exists and not has_status_4:
                        index += 1
                        companies.append({
                            'row': index,
                            'id': company.id,
                            'auto_id': '#ENQ-000' + str(company.auto_id),
                        })
                 

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": companies
                })

            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })


def send_email_async(subject, message, recipient_list):
    """
    Function to send email asynchronously.
    """
    try:
        send_mail(subject, message, settings.EMAIL_HOST_USER, recipient_list, fail_silently=False)
    except Exception as e:
        print(f"Error sending email: {str(e)}")




# class EnquiryAPIView(APIView):
#     permission_classes = (IsAuthenticated,)
    


#     def get(self, request, id=None):
#         if id is not None:
#             try:
                

#                 company = Enquiry.objects.get(id=id)

#                 ven = []
#                 for vendor_id in company.vendor:  
#                     rp = Profiles.objects.get(user_id=vendor_id)
#                     ven.append({
#                         'id': rp.user_id,
#                         'name': rp.name
#                     })

#                 quan = []

#                 for u in company.quantity:
#                     quan.append({
#                         'quantity': u
                        
#                     })


#                 des = []

#                 for d in company.description:
#                     des.append({
#                         'description': d
                        
#                     })
                

#                 em = request.user.id
              


#                 try:
#                     wr = Vendorquote.objects.get(enquiry_id=id, vendor_id=em)
#                 except Vendorquote.DoesNotExist:
#                     wr = None


                
#                 rateperunits = []
#                 transportcost = []
#                 packingcost = []

#                 if wr is not None:
#                     for ww in wr.rateperUnit:
#                         rateperunits.append({
#                             'rate': ww
#                         })

#                     for uu in wr.transportCost:
#                         transportcost.append({
#                             'trans': uu
#                         })

#                     for aa in wr.packingCost:
#                         packingcost.append({
#                             'pack': aa
#                         })

#                 pro = []
#                 for product_id in company.product:  
#                     rp = Product.objects.get(id=product_id)
#                     pro.append({
#                         'id': rp.id,
#                         'name': rp.name,
#                         'specification': rp.specification,
#                         'quan': quan,
#                         'des' : des,
#                         'rate': rateperunits,
#                         'trans': transportcost,
#                         'pack': packingcost,


#                     })

                

                    
                   



                

#                 data = {
#                     'id': company.id,
#                     'unit': company.unit,
#                     'quantity': company.quantity,
#                     'endDate': company.end_date,
#                     'endTime': company.end_time,
#                     'location': company.deliverylocation,
#                     'deliveryDate': company.deliverydate,
#                     'vendor': ven,
#                     'product':pro,
                   
#                     # 'total': total,


                    
#                 }

#                 return Response({
#                     "status": {"code": status.HTTP_200_OK, "response": "success"},
#                     "error": None,
#                     "data": data
#                 })
#             except ObjectDoesNotExist:
#                 return Response({
#                     "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
#                     "error": True,
#                     "message": "No data found",
#                 })
class EnquiryAPIView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request, id=None):
        if id is not None:
            try:
                company = Enquiry.objects.get(id=id)

                # Vendor list
                ven = []
                for vendor_id in company.vendor:
                    rp = Profiles.objects.get(user_id=vendor_id)
                    ven.append({
                        'id': rp.user_id,
                        'name': rp.name
                    })

                # Quantity list
                quan = [{'quantity': q} for q in company.quantity]

                # Description list
                des = [{'description': d} for d in company.description]
                unit = [{'unit': u} for u in company.units]


                em = request.user.id  # Current vendor user

                # Get quote info if it exists
                try:
                    wr = Vendorquote.objects.get(enquiry_id=id, vendor_id=em)
                    rateperunits = [{'rate': rate} for rate in wr.rateperUnit or []]
                    transportcost = [{'trans': trans} for trans in wr.transportCost or []]
                    packingcost = [{'pack': pack} for pack in wr.packingCost or []]
                    gst = [{'gst': gst} for gst in wr.gst or []]

                except Vendorquote.DoesNotExist:
                    rateperunits = []
                    transportcost = []
                    packingcost = []
                    gst = []


                # Product info
                pro = []
                for product_id in company.product:
                    rp = Product.objects.get(id=product_id)


                    pro.append({
                        'id': rp.id,
                        'name': rp.name,
                        'specification': rp.specification,
                        'quan': quan,
                        'des': des,
                        'rate': rateperunits,
                        'trans': transportcost,
                        'pack': packingcost,
                        'gst': gst,
                        'unit': unit,


                    })


                profile = Profiles.objects.get(user_id=company.created_by_id)

                data = {
                    'id': company.id,
                    # 'unit': company.unit,
                    'quantity': company.quantity,
                    # 'unit': company.units,
                    'symbol': profile.alteremail2,
                    'endDate': company.end_date,
                    'endTime': company.end_time,
                    'location': company.deliverylocation,
                    'deliveryDate': company.deliverydate,
                    'vendor': ven,
                    'product': pro,
                    'des':des
                    
                }

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": data
                })

            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })

        else:
            






            try:
                rr = request.user.id

                companies = []
                wt = Profiles.objects.get(user_id=rr)



                if wt.role != 2:  
                    index = 0  
                    try:
                        payment = Payment.objects.get(user_id=rr)

                        if payment.payment_status == 'basicMonth' or payment.payment_status == 'statndardMonth' or payment.payment_status == 'premiumMonth':
                            if isinstance(payment.payment_date, datetime):
                                payment_date = payment.payment_date.date()
                            else:
                                payment_date = payment.payment_date

                            due_date = payment_date + timedelta(days=31)

                            print(due_date,"completed show me")
                            today = datetime.today().date()
                            state = "Dook" if today >= due_date else "Completed"

                        elif payment.payment_status == 'basicYear' or payment.payment_status == 'statndardYear' or payment.payment_status == 'premiumYear':
                            if isinstance(payment.payment_date, datetime):
                                payment_date = payment.payment_date.date()
                            else:
                                payment_date = payment.payment_date

                            due_date = payment_date + timedelta(days=365)
                            today = datetime.today().date()
                            state = "Dook" if today >= due_date else "Completed"

                        else:
                            state = payment.payment_status

                        print("Status:", state)

                    except ObjectDoesNotExist:
                        state = 'Pending'

                    
                    for company in Enquiry.objects.filter(created_by_id = rr):

                        try:
                            fe = Vendorquote.objects.get(enquiry_id=company.id, vendor_id=request.user)

                            stw = fe.status

                        except ObjectDoesNotExist:





                            st = '1'
                            stw = int(st)



                        pro = []
                        for product_id in company.product:
                            try:
                                rp = Product.objects.get(id=product_id)
                                pro.append({'id': rp.id, 'label': rp.name})
                            except Product.DoesNotExist:
                                continue

                        # Build quantity info
                        quan = [{'label': q} for q in company.quantity]

                        index += 1
                        companies.append({
                            'row': index,
                            'id': company.id,
                            'deliverydate': company.deliverydate,
                            'deliverylocation': company.deliverylocation,
                            'quantity': company.quantity,
                            'end_date': company.end_date,
                            'end_time': company.end_time,
                            'product' : pro,
                            'quantity' : quan,

                            'expirestatus': company.expirestatus,
                            'auto_id': '#ENQ-000'+str(company.auto_id),
                            'status' :stw

                        })

                    return Response({
                        "status": {"code": status.HTTP_200_OK, "response": "success"},
                        "error": None,
                        "data": companies,
                        "sta": state
                    })

                else:  # If role is 2, filter companies where 'rr' is in the vendor list
                    for company in Enquiry.objects.all():
                        if str(rr) in company.vendor:  # Check if 'rr' (user ID) is in the vendor list


                            try:
                                fe = Vendorquote.objects.get(enquiry_id=company.id, vendor_id=request.user)
                                der = fe.requote_date
                                stw = fe.status
                                

                            except ObjectDoesNotExist:



                                # print(type(sq))
                                der = '-----'

                                st = '1'
                                stw = int(st)
                            pro = []
                            for product_id in company.product:  
                                rp = Product.objects.get(id=product_id)
                                pro.append({
                                    'id': rp.id,
                                    'name': rp.name,
                                    'specification': rp.specification,
                                    'code': rp.code,

                                


                                })
                            quan = []

                            for u in company.quantity:
                                quan.append({
                                    'quantity': u
                                    
                                })
                            

                            companies.append({
                                'id': company.id,
                                'deliverydate': company.deliverydate,
                                'deliverylocation': company.deliverylocation,
                                'quantity': company.quantity,
                                'end_date': company.end_date,
                                'end_time': company.end_time,
                                'expirestatus': company.expirestatus,
                                'updated_at': der,
                                'product': pro,
                                'quantity': quan,
                                'status': stw,
                                'auto_id':  '#ENQ-000'+str(company.auto_id),



                            })
                            print(company.id, 'Vendor found in company:', company)

                    return Response({
                        "status": {"code": status.HTTP_200_OK, "response": "success"},
                        "error": None,
                        "data": companies
                    })

            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })



    def post(self, request):
        data = request.data

        try:

        

            enquiry_id = data.get('id')  # Safely get the 'id' from the dictionary


    
            # Check if the 'id' exists
            if enquiry_id is not None:

                enquiry = Enquiry.objects.get(id=enquiry_id) 

                enquiry.expirestatus = 2

                enquiry.save()

                return Response({
                        "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                        "error": None,
                        "message": "Enquiry status successfully"
                    })

            else:
                quantity = data.get('quantity')
                deliverydate = data.get('deliveryDate')
                end_date = data.get('enddate')
                end_time = data.get('endtime')
                deliverylocation = data.get('location')
                vendors = data.get('vendor') 
                # products = data.get('product') 
                max = data.get('max')

                vendors_list = vendors.split(',') if vendors else []
                product_json = data.get('product')  # this is a string
                product_data = json.loads(product_json)  # now it's a list of dicts

                products_list = [item['product'] for item in product_data]
                quantity_list = [item['quantity'] for item in product_data]
                unit_list = [item['unit'] for item in product_data]

                description_list = [item.get('description', '') for item in product_data]




                count  = Enquiry.objects.filter(created_by_id=request.user.id).count()


                if count == 0:
                    counts = 1
                else:
                    counts = count + 1

                data = Enquiry(created_by=request.user,auto_id=counts,updated_at = max,description= description_list,
                    end_date=end_date,end_time=end_time,units=unit_list,quantity=quantity_list, deliverydate=deliverydate, deliverylocation=deliverylocation, vendor=vendors_list, product=products_list)
                data.save()



                payment_status = 'Free'
                payment_amount = "0"
                try:
                    payment_obj = Payment.objects.get(user_id=request.user.id)
                except Payment.DoesNotExist:
                    payment_obj = None

                # If the Payment object doesn't exist, create a new one
                if not payment_obj:
                
                    pay = Payment(payment_amount=payment_amount, payment_status = payment_status,user_id=request.user.id, created_by_id=request.user.id)


                    pay.save()
                else:
                    pass


                for i in vendors_list:



                    company_id = request.user.id 


                    company_name = Profiles.objects.get(user_id=company_id)


                    da  = Profiles.objects.get(user_id=int(i))
                    mail_message = f'''Dear {da.name},

                    This enquiry is from: {company_name.email}


                    We have assigned a new enquiry to you. Kindly log in to your vendor portal to review and submit your quotation.

                    Access the portal here:
                    https://procure4less.com/signin/

                    Your login credentials are as follows:
                    Username: {da.name}
                    Password: {da.password}

                    Please review the enquiry and submit your quote at the earliest convenience. If you have any questions, feel free to reach out to our support team.

                    Thank you,
                    {company_name.servicename}
                    '''

                    subject = 'New Enquiry Request - Action Required'
                    recipient_list = [da.email]


                    thread = threading.Thread(target=send_email_async, args=(subject, mail_message, recipient_list))
                    thread.start()



                    

                   
                return Response({
                        "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                        "error": None,
                        "message": "Enquiry created successfully"
                    })
        except KeyError as e:
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": f"Missing required field: {e}"
            })
        

    def put(self, request, id):
        data = request.data

        try:
            quantity = data.get('quantity')
            deliverydate = data.get('deliveryDate')
            end_date = data.get('enddate')
            end_time = data.get('endtime')
            deliverylocation = data.get('location')
            vendors = data.get('vendor') 
            vendors_list = vendors.split(',') if vendors else []

            product_json = data.get('product')  # this is a string
            product_data = json.loads(product_json)  # now it's a list of dicts

            products_list = [item['product'] for item in product_data]
            quantity_list = [item['quantity'] for item in product_data]
            unit_list = [item['unit'] for item in product_data]

            description_list = [item.get('description', '') for item in product_data]

            data = Enquiry.objects.get(id=id)
            data.end_date = end_date
            data.end_time = end_time
            data.units = unit_list
            data.quantity= quantity_list
            data.deliverydate = deliverydate
            data.deliverylocation = deliverylocation
            data.vendor = vendors_list
            data.product = products_list
            data.description = description_list
            
            data.expirestatus = 1

            data.save()
            

            


            for i in vendors_list:



                company_id = request.user.id 

                company_name = Profiles.objects.get(user_id=company_id)




                da  = Profiles.objects.get(user_id=int(i))
                mail_message = f'''Dear {da.name},

                This enquiry is from: {company_name.email}


                We have updated an enquiry for you. Kindly log in to your vendor portal to review and submit your quotation.

                Access the portal here:
                https://procure4less.com/signin/

                Your login credentials are as follows:
                Username: {da.name}
                Password: {da.password}

                Please review the enquiry and submit your quote at the earliest convenience. If you have any questions, feel free to reach out to our support team.

                Thank you,
                {company_name.servicename}

                '''

                subject = 'Enquiry Update Request - Action Required'
                recipient_list = [da.email]



                thread = threading.Thread(target=send_email_asynce, args=(subject, mail_message, recipient_list))

                thread.start()
               

                
    
            return Response({
                "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                "error": None,
                "message": "Enquiry created successfully"
            })
        except KeyError as e:
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": f"Missing required field: {e}"
            })
        



def send_email_asynce(subject, message, recipient_list):
    """
    Function to send email asynchronously.
    """
    try:

        send_mail(subject, message, settings.EMAIL_HOST_USER, recipient_list, fail_silently=False)
    except Exception as e:
        print(f"Error sending email: {str(e)}")



        
def send_email_quote(subject, message, recipient_list):
    """
    Function to send email asynchronously.
    """
    try:
        send_mail(subject, message, settings.EMAIL_HOST_USER, recipient_list, fail_silently=False)
    except Exception as e:
        print(f"Error sending email: {str(e)}")

def send_email_requote(subject, message, recipient_list):
    """
    Function to send email asynchronously.
    """
    try:
        send_mail(subject, message, settings.EMAIL_HOST_USER, recipient_list, fail_silently=False)
    except Exception as e:
        print(f"Error sending email: {str(e)}")
class QuoteAPIView(APIView):
    permission_classes = (IsAuthenticated,)
    


    def get(self, request, id=None):
        if id is not None:
            try:
                

                company = Enquiry.objects.get(id=id)
                vendor_id = request.user.id  # Store vendor ID separately
                products = []  # Rename 'pro' to 'products' for clarity
                
                for product_id in company.product:
                    product = Product.objects.get(id=product_id)  # Get the Product instance
                    products.append({
                        'id': product.id,
                        'name': product.name
                    })

                # Use vendor_id instead of rp here
                op = Vendorquote.objects.get(enquiry_id=id, vendor_id=vendor_id)

                try:
                    requoteamount = op.requoteamount
                except ObjectDoesNotExist:
                    requoteamount = '---'

                if op.requoteamount != None:
                    amount = op.requoteamount

                else:
                    amount = op.totalAmount

                # if op.requoteamount:
                #     amount = op.requoteamount
                # else:
                #     amount = op.totalAmount



                data = {
                    'id': company.id,
                    # 'unit': company.units,
                    'quantity': company.quantity,
                    
                    'total': amount,
                    'product': products,
                }


                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": data
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })
        else:



            try:
                rr = request.user.id

                companies = []
                wt = Profiles.objects.get(user_id=rr)

                if wt.role != 2:  # If role is NOT 2, get all companies
                    index = 0  # Initialize index variable
                    for company in Enquiry.objects.all():
                        index += 1
                        companies.append({
                            'row': index,
                            'id': company.id,
                            'deliverydate': company.deliverydate,
                            'deliverylocation': company.deliverylocation,
                            'quantity': company.quantity,
                            'end_date': company.end_date,
                            'end_time': company.end_time,
                        })

                    return Response({
                        "status": {"code": status.HTTP_200_OK, "response": "success"},
                        "error": None,
                        "data": companies
                    })

                else:  # If role is 2, filter companies where 'rr' is in the vendor list
                    for company in Enquiry.objects.all():
                        if str(rr) in company.vendor:  # Check if 'rr' (user ID) is in the vendor list
                            companies.append({
                                'id': company.id,
                                'deliverydate': company.deliverydate,
                                'deliverylocation': company.deliverylocation,
                                'quantity': company.quantity,
                                'end_date': company.end_date,
                                'end_time': company.end_time,
                            })
                            print(company.id, 'Vendor found in company:', company)

                    return Response({
                        "status": {"code": status.HTTP_200_OK, "response": "success"},
                        "error": None,
                        "data": companies
                    })

            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })

    def post(self, request):
        data = request.data

        try:
            user_id = request.user.id
            enquiry_id = data.get('enid')
            status_val = data.get('status')
            enquiryid = data.get('enquiryid')
            reason = data.get('reason')

            product_json = data.get('product')
            product_data = json.loads(product_json) if product_json else []
            products_list = [item['product'] for item in product_data]
            rate_list = [item['ratePerUnit'] for item in product_data]
            trans_list = [item['transportCost'] for item in product_data]
            pack_list = [item['packingCost'] for item in product_data]
            total_list = [item['calculateTotal'] for item in product_data]
            gst_list = [item['gst'] for item in product_data]


            if not Vendorquote.objects.filter(vendor_id=user_id, enquiry_id=enquiry_id).exists():
                new_enquiry = Vendorquote(
                    status=status_val,
                    enquiry_id=enquiryid or enquiry_id,  # fallback
                    vendor_id=user_id,
                    reason=reason
                )
                new_enquiry.save()


                

                return Response({
                    "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                    "error": None,
                    "message": "Quote data created successfully"
                })

            else:
                try:
                    enquiry = Vendorquote.objects.get(enquiry_id=enquiry_id, vendor_id=user_id)
                    if enquiry.enquirystatus == 2:

                        enquiry.requoteamount = data.get('totalAmount')
                        enquiry.rateperUnit = rate_list
                        enquiry.packingCost = pack_list
                        enquiry.transportCost = trans_list
                        enquiry.gst = gst_list
                        enquiry.total = total_list

                    else:
                        enquiry.total = total_list
                        enquiry.totalAmount = data.get('totalAmount')
                        enquiry.rateperUnit = rate_list
                        enquiry.packingCost = pack_list
                        enquiry.gst = gst_list

                        enquiry.transportCost = trans_list
                        enquiry.product = products_list

                    enquiry.save()



                    quote_log = Quotelog(
                        rateperUnit=rate_list,
                        packingCost=pack_list,
                        transportCost = trans_list,
                        gst = gst_list,
                        totalAmount = data.get('totalAmount'),
                        requoteamount = data.get('totalAmount'),
                        total = total_list,

                        enquiry_id=enquiryid or enquiry_id,  # fallback
                        vendor_id=user_id,
                    )
                    quote_log.save()

                    return Response({
                        "status": {"code": status.HTTP_200_OK, "response": "success"},
                        "error": None,
                        "message": "Enquiry updated successfully"
                    })

                except Vendorquote.DoesNotExist:
                    return Response({
                        "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                        "error": True,
                        "message": "Enquiry not found for the given vendor."
                    })

        except KeyError as e:
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": f"Missing required field: {e}"
            })


    # def post(self, request):
    #     data = request.data

    #     try:
    #         user_id = request.user.id  # Get the current user's ID
    #         enquiry_id = data.get('enid')  # Get the enquiry ID from the request data




    #         status_val = data.get('status')  # Get the enquiry ID from the request data
    #         enquiryid = data.get('enquiryid')  # Get the enquiry ID from the request data
    #         reason = data.get('reason') 

    #         product_json = data.get('product')  # this is a string
    #         product_data = json.loads(product_json) 
    #         products_list = [item['product'] for item in product_data]
    #         rate_list = [item['ratePerUnit'] for item in product_data]
    #         trans_list = [item['transportCost'] for item in product_data]
    #         pack_list = [item['packingCost'] for item in product_data]
    #         total_list = [item['calculateTotal'] for item in product_data]

          


    #         if not Vendorquote.objects.filter(vendor_id=user_id, enquiry_id=enquiry_id).exists():
    #             new_enquiry = Vendorquote(
    #                 # product=products_list,
    #                 # rateperUnit=rate_list,
    #                 # packingCost=pack_list,
    #                 # transportCost=trans_list,
    #                 # total=total_list,
    #                 # totalAmount=data.get('totalAmount'),
    #                 status = int(status_val),
    #                 enquiry_id=int(enquiryid),
    #                 vendor_id=user_id,
    #                 reason = reason
    #             )

    #             new_enquiry.save()

    #             return Response({
    #                 "status": {"code": status.HTTP_201_CREATED, "response": "success"},
    #                 "error": None,
    #                 "message": "Quote data created successfully"
    #             })

    #         else:
    #             try:
    #                 enquiry = Vendorquote.objects.get(enquiry_id=enquiry_id, vendor_id=user_id)
    #                 from decimal import Decimal

    #                 bao = data.get('totalAmount')
    #                 if enquiry.enquirystatus == 2:
    #                     enquiry.requoteamount = data.get('totalAmount')
    #                     enquiry.rateperUnit = rate_list
    #                     enquiry.packingCost = pack_list
    #                     enquiry.transportCost = trans_list
    #                 else:
    #                     enquiry.total = data.get('totalAmount')

    #                     enquiry.rateperUnit = rate_list
    #                     enquiry.packingCost = pack_list
    #                     enquiry.transportCost = trans_list

    #                 enquiry.save()

    #                 return Response({
    #                     "status": {"code": status.HTTP_200_OK, "response": "success"},
    #                     "error": None,
    #                     "message": "Enquiry updated successfully"
    #                 })

    #             except Vendorquote.DoesNotExist:
    #                 return Response({
    #                     "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
    #                     "error": True,
    #                     "message": "Enquiry not found for the given vendor."
    #                 })

    #     except KeyError as e:
    #         return Response({
    #             "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
    #             "error": True,
    #             "message": f"Missing required field: {e}"
    #         })


    def put(self, request, id):
        data = request.data

        try:
            

            ven = data['vendor_id']
            quote = data['quote']


            print(quote)
            


            data = Vendorquote.objects.get(enquiry_id=id, vendor_id=ven)
            if quote == "quote":
                data.enquirystatus = 1
                data.status = 4 

                data.save()
                company_id = request.user.id 

                company_name = Profiles.objects.get(user_id=company_id)

                da  = Profiles.objects.get(user_id=ven)
                mail_message = f'''Dear {da.name},

                This enquiry is from: {company_name.email}


                We are pleased to inform you that your quotation for the enquiry has been accepted.

                You may click the link below to view the details:
                https://procure4less.com/signin/

                Thank you for your quotation and continued support.

                Best regards,
                {company_name.servicename}
                '''
                
                subject = 'Your Quotation Has Been Accepted'
                recipient_list = [da.email]

                # Sending email asynchronously using threading
                thread = threading.Thread(
                    target=send_email_quote,
                    args=(subject, mail_message, recipient_list)
                )
                thread.start()

            else:
                datas = Vendorquote.objects.get(enquiry_id=id, vendor_id=ven)
                datas.status = 5
                datas.enquirystatus = 2
                datas.requote_date = timezone.now() 


                company_id = request.user.id 

                company_name = Profiles.objects.get(user_id=company_id)

                da  = Profiles.objects.get(user_id=ven)
                mail_message = f'''Dear {da.name},

                This enquiry is from: {company_name.email}


                You are requested to review and submit your requote for the provided enquiry.

                Kindly click the link below to view the details and submit your requote:
                https://procure4less.com/signin/

                If you have any questions, please feel free to reach out to our team.

                Thank you,
                {company_name.servicename}
                '''

                subject = 'Request for Requote Submission'
                recipient_list = [da.email]



                # Sending email asynchronously using threading
                thread = threading.Thread(
                    target=send_email_requote,
                    args=(subject, mail_message, recipient_list)
                )
                thread.start()


                datas.save()
            

            



          
    
            return Response({
                "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                "error": None,
                "message": "Enquiry updated successfully"
            })
        except KeyError as e:
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": f"Missing required field: {e}"
            })
        

class QuotelistAPIView(APIView):
    permission_classes = (IsAuthenticated,)
    

    def get(self, request, id=None):
        if id is not None:
            try:
                company = Enquiry.objects.get(id=id)
                vendor_data = []

                for vendor_id in company.vendor:
                    auction = Auction.objects.filter(en_id_id=id).exists()
                    if auction:
                        auction_status = 1
                    else:
                        auction_status = 0

                    try:
                        
                        op = Vendorquote.objects.get(enquiry_id=id, vendor_id=vendor_id)
                        useid = op.vendor_id
                        requoteamount = op.requoteamount
                        amo = op.totalAmount
                        stm = op.status
                        stms = op.enquirystatus
                        reason = op.reason

                    except ObjectDoesNotExist:
                        useid = vendor_id
                        requoteamount = '---'
                        amo = '---'
                        st = '1'
                        stm = int(st)
                        sts = '0'
                        stms = int(sts)
                        reason = '---'

                    try:
                        val = User.objects.get(id=useid)
                        username = val.username
                        email = val.email
                    except User.DoesNotExist:
                        username = "Unknown"
                        email = "Unknown"

                    vendor_data.append({
                        'vendor_id': vendor_id,
                        'username': username,
                        'email': email,
                        'total': amo,
                        'en_id': company.id,
                        'status': stm,
                        'requote': stms,
                        'requoteamount': requoteamount,
                        'reason' : reason,
                        'originalenquirystatus': company.expirestatus,
                        'auction_status' : auction_status
                    })

                    

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": vendor_data
                })

            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })

        else:



            try:
                rr = request.user.id

                companies = []
                wt = Profiles.objects.get(user_id=rr)

                if wt.role != 2:  # If role is NOT 2, get all companies
                    index = 0  # Initialize index variable
                    for company in Enquiry.objects.all():
                        index += 1
                        companies.append({
                            'row': index,
                            'id': company.id,
                            'deliverydate': company.deliverydate,
                            'deliverylocation': company.deliverylocation,
                            'quantity': company.quantity,
                            'end_date': company.end_date,
                            'end_time': company.end_time,
                        })

                    return Response({
                        "status": {"code": status.HTTP_200_OK, "response": "success"},
                        "error": None,
                        "data": companies
                    })

                else:  # If role is 2, filter companies where 'rr' is in the vendor list
                    for company in Enquiry.objects.all():
                        if str(rr) in company.vendor:  # Check if 'rr' (user ID) is in the vendor list
                            companies.append({
                                'id': company.id,
                                'deliverydate': company.deliverydate,
                                'deliverylocation': company.deliverylocation,
                                'quantity': company.quantity,
                                'end_date': company.end_date,
                                'end_time': company.end_time,
                            })
                            print(company.id, 'Vendor found in company:', company)

                    return Response({
                        "status": {"code": status.HTTP_200_OK, "response": "success"},
                        "error": None,
                        "data": companies
                    })

            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })
            


def send_email_accquote(subject, message, recipient_list):
    """
    Function to send email asynchronously.
    """
    try:
        send_mail(subject, message, settings.EMAIL_HOST_USER, recipient_list, fail_silently=False)
    except Exception as e:
        print(f"Error sending email: {str(e)}")

class AllauctionAPIView(APIView):
    permission_classes = (IsAuthenticated,)
    


    def get(self, request, id=None):
        if id is not None:
            try:
                from datetime import datetime, timedelta
                from django.core.exceptions import ObjectDoesNotExist
                from rest_framework.response import Response
                from rest_framework import status
                data = []

                auc = Auction.objects.get(en_id_id=id)

                if auc.status == 1:
                    company = Message.objects.filter(enq_id_id=id).order_by('-message')
                else:
                    company = Message.objects.filter(enq_id_id=id).order_by('message')




                company = Message.objects.filter(enq_id_id=id).order_by('-message')

                rrr = request.user.id

                man = Profiles.objects.get(user_id=rrr)


                EN = Enquiry.objects.get(id=id)
                sym= Profiles.objects.get(user_id=EN.created_by_id)

                quan = []

                for u in EN.quantity:
                    quan.append({
                        'quantity': u
                        
                    })

                pro = []
                for product_id in EN.product:  
                    rp = Product.objects.get(id=product_id)
                    pro.append({
                        'id': rp.id,
                        'name': rp.name,
                       


                    })



                for i in company:

                    pe = User.objects.get(id=i.created_by_id )

                    # if i.created_by_id == rrr:
                    #     username = pe.username
                    # elif man.role == 0 or man.role == 1: 
                    #     username =  pe.username

                    # else:
                    #     username = "----"

                    username = pe.username

                    data.append({
                        'quan': quan,
                        'username': username,
                        'message': i.message,
                        'total': i.total,
                        'sto': i.status,
                        'enq_id_id': i.enq_id_id,
                        'created_by_id': i.created_by_id
                    })

                top = []
                sop = []

                for item in data:
                    ops = float(item['message'])  # <--- இங்கே மாற்றம்
                    # ops = int(item['message'])
                    top.append(ops)

                for item in data:
                    opss = float(item['total'])  # <--- இங்கே மாற்றம்
                    # opss = int(item['total'])  
                    sop.append(opss)

                amu = top[0]
                for e in top:
                    if e < amu:
                        amu = e

                abc = sop[0]
                for r in sop:
                    if r < abc:
                        abc = r

                print('Leat total amount', abc)

                        





                



                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": data,
                    "pro":pro,
                    "symbol":sym.alteremail2,
                    "quan":quan,
                    "auto_id": '#ENQ-000'+str(EN.auto_id),
                    "leastquoteamount" : abc,
                    "leastauctionamount": amu

                    
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })
        else:



            from datetime import datetime, timedelta
            from django.core.exceptions import ObjectDoesNotExist
            from rest_framework.response import Response
            from rest_framework import status

            try:

                rr = request.user.id

                companies = []
                current_date_and_time = datetime.now()  # Get

                for take in Enquiry.objects.all():



                    if str(rr) in take.vendor: 

                        try:

                            ve = Message.objects.get(created_by_id = str(rr), enq_id_id=take.id)
                        except ObjectDoesNotExist:
                            continue

                        try:
                            

                            company =  Auction.objects.get(en_id_id=ve.enq_id_id)
                        except ObjectDoesNotExist:
                            continue

                    
                        end_date = datetime.strptime(company.end_date, "%Y-%m-%d").date() if isinstance(company.end_date, str) else company.end_date
                        
                        end_time = datetime.strptime(company.end_time, "%H:%M").time() if isinstance(company.end_time, str) else company.end_time

                        auction_end = datetime.combine(end_date, end_time)
                        minutes = int(company.duration.split(":")[0])
                        total_minutes = minutes 

                    
                        auction_expiration = auction_end + timedelta(minutes=total_minutes)


                        # Determine auction statu
                        if current_date_and_time < auction_end:
                            sm = 'Not Started'
                        elif current_date_and_time < auction_expiration:
                            sm = 'Auction Ongoing'
                        else:
                            sm = 'Expired'


                        pro = []
                        if take.product:
                            for product_id in take.product:
                                try:
                                    rp = Product.objects.get(id=product_id)
                                    pro.append({
                                        'id': rp.id,
                                        'label': rp.name,
                                    })
                                except Product.DoesNotExist:
                                    continue

                        companies.append({
                            'id': take.id,
                            'status': sm,
                            'auto_id' : '#ENQ-000'+str(take.auto_id),
                            'auction_date' :company.created_at.date(),
                            'product': pro,
                            'expiration_time': auction_expiration.isoformat(),
                            "auction_end": auction_end.isoformat(),

                        })

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": companies
                })

            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })
            except Exception as e:  # Catching any other exceptions for debugging
                return Response({
                    "status": {"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "response": "failed"},
                    "error": True,
                    "message": str(e),
                })
            


    def put(self, request, id):
        data = request.data

        try:
            

            ven = data['vendor_id']


            


            data = Message.objects.get(enq_id_id=id, created_by_id=ven)

            data.status = 2

            
            
            
            company_id = request.user.id 


            company_name = Profiles.objects.get(user_id=company_id)
            da  = Profiles.objects.get(user_id=ven)

            mail_message = f'''Dear {da.name},

            We are pleased to inform you that your quote for the online auction has been accepted.
            
            The Purchase Order (PO) is currently under process and will be sent to you shortly.

            

            Thank you for your participation.

            Best regards,
            {company_name.servicename}
            '''

            subject = 'Your Online Auction Quote Has Been Accepted'
            recipient_list = [da.email]

            

            thread = threading.Thread(
                target=send_email_accquote,
                args=(subject, mail_message, recipient_list)
            )
            thread.start()

            

            data.save()
            

            



           
    
            return Response({
                "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                "error": None,
                "message": "Quote accepted successfully"
            })
        except KeyError as e:
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": f"Missing required field: {e}"
            })


class VendoractivestatusupdateAPIView(APIView):
    
    def put(self, request, id):
        

        try:
            


            ven = Vendor.objects.get(id=id)

            if ven.status == 1:
                ven.status = 2
                ven.save()

            else:
                ven.status = 1
                ven.save()
            

            pro = Profiles.objects.get(user_id=ven.user_id)

            if pro.status == 1:
                pro.status = 2
                pro.save()
            else:
                pro.status=1
                pro.save()

            



           
    
            return Response({
                "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                "error": None,
                "message": "Quote accepted successfully"
            })
        except KeyError as e:
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": f"Missing required field: {e}"
            })
class ProductactivestatusupdateAPIView(APIView):
    
    def put(self, request, id):
        

        try:
            


            ven = Product.objects.get(id=id)

            if ven.status == 1:
                ven.status = 2
                ven.save()

            else:
                ven.status = 1
                ven.save()
            

           

            



           
    
            return Response({
                "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                "error": None,
                "message": "Quote accepted successfully"
            })
        except KeyError as e:
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": f"Missing required field: {e}"
            })
class PHAPIView(APIView):
    permission_classes = (IsAuthenticated,)
   
    def get(self, request, id=None):

        from django.core.exceptions import ObjectDoesNotExist
        from rest_framework.response import Response
        from rest_framework import status

        CURRENCY_SYMBOLS = {
            "INR": "₹",   "USD": "$",    "EUR": "€",    "GBP": "£",
            "AED": "د.إ", "OMR": "ر.ع.", "KWD": "KD",   "BHD": ".د.ب",
            "SAR": "﷼",   "QAR": "ر.ق",  "SGD": "S$",   "AUD": "A$",
            "JPY": "¥",   "MYR": "RM",   "THB": "฿",    "ZAR": "R",
            "CAD": "C$",  "CHF": "Fr",   "HKD": "HK$",  "CNY": "¥",
            "KRW": "₩",   "BRL": "R$",   "EGP": "£",    "NGN": "₦",
            "PKR": "₨",   "BDT": "৳",    "LKR": "Rs",   "KES": "KSh",
            "TRY": "₺",   "ILS": "₪",    "PHP": "₱",    "IDR": "Rp",
        }

        PLAN_DETAILS = {
            "basicMonth":    ("One Month Basic Subscription",    "1 Month"),
            "standardMonth": ("One Month Standard Subscription", "1 Month"),
            "premiumMonth":  ("One Month Premium Subscription",  "1 Month"),
            "basicYear":     ("One Year Basic Subscription",     "1 Year"),
            "standardYear":  ("One Year Standard Subscription",  "1 Year"),
            "premiumYear":   ("One Year Premium Subscription",   "1 Year"),
        }

        # ── SINGLE RECORD ──────────────────────────────────────────
        if id is not None:
            try:
                company = Paymenthistory.objects.get(id=id)
                vendor  = Profiles.objects.get(user_id=company.user_id)

                plan    = company.payment_status
                no, yes = PLAN_DETAILS.get(plan, ("Subscription", "N/A"))

                # ✅ DB amount = final amount (GST already included for India)
                # Example: India → 824.82, Oman → 2.87, USA → 8.40
                er = float(company.payment_amount) if company.payment_amount else 0.00

                # ✅ Currency from vendor profile
                currency    = vendor.alteremail1 if vendor.alteremail1 else "INR"
                curr_symbol = (
                    vendor.alteremail2
                    if vendor.alteremail2
                    else CURRENCY_SYMBOLS.get(currency, currency)
                )

                # ✅ Invoice GST breakdown
                # India: DB = 824.82 (GST included) → show breakdown
                #        er_before_gst = 824.82 / 1.18 = 699
                #        gst_amount    = 824.82 - 699 = 125.82
                # Others: DB = 2.87 → no GST row
                if currency == "INR":
                    er_before_gst = round(er / 1.18, 2)   # 699.00
                    gst_amount    = round(er - er_before_gst, 2)  # 125.82
                    total_payable = er                      # 824.82
                    show_gst      = True
                else:
                    er_before_gst = er
                    gst_amount    = 0
                    total_payable = er
                    show_gst      = False

                # ✅ Format date
                payment_date = ""
                if company.payment_date:
                    try:
                        payment_date = company.payment_date.strftime("%Y-%m-%d")
                    except Exception:
                        payment_date = str(company.payment_date)

                data = {
                    'id':              company.id,
                    'amount':          er,
                    'date':            payment_date,       # "2025-09-07"
                    'name':            vendor.name,
                    'email':           vendor.email,
                    'gst':             vendor.gstnumber,
                    'yes':             yes,                # "1 Month"
                    'no':              no,                 # "One Month Basic Subscription"
                    'er':              er_before_gst,      # 699.00 (before GST) for India
                                                           # 2.87 (final) for others
                    'totalamount':     er,
                    'currency':        currency,           # "INR" / "OMR" / "USD"
                    'currency_symbol': curr_symbol,        # "₹" / "ريال" / "$"
                    'gst_amount':      gst_amount,         # 125.82 for India, 0 for others
                    'total_payable':   total_payable,      # 824.82 for India, 2.87 for others
                    'show_gst':        show_gst,           # True for India, False for others
                }

                return Response({
                    "status": {"code": 200, "response": "success"},
                    "error":  None,
                    "data":   data,
                })

            except Paymenthistory.DoesNotExist:
                return Response({
                    "status":  {"code": 404, "response": "failed"},
                    "error":   True,
                    "message": "Payment history not found",
                }, status=404)

            except Profiles.DoesNotExist:
                return Response({
                    "status":  {"code": 404, "response": "failed"},
                    "error":   True,
                    "message": "Vendor profile not found",
                }, status=404)

            except Exception as e:
                return Response({
                    "status":  {"code": 500, "response": "failed"},
                    "error":   True,
                    "message": str(e),
                }, status=500)

        # ── LIST ───────────────────────────────────────────────────
        else:
            try:
          
                companies = []
                qp = Profiles.objects.get(user_id=request.user.id)

                if qp.role == 1:
                    wp = Paymenthistory.objects.all().order_by('-id')
                else:
                    wp = Paymenthistory.objects.filter(
                        created_by_id=request.user.id
                    ).order_by('-id')

                for company in wp:
                    try:
                        from django.core.exceptions import ObjectDoesNotExist
                        from rest_framework.response import Response
                        from rest_framework import status
                        wu = Profiles.objects.get(user_id=company.user_id)

                        currency    = wu.alteremail1 if wu.alteremail1 else "INR"
                        curr_symbol = (
                            wu.alteremail2
                            if wu.alteremail2
                            else CURRENCY_SYMBOLS.get(currency, currency)
                        )

                        # ✅ DB amount = already final (no GST calculation needed)
                        er = float(company.payment_amount) if company.payment_amount else 0.00

                        # ✅ Format date
                        payment_date = ""
                        if company.payment_date:
                            try:
                                payment_date = company.payment_date.strftime("%Y-%m-%d")
                            except Exception:
                                payment_date = str(company.payment_date)

                        companies.append({
                            'id':              company.id,
                            'amount':          er,           # final amount (824.82 or 2.87)
                            'total_payable':   er,           # same — already final in DB
                            'currency':        currency,
                            'currency_symbol': curr_symbol,
                            'date':            payment_date,
                            'name':            wu.name,
                        })

                    except Profiles.DoesNotExist:
                        continue

                return Response({
                    "status": {"code": 200, "response": "success"},
                    "error":  None,
                    "data":   companies,
                })

            except Profiles.DoesNotExist:
                return Response({
                    "status":  {"code": 404, "response": "failed"},
                    "error":   True,
                    "message": "No data found",
                }, status=404)

            except Exception as e:
                return Response({
                    "status":  {"code": 500, "response": "failed"},
                    "error":   True,
                    "message": str(e),
                }, status=500)
# class PHAPIView(APIView):
#     permission_classes = (IsAuthenticated,)

#     def get(self, request, id=None):
#         if id is not None:
#             try:
#                 from django.core.exceptions import ObjectDoesNotExist
#                 from rest_framework.response import Response
#                 from rest_framework import status

#                 company = Paymenthistory.objects.get(id=id)
#                 vendor  = Profiles.objects.get(user_id=company.user_id)

#                 # ✅ Currency symbol fallback map
#                 CURRENCY_SYMBOLS = {
#                     "INR": "₹",   "USD": "$",    "EUR": "€",    "GBP": "£",
#                     "AED": "د.إ", "OMR": "ر.ع.", "KWD": "KD",   "BHD": ".د.ب",
#                     "SAR": "﷼",   "QAR": "ر.ق",  "SGD": "S$",   "AUD": "A$",
#                     "JPY": "¥",   "MYR": "RM",   "THB": "฿",    "ZAR": "R",
#                     "CAD": "C$",  "CHF": "Fr",   "HKD": "HK$",  "CNY": "¥",
#                     "KRW": "₩",   "BRL": "R$",   "EGP": "£",    "NGN": "₦",
#                     "PKR": "₨",   "BDT": "৳",    "LKR": "Rs",   "KES": "KSh",
#                     "TRY": "₺",   "ILS": "₪",    "PHP": "₱",    "IDR": "Rp",
#                 }

#                 # ✅ Plan details
#                 PLAN_DETAILS = {
#                     "basicMonth":    ("One Month Basic Subscription",    "1 Month"),
#                     "standardMonth": ("One Month Standard Subscription", "1 Month"),
#                     "premiumMonth":  ("One Month Premium Subscription",  "1 Month"),
#                     "basicYear":     ("One Year Basic Subscription",     "1 Year"),
#                     "standardYear":  ("One Year Standard Subscription",  "1 Year"),
#                     "premiumYear":   ("One Year Premium Subscription",   "1 Year"),
#                 }

#                 plan = company.payment_status
#                 no, yes = PLAN_DETAILS.get(plan, ("Subscription", "N/A"))

#                 # ✅ Actual amount from DB
#                 er = float(company.payment_amount) if company.payment_amount else 0.00

#                 # ✅ Currency from vendor profile
#                 # alteremail1 = currency code (INR / OMR / USD)
#                 # alteremail2 = currency symbol (₹ / ريال / $)
#                 currency = vendor.alteremail1 if vendor.alteremail1 else "INR"

#                 # alteremail2-ல் symbol இருந்தா use பண்ணு, இல்லன்னா map-இல் இருந்து எடு
#                 curr_symbol = (
#                     vendor.alteremail2
#                     if vendor.alteremail2
#                     else CURRENCY_SYMBOLS.get(currency, currency)
#                 )

#                 # ✅ GST only for India (INR)
#                 # India: er = INR amount WITHOUT GST (699, 999, 1299...)
#                 # DB-ல் store ஆனது GST இல்லாம — இங்க add பண்றோம்
#                 gst_amount    = 0
#                 total_payable = er      # DB amount already final (824.82)
#                 show_gst      = False 

#                 # ✅ Format date: 2025-09-07
#                 payment_date = ""
#                 if company.payment_date:
#                     try:
#                         payment_date = company.payment_date.strftime("%Y-%m-%d")
#                     except Exception:
#                         payment_date = str(company.payment_date)

#                 data = {
#                     'id':              company.id,
#                     'amount':          company.payment_amount,
#                     'date':            payment_date,      # "2025-09-07"
#                     'name':            vendor.name,
#                     'email':           vendor.email,
#                     'gst':             vendor.gstnumber,
#                     'yes':             yes,               # "1 Month"
#                     'no':              no,                # "One Month Basic Subscription"
#                     'er':              er,                # base amount (699 or 2.87)
#                     'totalamount':     er,                # same as er (before GST)
#                     'currency':        currency,          # "INR" / "OMR" / "USD"
#                     'currency_symbol': curr_symbol,       # "₹" / "ريال" / "$"
#                     'gst_amount':      gst_amount,        # 125.82 for INR, 0 for others
#                     'total_payable':   total_payable,     # 824.82 for INR, 2.87 for OMR
#                     'show_gst':        show_gst,          # True for INR, False for others
#                 }

#                 return Response({
#                     "status": {"code": 200, "response": "success"},
#                     "error":  None,
#                     "data":   data,
#                 })

#             except Paymenthistory.DoesNotExist:
#                 return Response({
#                     "status":  {"code": 404, "response": "failed"},
#                     "error":   True,
#                     "message": "Payment history not found",
#                 }, status=404)

#             except Profiles.DoesNotExist:
#                 return Response({
#                     "status":  {"code": 404, "response": "failed"},
#                     "error":   True,
#                     "message": "Vendor profile not found",
#                 }, status=404)

#             except Exception as e:
#                 return Response({
#                     "status":  {"code": 500, "response": "failed"},
#                     "error":   True,
#                     "message": str(e),
#                 }, status=500)
#        # ============================================================
# # Backend — PHAPIView (list part)
# # ============================================================

#         else:
#             from django.core.exceptions import ObjectDoesNotExist
#             from rest_framework.response import Response
#             from rest_framework import status

#             try:
#                 companies = []
#                 qp = Profiles.objects.get(user_id=request.user.id)

#                 if qp.role == 1:
#                     wp = Paymenthistory.objects.all()
#                 else:
#                     wp = Paymenthistory.objects.filter(created_by_id=request.user.id)

#                 CURRENCY_SYMBOLS = {
#                     "INR": "₹",   "USD": "$",    "EUR": "€",    "GBP": "£",
#                     "AED": "د.إ", "OMR": "ر.ع.", "KWD": "KD",   "BHD": ".د.ب",
#                     "SAR": "﷼",   "QAR": "ر.ق",  "SGD": "S$",   "AUD": "A$",
#                     "JPY": "¥",   "MYR": "RM",   "THB": "฿",    "ZAR": "R",
#                     "CAD": "C$",  "CHF": "Fr",   "HKD": "HK$",  "CNY": "¥",
#                     "KRW": "₩",   "BRL": "R$",   "EGP": "£",    "NGN": "₦",
#                     "PKR": "₨",   "BDT": "৳",    "LKR": "Rs",   "KES": "KSh",
#                     "TRY": "₺",   "ILS": "₪",    "PHP": "₱",    "IDR": "Rp",
#                 }

#                 for company in wp:
#                     try:
#                         wu = Profiles.objects.get(user_id=company.user_id)

#                         # ✅ Currency code — alteremail1
#                         currency = wu.alteremail1 if wu.alteremail1 else "INR"

#                         # ✅ Currency symbol — alteremail2 (fallback to map)
#                         curr_symbol = (
#                             wu.alteremail2
#                             if wu.alteremail2
#                             else CURRENCY_SYMBOLS.get(currency, currency)
#                         )

#                         # ✅ Amount from DB
#                         er = float(company.payment_amount) if company.payment_amount else 0.00
                        

#                         # ✅ GST only for INR
#                         if currency == "INR":
#                             gst_amount    = round(er * 0.18, 2)
#                             total_payable = round(er + gst_amount, 2)
#                         else:
#                             gst_amount    = 0
#                             total_payable = er

#                         # ✅ Format date
#                         payment_date = ""
#                         if company.payment_date:
#                             try:
#                                 payment_date = company.payment_date.strftime("%Y-%m-%d")
#                             except Exception:
#                                 payment_date = str(company.payment_date)

#                         companies.append({
#                             'id':              company.id,
#                             'amount':          er,              # base amount
#                             'total_payable':   total_payable,   # with GST if INR
#                             'currency':        currency,         # "INR" / "OMR"
#                             'currency_symbol': curr_symbol,      # "₹" / "ريال"
#                             'date':            payment_date,     # "2025-09-07"
#                             'name':            wu.name,
#                         })

#                     except Profiles.DoesNotExist:
#                         continue  # profile இல்லன்னா skip பண்ணு

#                 return Response({
#                     "status": {"code": 200, "response": "success"},
#                     "error":  None,
#                     "data":   companies,
#                 })

#             except ObjectDoesNotExist:
#                 return Response({
#                     "status":  {"code": 404, "response": "failed"},
#                     "error":   True,
#                     "message": "No data found",
#                 }, status=404)

#             except Exception as e:
#                 return Response({
#                     "status":  {"code": 500, "response": "failed"},
#                     "error":   True,
#                     "message": str(e),
#                 }, status=500)
class QuotelogAPIView(APIView):
    permission_classes = (IsAuthenticated,)
    


    def get(self, request, id=None):
        if id is not None:
            try:
                from datetime import datetime, timedelta
                from django.core.exceptions import ObjectDoesNotExist
                from rest_framework.response import Response
                from rest_framework import status

                vendor_id = request.GET.get('vendor_id')

                logs = []
                quotelog = Quotelog.objects.filter(enquiry_id=id, vendor_id=vendor_id)
                EN = Enquiry.objects.get(id=id)

                quan = []
                for u in EN.quantity:
                    quan.append([
                        u
                    ])

                pro = []
                for product_id in EN.product:
                    rp = Product.objects.get(id=product_id)
                    pro.append([
                      
                        rp.name,
                    ])

                for i, log in enumerate(quotelog):
                    logs.append({
                        'id': i + 1,
                        'date': str(log.created_at.date()) if log.created_at else '',
                        'amount': log.totalAmount if log.totalAmount else '',

                        'rateperunit': log.rateperUnit if isinstance(log.rateperUnit, list) else [log.rateperUnit],
                        'transportcost': log.transportCost if isinstance(log.transportCost, list) else [log.transportCost],
                        'packingcost': log.packingCost if isinstance(log.packingCost, list) else [log.packingCost],
                        'total': log.total if isinstance(log.total, list) else [log.total],

                        'gst': log.gst if isinstance(log.gst, list) else [log.gst],
                        'product': pro,
                        'quantity': quan,




                        # 'packing_cost': log.packing_cost if hasattr(log, 'packing_cost') else '',
                        # 'subtotal': log.subtotal if hasattr(log, 'subtotal') else '',
                        # 'total': log.total if hasattr(log, 'total') else '',
                    })

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "logs": logs,
                 
                })

            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })

        else:



            from datetime import datetime, timedelta
            from django.core.exceptions import ObjectDoesNotExist
            from rest_framework.response import Response
            from rest_framework import status

            try:
                companies = []
                user_id = request.user.id

                try:
                    profile = Profiles.objects.get(user_id=user_id)
                except Profiles.DoesNotExist:
                    return Response({
                        "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                        "error": True,
                        "message": "User profile not found.",
                    })

                if profile.role == 0:
                    vendors = Vendor.objects.filter(created_by_id=profile.user_id)
                    tickets = Ticket.objects.filter(created_by_id__in=vendors.values_list('user_id', flat=True))
                else:
                    tickets = Ticket.objects.filter(created_by_id=user_id)

                for ticket in tickets:
                    try:
                        enquiry = Enquiry.objects.get(id=ticket.en_id_id)
                    except Enquiry.DoesNotExist:
                        continue  # Skip if Enquiry not found

                    companies.append({
                        "id": ticket.id,
                        "date": ticket.created_at.date(),
                        "auto_id": '#ENQ-000'+str(enquiry.auto_id),
                        "subject": ticket.subject,
                        "description": ticket.description,
                        "en_id": ticket.en_id_id,
                        "status": ticket.status,
                    })

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": companies
                })

            except Exception as e:
                return Response({
                    "status": {"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "response": "failed"},
                    "error": True,
                    "message": str(e),
                })


class AuctionlogAPIView(APIView):
    permission_classes = (IsAuthenticated,)
    


    def get(self, request, id=None):
        if id is not None:
            try:
                from datetime import datetime, timedelta
                from django.core.exceptions import ObjectDoesNotExist
                from rest_framework.response import Response
                from rest_framework import status

                vendor_name = request.GET.get('vendor_name')

                logs = []
                quotelog = Auctionlog.objects.filter(enq_id_id=id, username=vendor_name)

                

                for i, log in enumerate(quotelog):
                    logs.append({
                        'id': i + 1,
                      
                        'amount': log.message,
                        'percentage': log.percentage
                    })

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "logs": logs,
                 
                })

            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })

        else:



            from datetime import datetime, timedelta
            from django.core.exceptions import ObjectDoesNotExist
            from rest_framework.response import Response
            from rest_framework import status

            try:
                companies = []
                user_id = request.user.id

                try:
                    profile = Profiles.objects.get(user_id=user_id)
                except Profiles.DoesNotExist:
                    return Response({
                        "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                        "error": True,
                        "message": "User profile not found.",
                    })

                if profile.role == 0:
                    vendors = Vendor.objects.filter(created_by_id=profile.user_id)
                    tickets = Ticket.objects.filter(created_by_id__in=vendors.values_list('user_id', flat=True))
                else:
                    tickets = Ticket.objects.filter(created_by_id=user_id)

                for ticket in tickets:
                    try:
                        enquiry = Enquiry.objects.get(id=ticket.en_id_id)
                    except Enquiry.DoesNotExist:
                        continue  # Skip if Enquiry not found

                    companies.append({
                        "id": ticket.id,
                        "date": ticket.created_at.date(),
                        "auto_id": '#ENQ-000'+str(enquiry.auto_id),
                        "subject": ticket.subject,
                        "description": ticket.description,
                        "en_id": ticket.en_id_id,
                        "status": ticket.status,
                    })

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": companies
                })

            except Exception as e:
                return Response({
                    "status": {"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "response": "failed"},
                    "error": True,
                    "message": str(e),
                })








class TicketAPIView(APIView):
    permission_classes = (IsAuthenticated,)
    


    def get(self, request, id=None):
        if id is not None:
            try:
                from datetime import datetime, timedelta
                from django.core.exceptions import ObjectDoesNotExist
                from rest_framework.response import Response
                from rest_framework import status

                val = request.query_params.get('val')
                
                if val == "0":
                    # Return ticket history logs
                    logs = []
                    ticket = Ticket.objects.get(id=id)
                    ticket_logs = Ticketlog.objects.filter(ticket_id_id=ticket.id)

                    for log in ticket_logs:
                        profile = Profiles.objects.get(user_id=log.created_by_id)
                        logs.append({
                            'sender': profile.name,
                            'date': log.created_at.date(),
                            'description': log.description
                        })

                    return Response({
                        "status": {"code": status.HTTP_200_OK, "response": "success"},
                        "error": None,
                        "logs": logs
                    })
                else:



                
                    company = Ticket.objects.get(id=id)
                    data = {
                    'id': company.id,
                    'enid': company.en_id_id,
                    'description': company.description,
                    'subject': company.subject,




                    }

                    return Response({
                        "status": {"code": status.HTTP_200_OK, "response": "success"},
                        "error": None,
                        "data": data
                    })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })
        else:



            from datetime import datetime, timedelta
            from django.core.exceptions import ObjectDoesNotExist
            from rest_framework.response import Response
            from rest_framework import status

            try:
                companies = []
                user_id = request.user.id

                try:
                    profile = Profiles.objects.get(user_id=user_id)
                except Profiles.DoesNotExist:
                    return Response({
                        "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                        "error": True,
                        "message": "User profile not found.",
                    })

                if profile.role == 0:
                    vendors = Vendor.objects.filter(created_by_id=profile.user_id)
                    tickets = Ticket.objects.filter(created_by_id__in=vendors.values_list('user_id', flat=True))
                else:
                    tickets = Ticket.objects.filter(created_by_id=user_id)

                for ticket in tickets:
                    try:
                        enquiry = Enquiry.objects.get(id=ticket.en_id_id)
                    except Enquiry.DoesNotExist:
                        continue  # Skip if Enquiry not found

                    companies.append({
                        "id": ticket.id,
                        "date": ticket.created_at.date(),
                        "auto_id": '#ENQ-000'+str(enquiry.auto_id),
                        "subject": ticket.subject,
                        "description": ticket.description,
                        "en_id": ticket.en_id_id,
                        "status": ticket.status,
                    })

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": companies
                })

            except Exception as e:
                return Response({
                    "status": {"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "response": "failed"},
                    "error": True,
                    "message": str(e),
                })




    def post(self, request):
        data = request.data

        try:

        

            subject = data.get('subject')
            description = data.get('description')
            enid = data.get('enid')
                
            data = Ticket(created_by=request.user,
                subject=subject,description=description,en_id_id=enid)
            data.save()


            ticket_instance = data.id

            dataw = Ticketlog(created_by=request.user,
                description=description,ticket_id_id=ticket_instance)
            dataw.save()





                # book = Enquiry.objects.get(id=enid)
                # for i in book.vendor:

                #     da  = Profiles.objects.get(user_id=int(i))
                #     mail_message = f'Hai Sir, New online Auction add kindly check and quote  http://pearl.pearlpackagingindia.com/'

                #     subject = 'Auction email from Pearl cost management system'
                #     recipient_list = [da.email]


                    

                #     # Sending email asynchronously using threading
                #     thread = threading.Thread(target=send_email_async, args=(subject, mail_message, recipient_list))
                #     thread.start()
            return Response({
                    "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                    "error": None,
                    "message": "Ticket created successfully"
                })
        except KeyError as e:
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": f"Missing required field: {e}"
            })
        

    def put(self, request, id):
        data = request.data
        sta = data.get('status')
        description = data.get('message')
        val = data.get('value')

        if val == 0:

            rt = Ticket.objects.get(id=id)
            # rt.description = description
            rt.status = sta
            rt.save()

            dataw = Ticketlog(
                created_by=request.user,
                description=description,
                ticket_id_id=id
            )
            dataw.save()

            return Response({
                "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                "error": None,
                "message": "Reply successfully"
            })

        else:
            try:
                subject = data.get('subject')
                description = data.get('description')
                enid = data.get('enid')


                rt = Ticket.objects.get(id=id)
                rt.description = description
                rt.subject = subject
                rt.en_id_id = enid
                rt.save()

                return Response({
                    "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                    "error": None,
                    "message": "Ticket updated successfully"
                })

            except KeyError as e:
                return Response({
                    "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                    "error": True,
                    "message": f"Missing required field: {e}"
                })    



class AuctionAPIView(APIView):
    permission_classes = (IsAuthenticated,)
    


    def get(self, request, id=None):
        if id is not None:
            try:
                from datetime import datetime, timedelta
                from django.core.exceptions import ObjectDoesNotExist
                from rest_framework.response import Response
                from rest_framework import status
                
                company = Auction.objects.get(id=id)




                

                data = {
                    'id': company.id,
                    'duration': company.duration,
                    'endDate': company.end_date,
                    'endTime': company.end_time,
                    'enq_id': company.en_id_id,
                 


                    
                }

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": data
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })
        else:



            from datetime import datetime, timedelta
            from django.core.exceptions import ObjectDoesNotExist
            from rest_framework.response import Response
            from rest_framework import status
            rr = request.user.id
            try:
                payment = Payment.objects.get(user_id=rr)

                if payment.payment_status == 'basicMonth' or payment.payment_status == 'statndardMonth' or payment.payment_status == 'premiumMonth':

                    if isinstance(payment.payment_date, datetime):
                        payment_date = payment.payment_date.date()
                    else:
                        payment_date = payment.payment_date

                    due_date = payment_date + timedelta(days=31)
                    today = datetime.today().date()
                    state = "Dook" if today >= due_date else "Completed"

                elif payment.payment_status == 'basicYear' or payment.payment_status == 'standardYear' or payment.payment_status == 'premiumYear':

                    if isinstance(payment.payment_date, datetime):
                        payment_date = payment.payment_date.date()
                    else:
                        payment_date = payment.payment_date

                    due_date = payment_date + timedelta(days=365)
                    today = datetime.today().date()
                    state = "Dook" if today >= due_date else "Completed"

                else:
                    state = payment.payment_status

                print("Status:", state)

            except ObjectDoesNotExist:
                state = 'Pending'

            try:
                companies = []
                current_date_and_time = datetime.now()  # Get the current date and time

                user_id = request.query_params.get('user_id')


                if user_id:
                    erpo = Auction.objects.filter(created_by_id=user_id)


                else:
                    erpo = Auction.objects.filter(created_by_id=request.user.id)


                for company in erpo:

                    end_date = datetime.strptime(company.end_date, "%Y-%m-%d").date() if isinstance(company.end_date, str) else company.end_date
                    
                    end_time = datetime.strptime(company.end_time, "%H:%M").time() if isinstance(company.end_time, str) else company.end_time

                    auction_end = datetime.combine(end_date, end_time)

                    minutes = int(company.duration.split(":")[0])
                    total_minutes = minutes 

                    auction_expiration = auction_end + timedelta(minutes=total_minutes)


                    if current_date_and_time < auction_end:
                        sm = 'Not Started'
                    elif current_date_and_time < auction_expiration:
                        sm = 'Auction Ongoing'
                    else:
                        sm = 'Expired'


                    ery =Enquiry.objects.get(id=company.en_id_id)

                    pro = []
                    if ery.product:
                        for product_id in ery.product:
                            try:
                                rp = Product.objects.get(id=product_id)
                                pro.append({
                                    'id': rp.id,
                                    'label': rp.name,
                                })
                            except Product.DoesNotExist:
                                continue

                    companies.append({
                        'id': company.en_id_id,
                        'status': sm,
                        'flag' : company.status,
                        'date' : company.created_at,
                        'ids': company.id,
                        'auto_id': '#ENQ-000'+str(ery.auto_id),
                        'expiration_time': auction_expiration.isoformat(),
                        "auction_end": auction_end.isoformat(),
                        'auction_date' :company.created_at.date(),
                        'product': pro,
                    })

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": companies,
                    "state" : state

                })

            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })
            except Exception as e:  # Catching any other exceptions for debugging
                return Response({
                    "status": {"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "response": "failed"},
                    "error": True,
                    "message": str(e),
                })




    def post(self, request):
        data = request.data

        try:
            enquiry_id = data.get('id')  # Safely get the 'id' from the dictionary
            end_date = data.get('enddate')
            end_time = data.get('endtime')
            enid = data.get('enid')
            duration = data.get('duration')

            # Save Auction
            auction = Auction(
                created_by=request.user,
                end_date=end_date,
                end_time=end_time,
                en_id_id=enid,
                duration=duration
            )
            auction.save()

            vendor_quotes = Vendorquote.objects.filter(enquiry_id=enid)
            for quote in vendor_quotes:
                if quote.status == 3:
                    continue  # Skip status 3

                # Status 2: try requoteamount first, fallback to totalAmount
                if quote.status == 2:
                    if quote.requoteamount is not None:
                        amount = int(float(quote.requoteamount))
                    elif quote.totalAmount is not None:
                        amount = int(float(quote.totalAmount))  # ✅ fallback
                    else:
                        continue  # no usable value
                else:
                    if quote.totalAmount is not None:
                        amount = int(float(quote.totalAmount))
                    else:
                        continue


                print(amount, '<<< Converted amount for message')

                # Get vendor username
                try:
                    val = User.objects.get(id=quote.vendor_id)
                    username = val.username
                except User.DoesNotExist:
                    username = "Unknown"

                # Create Message entry
                message = Message(
                    message=amount,
                    created_by_id=quote.vendor_id,
                    enq_id_id=enid,
                    username=username,
                    total=amount,
                )
                message.save()

            # Send auction email to each vendor in enquiry
            book = Enquiry.objects.get(id=enid)
            for i in book.vendor:


                company_id = request.user.id 


                company_name = Profiles.objects.get(user_id=company_id)

                da = Profiles.objects.get(user_id=int(i))
                mail_message = f'''Dear {da.name},

                This enquiry is from: {company_name.email}


                You are invited to participate in an online auction. Kindly log in to the vendor portal to review the auction details and submit your quotation.

                Access the auction portal here:
                https://procure4less.com/signin/

                We encourage you to respond promptly to ensure your participation.

                If you have any questions, feel free to contact our team.

                Thank you,
                {company_name.servicename}
                '''

                subject = 'Online Auction Invitation - Action Required'
                recipient_list = [da.email]


                thread = threading.Thread(
                    target=send_email_async,
                    args=(subject, mail_message, recipient_list)
                )
                thread.start()
            return Response({
                "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                "error": None,
                "message": "Auction created successfully"
            })

        except KeyError as e:
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": f"Missing required field: {e}"
            })
     

    def put(self, request, id):
        data = request.data

        try:
            enqid = data.get('unit')
            end_date = data.get('enddate')
            end_time = data.get('endtime')
            duration = data.get('duration')
            rt = Auction.objects.get(id=id)

            rt.duration = duration
            rt.end_date = end_date
            rt.end_time = end_time
            rt.en_id_id = enqid

            rt.save()
    
            return Response({
                "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                "error": None,
                "message": "Auction updated successfully"
            })
        except KeyError as e:
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": f"Missing required field: {e}"
            })
        



class RequoteexpireAPIView(APIView):
    permission_classes = (IsAuthenticated,)
    

    def put(self, request, id):
        data = request.data


        try:
            
            rt = Vendorquote.objects.get(vendor_id=request.user.id, enquiry_id=id)

            rt.enquirystatus = 1
            rt.status = 2

            

            rt.save()
    
            return Response({
                "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                "error": None,
                "message": "Auction updated successfully"
            })
        except KeyError as e:
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": f"Missing required field: {e}"
            })
        




class VendorreportsAPIView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request, id=None):
        if id is not None:
            try:
                company = Vendor.objects.get(id=id)
                data = {
                    'id': company.id,
                    'vendorname': company.vendorname,
                    'phone': company.phone,
                    'email': company.email,
                    'address': company.address,
                    'gst': company.gst,
                    'address1': company.country,
                    'city': company.city,
                    'state': company.state,
                    'vendor_company_name': company.vendor_company_name,
                    'plan': company.plan,
                    'plan_details': company.plan_details,
                    'remarks': company.remarks,
                    'registered_date': company.registered_date,
                    'status': company.status,

                    'vendor_id':user_id,


                    'pincode': company.pincode

                }



                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": data
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })
        else:
            try:



                index = 0
                companies = []

                op = request.user.id


                com = Profiles.objects.get(user_id=op)
                companyname = com.servicename
                comapnyaddress = com.address
                companyphone = com.phone
                companypincode = com.pincode
                companyemail = com.email
                companylogo  = com.companylogo.url

                data = {
                    'companyname' : companyname,
                    'comapnyaddress' : comapnyaddress,
                    'companyphone' : companyphone,
                    'companypincode' : companypincode,
                    'companyemail' : companyemail,
                    'companylogo' : companylogo,


                }

                

                user_id = request.query_params.get('user_id')
                vendorname = request.query_params.get('vendorname', '').strip() 
                email = request.query_params.get('email', '').strip() 
                phone = request.query_params.get('phone', '').strip()  

                status_param = request.query_params.get('status', '').strip()

                if user_id:
                    vendors = Vendor.objects.filter(created_by_id=user_id)
                else:
                    vendors = Vendor.objects.filter(created_by_id=request.user.id)


                if vendorname:
                  
                    vendors = vendors.filter(vendorname__icontains=vendorname) 

                if email:
                  
                    vendors = vendors.filter(email__icontains=email) 
                if phone:
                  
                    vendors = vendors.filter(phone__icontains=phone) 
                if status_param:
                    try:
                        status_int = int(status_param)
                        if status_int in [1, 2]:
                            vendors = vendors.filter(status=status_int)
                    except ValueError:
                        pass 

                

                for company in vendors:

                    auccount = Message.objects.filter(created_by_id =company.user_id).count()
                    auctionsuccesscount = Message.objects.filter(created_by_id =company.user_id, status=2).count()
                    auctionfailcount = Message.objects.filter(created_by_id =company.user_id, status=1).count()

                    



                        
                    index += 1

                    companies.append({
                        'row': index,
                        'id': company.id,
                        'name': company.vendorname,
                        'email': company.email,
                        'phone': company.phone,
                        'address': company.address,
                        'status': company.status,
                        'user_id': company.user_id,
                        'auctioncount': auccount,
                        'auctionsuccesscount': auctionsuccesscount,
                        'auctionfailcount': auctionfailcount,






                    })

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": companies,
                    "companydata": data
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })


class EnquiryreportsAPIView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request, id=None):
        try:
            index = 0
            companies = []
            op = request.user.id


            com = Profiles.objects.get(user_id=op)
            companyname = com.servicename
            comapnyaddress = com.address
            companyphone = com.phone
            companypincode = com.pincode
            companyemail = com.email
            companylogo  = com.companylogo.url if com.companylogo else None



            data = {
                    'companyname' : companyname,
                    'comapnyaddress' : comapnyaddress,
                    'companyphone' : companyphone,
                    'companypincode' : companypincode,
                    'companyemail' : companyemail,
                    'companylogo' : companylogo,


            }

            

            user_id = request.query_params.get('user_id')
            setenid = request.query_params.get('setenid', '').strip()
            setdate = request.query_params.get('setdate', '').strip()

            if user_id:
                vendors = Enquiry.objects.filter(created_by_id=op)
            else:
                vendors = Enquiry.objects.filter(created_by_id=request.user.id)

            if setdate:
                vendors = vendors.filter(created_at__icontains=setdate)
            if setenid:
                vendors = vendors.filter(auto_id__icontains=setenid)

            for company in vendors:
                index += 1

                # Products
                pro = []
                if company.product:
                    for product_id in company.product:
                        try:
                            rp = Product.objects.get(id=product_id)
                            pro.append({
                                'id': rp.id,
                                'label': rp.name,
                            })
                        except Product.DoesNotExist:
                            continue

                # Vendors
                ven = []
                if company.vendor:
                    for vendor_id in company.vendor:
                        try:
                            rp = Profiles.objects.get(user_id=vendor_id)
                            ven.append({
                                'id': rp.user_id,
                                'label': rp.name,
                            })
                        except Profiles.DoesNotExist:
                            continue

                responsecount = Vendorquote.objects.filter(enquiry_id=company.id).count()

                rateperunits = []
                total = []

                for vendor_dict in ven:
                    v_id = vendor_dict['id']
                    try:
                        wr = Vendorquote.objects.get(enquiry_id=company.id, vendor_id=v_id)

                        # Check if rateperUnit and total are iterable (not None)
                        if wr.rateperUnit:
                            for r in wr.rateperUnit:
                                rateperunits.append({'rate': r})

                        if wr.total:
                            for t in wr.total:
                                total.append({'total': t})

                    except Vendorquote.DoesNotExist:
                        continue

                companies.append({
                    'row': index,
                    'id': company.id,
                    'auto_id': '#ENQ-000'+str(company.auto_id),
                    'date': company.created_at.date(),
                    'invitedvendor': len(ven),
                    'description': company.description,
                    'responsecount': responsecount,
                    'vendor': ven,
                    'product': pro,
                    'rateperunit': rateperunits,
                    'total': total,
                })
               

            return Response({
                "status": {"code": status.HTTP_200_OK, "response": "success"},
                "error": None,
                "data": companies,
                "companydata" : data
            })

        except Exception as e:
            return Response({
                "status": {"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "response": "failed"},
                "error": True,
                "message": str(e),
            })        



class VendortotalreportsAPIView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request, id=None):
        if id is not None:
            try:
                company = Vendor.objects.get(id=id)
                data = {
                    'id': company.id,
                    'vendorname': company.vendorname,
                   

                    'vendor_id':user_id,



                }



                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": data
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })
        else:
            try:

                index = 0
                companies = []

                op = request.user.id


                com = Profiles.objects.get(user_id=op)
                companyname = com.servicename
                comapnyaddress = com.address
                companyphone = com.phone
                companypincode = com.pincode
                companyemail = com.email
                companylogo  = com.companylogo.url

                data = {
                    'companyname' : companyname,
                    'comapnyaddress' : comapnyaddress,
                    'companyphone' : companyphone,
                    'companypincode' : companypincode,
                    'companyemail' : companyemail,
                    'companylogo' : companylogo,


                }
                datas = []

                user_id = request.query_params.get('user_id')
                vendor_id = request.query_params.get('vendor_id', '').strip() 
            


                if vendor_id:
                    auction = Message.objects.filter(created_by_id=vendor_id)
                    for p in auction:
                        ro = Auction.objects.get(en_id_id= p.enq_id_id)

                        en = Enquiry.objects.get(id=p.enq_id_id)
                        autualamount  = p.message
                        quoteamount = p.total
                        sta = p.status

                        

                        pro = []
                        quan = []
                        for product_id in en.product:
                            rp = Product.objects.get(id=product_id)
                            pro.append({
                                'id': rp.id,
                                'label': rp.name,
                            })

                        for q in en.quantity:
                            quan.append({
                                'quantity': q
                                
                            })
                        datas.append({
                            'row': index,
                            'date': ro.created_at,
                            'auction_id': ro.id,
                            'product': pro,
                            'quantity': quan,
                            'autualamount': autualamount,
                            'quoteamount' : quoteamount,
                            'status' : sta
                        })
                else:
                    vendors = Vendor.objects.filter(created_by_id=request.user.id)
                    for company in vendors:

                        index += 1

                        companies.append({
                            'row': index,
                            'id': company.id,
                            'name': company.vendorname,
                            'vendor_id': company.user_id,
                        })

                
                
               


                
                
                
                
                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": companies,
                    "datas": datas,
                    "companydata" : data
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })

class PolicyAPIView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request, id=None):
        if id is not None:
            try:
                company = Product.objects.get(id=id)

                try:
                    fl = company.sfile.url if company.sfile else None
                except ValueError:
                    fl = None 
                data = {
                    'id': company.id,
                    'name': company.name,
                    'description': company.description,
                    'specification':company.specification,
                    'sfile': fl,
                    'status': company.status

                }

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": data
                })
            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })
        else:
            try:
                wp = request.user.id
                status_param = request.query_params.get('status', '').strip()

                try:
                    status_param = int(status_param)
                except ValueError:
                    status_param = None

                ro = Profiles.objects.get(user_id=wp)

                # Role 2: Vendor, get policy from the creator of the vendor
                if ro.role == 2:
                    op = Vendor.objects.get(user_id=ro.user_id)
                    fg = op.created_by_id
                    rp = Policy.objects.get(created_by_id=fg)
                    content = rp.content

                # Role 0: Admin or company
                elif ro.role == 0:
                    if status_param == 1:
                        rp = Policy.objects.get(created_by_id=ro.user_id)
                        content = rp.content

                    else:
                        MP = Profiles.objects.get(role=1)

                        rp = Policy.objects.get(created_by_id=MP.user_id)
                        content = rp.content

                # Other roles: use user's own policy
                else:
                    rp = Policy.objects.get(created_by_id=wp)
                    content = rp.content

                return Response({
                    "status": {"code": status.HTTP_200_OK, "response": "success"},
                    "error": None,
                    "data": content
                })

            except ObjectDoesNotExist:
                return Response({
                    "status": {"code": status.HTTP_404_NOT_FOUND, "response": "failed"},
                    "error": True,
                    "message": "No data found",
                })

    def post(self, request):
        data = request.data

        try:


            if not Policy.objects.filter(created_by_id=request.user.id).exists():

                content = data.get("content", "").strip()

                company = Policy.objects.create(
                content=content,
                
                created_by=request.user
                )
                company.save()

                return Response({
                    "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                    "error": None,
                    "message": "Policy data created successfully"
                })

            else:
                content = data.get("content", "").strip()


                comp = Policy.objects.get(created_by_id = request.user.id)
                comp.content = content
                
                comp.save()

                return Response({
                    "status": {"code": status.HTTP_201_CREATED, "response": "success"},
                    "error": None,
                    "message": " Policy data updated successfully"
                })
        except KeyError as e:
            return Response({
                "status": {"code": status.HTTP_400_BAD_REQUEST, "response": "failed"},
                "error": True,
                "message": f"Missing required field: {e}"
            })





        




        



            
    
            


        



            
    
            






            


