from django.shortcuts import render, redirect, get_object_or_404

# Iportant to serialize your data to a form understandable by rest frameworks.
#from .serlializers import NoteSerializer
from rest_framework import serializers

# Codes for rest_framework installation
from rest_framework import status, viewsets
from rest_framework.permissions import AllowAny
from rest_framework.decorators import action
from django.http import HttpResponse
from rest_framework.response import Response


# Importing For Responses and Messages 
from django.http import JsonResponse
from django.contrib import messages

#Importing For Json
import json

#For Generating Random Numbers
import string
import random

# Import User
from django.contrib.auth.models import User
from django.contrib.auth import login , logout
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required

#Importing for Models
from .models import Church, ServiceTime, Leader, ChurchComment,  AboutSection, HomepageSection

#Importing For the serializer
from .serializers import ChurchSerializer

#FOR EMAILS PURPOSES
from django.core.mail import send_mail
from django.utils.html import strip_tags


#For Date Application
from datetime import date


#For querying the database
from django.db.models import Q 


#Required for maps requests and location
import requests
from geopy.distance import geodesic

#For pagination
from django.core.paginator import Paginator

maps_api_key = "pk.2edec2c84a76fa937b0fcac91536be77" #LOCATIONIQ

#For url encoding and decording
from urllib.parse import unquote

class DummySerializer(serializers.Serializer):
    #I will add some data later on...
    pass


class LuminasCrossDefaultPage(viewsets.ModelViewSet): 
      
    @action(detail=False, methods=['get'], url_path='')
    def default_page(self, request, *args, **kwargs):
        base_domain = request.build_absolute_uri('/')
        all_churches = Church.objects.filter(is_approved=True).order_by('-created_at')
        homepage  = HomepageSection.objects.all().values()
        
        is_authenticated = False
        if request.user.is_authenticated:
           is_authenticated = True
           
            # Set up pagination
        paginator = Paginator(all_churches, 9)  # 10 churches per page
        page_number = request.GET.get('page')
        page_obj = paginator.get_page(page_number)
               
        return render(request, 'index.html',{'base_domain':base_domain, 
                                             'is_authenticated':is_authenticated,
                                             'sameusernameerror':"",
                                             'page_obj': page_obj,
                                             'home_page_background_image':homepage[0]['homepage_background_image'],
                                             'homepage_scripture':homepage[0]['homepage_daily_scripture'],
                                             'homepage_bible_verse':homepage[0]['homepage_daily_scripture_bible_reading']})


class LuminasCrossViewSet(viewsets.ModelViewSet):
    
    permission_classes = (AllowAny,)
    serializer_class = DummySerializer
    
    
    @action(detail=False, methods=['get', 'POST'], url_path="login")
    def admin_login(self, request):
     base_domain = request.build_absolute_uri('/')
     
     if request.method == "POST":
        email = request.POST['email']
        password = request.POST['password']
        
        if email and password:
         user = User.objects.filter(email=email).first()
         
         if user:
            if user.check_password(password):
                login(request, user, backend='django.contrib.auth.backends.ModelBackend')
                return redirect(f'{base_domain}/') #Should redirect to this view.
            else:
                return render(request , 'login.html', {'login_errors': "Invalid password", 'base_domain':base_domain})
         else:
            return render(request , 'login.html', {'login_errors': "Invalid email or password",'base_domain':base_domain})
             
     else:
         return render(request , 'login.html', {'form': "", 'base_domain':base_domain})
    
    
    #This is like repetion might remove with time.
    # @action(detail=False, methods=['get'], url_path='')
    # def home(self, request):
    #     if request.user.is_authenticated:
    #         is_authenticated = True
    #     else:
    #         is_authenticated = False
        
    #     return render(request, 'index.html', {'is_authenticated':is_authenticated } )
    
    @action(detail=False, methods=['get'], url_path='')
    def about(self, request):
        base_domain = request.build_absolute_uri('/')
        
        if request.user.is_authenticated:
            is_authenticated = True
        else:
            is_authenticated = False
                 
        about  = AboutSection.objects.all().values()
        
        return render(request, 'about.html', {'base_domain':base_domain, 
                                              'about_title':about[0]['about_title'],
                                              'vision':about[0]['vision'], 
                                              'mission':about[0]['mission'],
                                              'description':about[0]['description'],
                                              'about_page_background_image': about[0]['about_page_background_image'],
                                              'is_authenticated':is_authenticated})
    
    
    @action(detail=False, methods=['get'], url_path='')
    def contact(self, request):
        base_domain = request.build_absolute_uri('/')
         
        if request.user.is_authenticated:
            is_authenticated = True
        else:
            is_authenticated = False  
            
        return render(request, 'contact.html', {'is_authenticated':is_authenticated,'base_domain':base_domain})
    
    
    @action(detail=False, methods=['GET','POST'], url_path=r'privacy/policy')
    def privacyandpolicy(self, request):
        base_domain = request.build_absolute_uri('/')
        
        if request.user.is_authenticated:
            is_authenticated = True
              
        else:
            is_authenticated = False 
            
        return render(request, 'privacypolicy.html', {'is_authenticated':is_authenticated,'base_domain':base_domain})
    
    
    @action(detail=False, methods=['GET','POST'], url_path=r'termsandconditions')
    def termsandconditions(self, request):
        base_domain = request.build_absolute_uri('/')
        
        if request.user.is_authenticated:
            is_authenticated = True
              
        else:
            is_authenticated = False 
            
        return render(request, 'termsandconditions.html', {'is_authenticated':is_authenticated,'base_domain':base_domain})
            
             
    
    
    @action(detail=False, methods=['GET', 'POST'], url_path='find/church')
    def churches(self, request): 
        base_domain = request.build_absolute_uri('/')
        
        if request.user.is_authenticated:
            is_authenticated = True
        else:
            is_authenticated = False  
            
        base_domain = request.build_absolute_uri('/')
        all_churches = Church.objects.filter(is_approved=True).order_by('-created_at')

        # Set up pagination
        paginator = Paginator(all_churches, 12)  # 10 churches per page
        page_number = request.GET.get('page')
        page_obj = paginator.get_page(page_number)
               
        return render(request, 'find-church.html',{'base_domain':base_domain, 
                                             'is_authenticated':is_authenticated,
                                             'sameusernameerror':"",
                                             'page_obj': page_obj,})
            
    
    @action(detail=False, methods=['GET','POST'], url_path='add/church')
    def add_churches(self, request):
        base_domain = request.build_absolute_uri('/')
        
        if request.user.is_authenticated:
            is_authenticated = True
        else:
            is_authenticated = False      
            
        churchUsername= request.GET.get('churchUsername', '').strip() #Will be used to check for the username
        
        def get_lat_lon_locationiq(country, state, city):
                    address = f"{city}, {state}, {country}"
                    url = f"https://us1.locationiq.com/v1/search.php"

                    params = {
                        'key': maps_api_key,
                        'q': address,
                        'format': 'json'
                    }
                    response = requests.get(url, params=params)
                    if response.status_code == 200:
                        data = response.json()
                        if isinstance(data, list) and data:
                            lat = data[0].get('lat')
                            lon = data[0].get('lon')
                            
                            print(lat,lon)
                            return float(lat), float(lon)
                    
                    return None, None
        

        if request.method == "POST":    
            try: 
                
                if Church.objects.filter(name=churchUsername).exists():
                        print("church name exists")
                        return JsonResponse({'error': 'The Church Name Already Exists. Choose a Different Name.'})
                    
                get_church_country = request.POST.get('country')
                get_church_state = request.POST.get('state')
                get_church_city = request.POST.get('city')
                
                lat, lon = get_lat_lon_locationiq(
                    get_church_country,
                    get_church_state,
                    get_church_city,
                )
                
                #print(f"The entered lat and long is: {lat},{lon} and type is {type(lat)}, {type(lon)}" )
                church_data = {
                    'name': request.POST.get('churchName'),
                    'mision':request.POST.get('churchMission'),
                    'values': request.POST.get('churchValues'),
                    'about': request.POST.get('aboutChurch'),
                    'expectations': request.POST.get('expectations'),
                    'address': request.POST.get('address'),
                    'city': request.POST.get('city'),
                    'state': request.POST.get('state'),
                    'country': request.POST.get('country'),
                    'postal_code': request.POST.get('postalCode'),
                    'latitude': f"{lat}",
                    'longitude':f"{lon}",
                    'email': request.POST.get('email'),
                    'phone': request.POST.get('phone'),
                    'website': request.POST.get('website'),
                    'social_media': request.POST.get('socialMedia'),
                }
                
                
                # Handle church logo/image
                if 'churchLogo' in request.FILES:
                    logo_file = request.FILES['churchLogo']
                    #file_name = default_storage.save(f'church_logos/{logo_file.name}', logo_file)
                    church_data['church_logo'] = logo_file
                    
                serializer = ChurchSerializer(data=church_data)
                if serializer.is_valid():
                    print("details are valid for church")
                    church = serializer.save()
                else:
                    return Response(
                        {'error': 'Invalid church data', 'details': serializer.errors},
                        status=status.HTTP_400_BAD_REQUEST
                    )
                
                # Handle service times
                service_times = json.loads(request.POST.get('serviceTimes', '[]'))
                for st in service_times:
                    ServiceTime.objects.create(
                        church=church,
                        day=st.get('day'),
                        start_time=st.get('startTime'),
                        end_time=st.get('endTime'),
                        service_type=st.get('type')
                    )
                
                # Handle leaders
                leader_index = 0
                while True:
                    # Check if we have leader data for this index
                    name_key = f'leaders[{leader_index}][name]'
                    if name_key not in request.POST:
                        break
                    
                    leader_data = {
                        'church': church,
                        'name': request.POST.get(name_key),
                        'position': request.POST.get(f'leaders[{leader_index}][position]'),
                        'description': request.POST.get(f'leaders[{leader_index}][description]', ''),
                    }
                    
                    # Handle leader image - need to use getlist for files
                    image_files = request.FILES.getlist(f'leaders[{leader_index}][image]')
            
                    if image_files and len(image_files) > 0:
                        leader_data['leader_image'] = image_files[0]
                    
                    Leader.objects.create(**leader_data)
                    leader_index += 1
                
                return redirect(f"{base_domain}church/added/pending/approval/")
            
            except Exception as e:
                return Response(
                    {'error': 'Failed to register church', 'details': str(e)},
                    status=status.HTTP_500_INTERNAL_SERVER_ERROR
                )
            

        if request.method == 'GET':
                if Church.objects.filter(name=churchUsername).exists():
                        print("church name exists")
                        return JsonResponse({'error': 'The Church Name Already Exists. Choose a Different Name.'})
                    
                else: 
                         return render(request, 'add_church.html', {'sameusernameerror':"", 'is_authenticated':is_authenticated,'base_domain':base_domain, } )
   

    @action(detail=False, methods=['GET', 'POST'], url_path='church/added/pending/approval')
    def church_added_pending_approval(self, request):
        base_domain = request.build_absolute_uri('/') 
         
        if request.user.is_authenticated:
            is_authenticated = True
        else:
            is_authenticated = False   
            
        return render(request, 'church_added_pending_approval.html', {'is_authenticated':is_authenticated, 'base_domain':base_domain}) 
    
    
    #@action(detail=False, methods=['GET','POST'], url_path=r'explore/church/(?P<name>[\w\s\-]+)')
    @action(detail=False, methods=['GET','POST'], url_path=r'explore/church/(?P<name>[a-zA-Z0-9\s]+)')
    def specific_churches(self, request, name):
        
        name = unquote(name)
        
        base_domain = request.build_absolute_uri('/')
        
        if request.user.is_authenticated:
            is_authenticated = True
        else:
            is_authenticated = False   

        specific_church = Church.objects.filter(name=name) 
        specific_church_2 = Church.objects.get(name=name)
        
        
        for church in specific_church:
            lat = church.latitude
            lon = church.longitude
            
        if lat and lon:
            url = f"https://us1.locationiq.com/v1/reverse?lat={lat}&lon={lon}&format=json&key=pk.2edec2c84a76fa937b0fcac91536be77"

            headers = {"accept": "application/json"}

            response = requests.get(url, headers=headers)  
            
            if response.status_code == 200:
                data = response.json()
                latitude = data.get("lat")
                longitude = data.get("lon")
                location_accurate = True
            
            else:
                latitude = "40.7128"
                longitude = "-74.0060"
                location_accurate = False
                print(f"Request failed with status code: {response.status_code}")
        else :
                latitude = "40.7128"
                longitude = "-74.0060"
                location_accurate = False
            
        
        if request.method == "POST" :
            
            for church in specific_church:
                receiver_email = church.email
                church_name = church.name
                
            senders_name = request.POST.get('senderName')
            senders_comment = request.POST.get('senderComment')
            senders_rating = request.POST.get('senderRating')
            
            if senders_name and senders_comment and senders_rating:
                
                def generate_unique_id(length=8):
                    characters = string.ascii_letters + string.digits
                    return ''.join(random.choices(characters, k=length))
                
                ChurchComment.objects.create(
                    unique_id = generate_unique_id,
                    church = specific_church_2,
                    senders_name = senders_name,
                    senders_comment = senders_comment,
                    senders_rating = senders_rating
                    
                )
                
                # subject = f'Comment On {church_name}'
                # html_message = f"""
                # <!DOCTYPE html>
                # <html>
                # <head>
                #     <meta charset="UTF-8">
                #     <title>Comment About Your Church</title>
                # </head>
                # <body style="font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 30px;">
                #     <div style="max-width: 600px; margin: auto; background-color: #ffffff; padding: 30px; border-radius: 10px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);">
                        
                #         <h2 style="color: #2c3e50; border-bottom: 1px solid #e0e0e0; padding-bottom: 10px;">New Comment Submission</h2>
                        
                #         <p style="margin-top: 20px;"><strong>Sender Name:</strong> {senders_name}</p>
                        
                #         <p><strong>Message:</strong></p>
                #         <div style="margin: 15px 0; padding: 15px; background-color: #f8f9fa; border-left: 5px solid #3498db; font-style: italic;">
                #             {senders_comment}
                #         </div>
                        
                #         <p><strong>Recommendation Score:</strong> <span style="color: #27ae60;">{senders_rating}/10</span></p>
                        
                #         <p><strong>Date Submitted:</strong> {date.today().strftime("%B %d, %Y")}</p>
                        
                #         <hr style="margin: 30px 0;">
                        
                #         <p style="font-size: 0.9em; color: #555555;">
                #             Please review the feedback provided above. Your attention to community input is highly appreciated.
                #         </p>
                #     </div>
                # </body>
                # </html>
                # """
                # plain_message = strip_tags(html_message)
                # from_email = "austinaustine4@gmail.com"
                
                # send_mail(
                #         subject,
                #         plain_message,
                #         from_email,
                #         [receiver_email],
                #         html_message=html_message,
                #         fail_silently=False,
                #     )
            
            user_name_interested_in_visiting = request.POST.get('visitorName')
            user_email_interested_in_visiting = request.POST.get('visitorEmail')
            
            if user_email_interested_in_visiting and user_name_interested_in_visiting :
                print(user_name_interested_in_visiting)
                print(user_email_interested_in_visiting)
                           
                # subject = f'Follower Insterested On Visiting Your Church'
                # html_message = f"""
                # <!DOCTYPE html>
                # <html>
                # <head>
                #     <meta charset="UTF-8">
                #     <title>Follower Interesed In Visiting Your Church</title>
                # </head>
                # 
                # <body style="font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 30px;">
                #     <div style="max-width: 600px; margin: auto; background-color: #ffffff; padding: 30px; border-radius: 10px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);">
                #         
                #         <h2 style="color: #2c3e50; border-bottom: 1px solid #e0e0e0; padding-bottom: 10px;">New Interested Church Member</h2>
                #         
                #         <p style="margin-top: 20px;"><strong>Member Name:</strong> {user_name_interested_in_visiting}</p>
                #         
                #         <p style="margin-top: 20px;"><strong>Member Email:</strong> {user_email_interested_in_visiting}</p>
                # 
                #         <p><strong>Date Submitted:</strong> {date.today().strftime("%B %d, %Y")}</p>
                #         
                #         <hr style="margin: 30px 0;">
                #         
                #         <p style="font-size: 0.9em; color: #555555;">
                #             Kindly Send Them a Custom Inivitation Email As you wish
                #         </p>
                #     </div>
                # </body>
                # </html>
                # """
                
                
        return render(request, 'specific-church.html', {'church':specific_church ,
                                                        'is_authenticated':is_authenticated,
                                                        'base_domain':base_domain,
                                                        'location_latitude': latitude,
                                                        'location_longitude':longitude,
                                                        'location_accurate':location_accurate})
    
   
    @action(detail=False, methods=['POST'], url_path=r'delete/comment/(?P<name>[a-zA-Z0-9\s]+)')
    def delete_comment(self, request, name):
        base_domain = request.build_absolute_uri('/')

        if not request.user.is_authenticated:
            return Response({'detail': 'Authentication required.'}, status=status.HTTP_401_UNAUTHORIZED)

        try:
            specific_church = Church.objects.get(name=name)
        except Church.DoesNotExist:
            return Response({'detail': f'Church with name "{name}" not found.'}, status=status.HTTP_404_NOT_FOUND)

        # Expecting the unique_id of the comment in the request data
        comment_id = request.data.get('comment_id')

        if not comment_id:
            return Response({'detail': 'comment_id is required in the request body.'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            comment = ChurchComment.objects.get(unique_id=comment_id, church=specific_church)
        except ChurchComment.DoesNotExist:
            return Response({'detail': 'Comment not found for the specified church.'}, status=status.HTTP_404_NOT_FOUND)

        comment.delete()
        return redirect(f"{base_domain}explore/church/{name}/")
   
   
    @method_decorator(login_required, name='dispatch') 
    @action(detail=False, methods=['GET','POST'], url_path=r'adminpanel/approve/churches')
    def  admin_list_churches(self, request):
        base_domain = request.build_absolute_uri('/')
        
        if request.user.is_authenticated:
            is_authenticated = True
        else:
            is_authenticated = False  
        
        all_non_approved_churches = Church.objects.filter(is_approved=False).order_by('-created_at')
        all_approved_churches = Church.objects.filter(is_approved=True).order_by('-created_at')
        
        if request.method == "POST":
            
            # Handle approval/unapproval/delete actions
            church_name = request.POST.get('churchName')
            action = request.POST.get('approve')
            action_unapprove = request.POST.get('unapprove')
            action_delete = request.POST.get('delete')

            church = Church.objects.filter(name=church_name).first()
            
            if church is None:
                messages.error(request, f'Church "{church_name}" not found.')
            
            elif action == 'approve':
                church.is_approved = True
                church.save()
                messages.success(request, f'"{church.name}" has been approved.') 
                
            elif action_unapprove == 'unapprove':
                church.is_approved = False
                church.save()
                messages.success(request, f'"{church.name}" has been unapproved.')
                
                
            elif action_delete == 'delete':
                church_name = church.name
                print(church_name)
                church.delete()
                messages.success(request, f'"{church_name}" has been deleted.')
                return redirect(f"{base_domain}adminpanel/approve/churches/")
            else:
                messages.error(request, "Invalid action")
            
            return redirect(f"{base_domain}adminpanel/approve/churches/")
        
        return render(request, 'admin_approve_churches.html', {'non_approved_churches': all_non_approved_churches,
                                                               'approved_churches': all_approved_churches,
                                                               'is_authenticated':is_authenticated,
                                                               'base_domain':base_domain} )
   
   
    @method_decorator(login_required, name='dispatch') 
    @action(detail=False, methods=['GET','POST'], url_path=r'adminpanel/approve/church/details/(?P<name>[a-zA-Z0-9\s]+)')
    def admin_church_updates(self, request, name): 
        base_domain = request.build_absolute_uri('/')
        
        if request.user.is_authenticated:
            is_authenticated = True
        else:
            is_authenticated = False 
        
        church = Church.objects.get(name=name)
        
        if request.method == "POST" :
            action = request.POST.get('action')
            
            if church is None:
                messages.error(request, f'Church "{church_name}" not found.')
            
            elif action == 'approve':
                church.is_approved = True
                church.save()
                messages.success(request, f'"{church.name}" has been approved.') 
                
            elif action == 'unapprove':
                church.is_approved = False
                church.save()
                messages.success(request, f'"{church.name}" has been unapproved.')
                
            elif action == 'delete':
                church_name = church.name
                church.delete()
                messages.success(request, f'"{church_name}" has been deleted.')
                return redirect(f"{base_domain}adminpanel/approve/churches/")
            else:
                messages.error(request, "Invalid action")
                
            return render(request, 'admin-specific-church.html', {'church':[church], 'is_authenticated':is_authenticated,'base_domain':base_domain })
            
            
        return render(request, 'admin-specific-church.html', {'church': [church], 'is_authenticated':is_authenticated,'base_domain':base_domain })
    
    
    @action(detail=False, methods=['GET'], url_path=r'luminantcross/querychurch')
    def query_church(self, request):
        base_domain = request.build_absolute_uri('/')
        
        church_username = request.GET.get('churchUsername', '').strip()

        if not church_username:
            return Response({'error': 'No input provided.'}, status=400)
        
        # Filter all matching church names
        matching_churches = Church.objects.filter(Q(name__icontains=church_username) | Q(state__icontains=church_username) | Q( city__icontains=church_username) & Q(is_approved=True))

        if matching_churches.exists():
            church_names = list(matching_churches.values_list('name','state'))
            return JsonResponse({'matches': church_names})
        else:
            return JsonResponse({'matches': []})
        
        
    @action(detail=False, methods=['GET'], url_path=r'explore/church/search')
    def query_mutiple_church(self, request):
        base_domain = request.build_absolute_uri('/')
        
        query = request.GET.get('q', '').strip().rstrip('/')
        
        print(query)
   
        # Filter all matching church names
        matching_churches = Church.objects.filter(Q(name__icontains=query) | Q(state__icontains=query) | Q( city__icontains=query) & Q(is_approved=True))

        if not query:
            return Response({'error': 'No input provided.'}, status=400)
        
        if matching_churches.exists():
            #church_names = list(matching_churches.values_list('name','state'))
            
            return render(request, 'query_matches_multiple_churches.html', {'churches':matching_churches,'base_domain':base_domain})
            #return JsonResponse({'matches': church_names})
        else:
            return JsonResponse({'matches': []})


    @action(detail=False, methods=['GET'], url_path=r'churches/nearby/(?P<lat>-?\d+(\.\d+)?)/(?P<long>-?\d+(\.\d+)?)')
    def nearby_churches(self, request, lat, long, *args, **kwargs):
        
        base_domain = request.build_absolute_uri('/')
        homepage  = HomepageSection.objects.all().values()
        
        is_authenticated = False
        if request.user.is_authenticated:
           is_authenticated = True
        
        try:
            # Convert parameters to float
            user_lat = float(lat)
            user_long = float(long)
            
            def get_location_from_lat_lon(lat, lon):
                url = "https://us1.locationiq.com/v1/reverse.php"

                params = {
                    'key': maps_api_key,
                    'lat': lat,
                    'lon': lon,
                    'format': 'json'
                }

                response = requests.get(url, params=params)
                
                if response.status_code == 200:
                    data = response.json()
                    address = data.get('address', {})
                    city = address.get('city') or address.get('town') or address.get('village')
                    state = address.get('state')
                    country = address.get('country')
                    
                    
                    return city, state, country

                return None, None, None
            
            city, state, country = get_location_from_lat_lon(user_lat, user_long)
            
            if not any([city, state, country]):
                return Response({'error': 'Could not determine location from coordinates'}, status=400)

            
            # Get all approved churches
            all_churches = Church.objects.filter(Q(city__icontains=city) | Q(state__icontains=state) | Q( country__icontains=country) & Q(is_approved=True)).order_by('-created_at')

            
            # Paginate results
            paginator = Paginator(all_churches, 9)  # 10 churches per page
            page_number = request.GET.get('page')
            page_obj = paginator.get_page(page_number)
        
            
            return render(request, 'index.html',{'base_domain':base_domain, 
                                             'is_authenticated':is_authenticated,
                                             'sameusernameerror':"",
                                             'page_obj': page_obj,
                                             'churches_near_location': f"{state},{country}",
                                             'home_page_background_image':homepage[0]['homepage_background_image'],
                                             'homepage_scripture':homepage[0]['homepage_daily_scripture'],
                                             'homepage_bible_verse':homepage[0]['homepage_daily_scripture_bible_reading']})
        
        except ValueError:
            return Response({'error': 'Invalid latitude or longitude parameters'}, status=400)
        except Exception as e:
            return Response({'error': str(e)}, status=500)