from django.shortcuts import render, redirect
from django.contrib import messages
from .models import Contact
from django.core.mail import send_mail

# Create your views here.
def contact(request):
    
    if request.method == "POST":
        listingg_id = request.POST['listingg_id']
        print(listingg_id)
        listing = request.POST['listing']
        name  = request.POST['name']
        email = request.POST['email']
        phone = request.POST['phone']
        message = request.POST['message']
        user_id = request.POST['user_id']
        realtor = request.POST['realtor_email']

        #check if user has made enquiry already or not 
        if request.user.is_authenticated:
                user_id = request.user.id
                has_contacted = Contact.objects.all().filter(listing_id=listingg_id,user_id=user_id)
                if has_contacted:
                        messages.error(request,'You have aleady made an enquiry for this listing')
                        return  redirect('/listings/'+listingg_id)


        contact = Contact(listing = listing, listing_id = listingg_id, name = name, email=email, phone=phone,message=message,user_id=user_id)

        contact.save()
        #send Email 
        send_mail(
                'Property Listing Enquiry ',
                'There has been enquiry for ' + listing + '.Sign in into admin panel for more info..',
                'rajsekharoyal@gmail.com',
                [realtor,'mahendramsdhoni808@gmail.com'],
                fail_silently = False
        )
        messages.success(request,'Your request has been submitted, a realtor will get back to you soon')
        
        return  redirect('/listings/'+listingg_id)