from django.shortcuts import render,redirect,HttpResponse
from adminapp.models import User
from django.contrib.auth import login,logout,authenticate
from adminapp.views import adminindex
from adminapp import models
from userapp.models import BikeRent
from adminapp.forms import FeedbackForm
from django.contrib import messages
# from adminapp.models import Feedback



# Create your views here.

def userindex(request):
    station = models.station.objects.all()
    context = {
        'station':station,
        }
    return render(request,'userapp/index.html',context)

def userbooking(request,id):
    bike = models.bike.objects.get(id=id)
    if request.method == "POST":
        addhar_image = request.FILES.get('aadhar_card')
        bike_rent = BikeRent.objects.create(user=request.user,
                                            bike=bike,
                                            addhar_image = addhar_image,
                                            )
        print(bike_rent)
        bike.is_available = False
        bike.is_running = True
        bike.save()
        return redirect(userform)
        
    context = {
        'bike':bike,
        }
    return render(request,'userapp/booking.html',context)

def userend(request,id):
    bike_rent = BikeRent.objects.get(id=id)
    start_time = bike_rent.start_time
    end_time =  bike_rent.end_time
    duration_minutes = int((end_time - start_time).total_seconds() / 60)
    cost = 60 + ((duration_minutes - 15) // 15) * 30 if duration_minutes > 15 else 30
    print("duration_minutes",duration_minutes)
    print("cost",cost)
    bike_rent.price = cost
    bike_rent.save()
    if request.method == "POST":
        payment = request.POST.get('payment')
        bike_rent.price = cost
        bike_rent.is_paid = True
        bike_rent.payment_mode = payment
        bike_rent.save()
        return redirect(userlast)

    context = {
        'bike_rent':bike_rent,
        'duration_minutes':duration_minutes,
        'cost':cost,
        }
    return render(request,'userapp/endride.html',context)

import datetime

def userform(request):
    bike_rent = BikeRent.objects.filter(user=request.user).last()
    if request.method == "POST":
        current_time = datetime.datetime.now()
        print("current_time",current_time)
        bike = bike_rent
        bike.is_returned = True
        bike.end_time = current_time
        bike.save()
        return redirect(userend,bike_rent.id)
    context = {'bike_rent':bike_rent}
    return render(request,'userapp/form.html',context)

def usercar(request):
    station = models.station.objects.all()
    context = {
        'station':station,
        }
    return render(request,'userapp/car.html',context)

def userteam(request):
    return render(request,'userapp/team.html')

def userdetail(request):
    element = models.bike.objects.all()
    context = {'element':element}
    return render(request,'userapp/detail.html',context)

def userservice(request):
    return render(request,'userapp/service.html')

def userabout(request):
    return render(request,'userapp/about.html')

def usertestimonial(request):
    return render(request,'userapp/testimonial.html')

def usercontact(request):
    return render(request,'userapp/contact.html')

def userlogin(request):
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username,password=password)
        if user is not None and user.is_superuser and user.role == "Admin":
            login(request,user)
            return redirect(adminindex)
        elif user is not None and user.is_superuser == False and user.role == "Customer":
            login(request,user)
            return redirect(userindex)
        else:
            return HttpResponse ("Username & Password incorrect")
    return render(request,'userapp/login.html')

def userlogout(request):
    logout(request)
    return redirect(userlogin)

def adminregister(request):
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        password1 = request.POST.get('password1')
        phone = request.POST.get('phone')
        address = request.POST.get('address')
        if password == password1:
            try:
                User.objects.get(username=username)
                return HttpResponse("Username already exists")
            except:
                User.objects.create_user(username=username,
                                         password=password,
                                         phone=phone,
                                         address=address,
                                         is_superuser=True,
                                         role="Admin")
                return redirect(userlogin)
        else:
            return HttpResponse("Pasword does not match")
    return render(request,'adminapp/register.html')


def userregister(request):
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        password1 = request.POST.get('password1')
        email = request.POST.get('email')
        phone = request.POST.get('phone')
        address = request.POST.get('address')
        password1 = request.POST.get('password1')
        password1 = request.POST.get('password1')
        if password == password1:
            try:
                User.objects.get(username=username)
                return HttpResponse("Username already exists")
            except:
                User.objects.create_user(username=username,password=password,email=email,phone=phone,address=address)
                return redirect(userlogin)
        else:
            return HttpResponse("Pasword does not match")
    return render(request,'userapp/register.html')


def user_profile(request):
    return render(request,'userapp/user_profile.html')


def manage_profile_view(request):
    user = request.user  # Get the logged-in user

    if request.method == "POST":
        user.username = request.POST["username"]
        user.email = request.POST["email"]
        user.phone = request.POST["phone"]  # Directly accessing User model fields
        user.address = request.POST["address"]

        user.save()
        messages.success(request, "Profile updated successfully!")
        return redirect("manage_profile_view")

    return render(request, "userapp/manage-user_profile.html", {"user": user})


def bikedetails(request,id):
    station = models.station.objects.get(id=id)
    bike = models.bike.objects.filter(station=station)
    context = {
        'bike':bike,
    }
    return render(request,'userapp/detail.html',context)

def userrent(request):
    bikes = BikeRent.objects.filter(is_returned=True,is_paid=True)
    context = {
        'bikes':bikes
        }
    return render(request,'userapp/rented_bicycle.html',context)

def userlast(request,id):
    return render(request,'userapp/last.html',{'bike_rent_id': id})

def userfeedback(request):
    if request.method == 'POST':
        form = FeedbackForm(request.POST)  
        if form.is_valid():  
            obj = form.save(commit=False) 
            obj.user = request.user  
            obj.save()  
            messages.success(request, "Thank you for your feedback!")
            return redirect(userlast)  
        else:
            print(form.errors)
    else:
        form = FeedbackForm()  

    return render(request, 'userapp/feedback.html', {'form': form})

from django.core.mail import send_mail
from django.conf import settings
def userforgot(request):
    if request.method == "POST":
        email = request.POST.get('email')
        print(email)
        if email:
            receipent_list = [email]
            from_user = settings.EMAIL_HOST_USER
            subject = "Password Forgot Request"
            message = "city_cycle_123"
            mail = send_mail(subject=subject,message=message,recipient_list=receipent_list,from_email=from_user)
            print("mail sent")
            return redirect(userlogin)
    return render(request,'userapp/forgot_password.html')



from django.conf import settings
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
import razorpay
import json
import hmac
import hashlib

client = razorpay.Client(auth=(settings.RAZORPAY_KEY_ID, settings.RAZORPAY_KEY_SECRET))

def payment_page(request):
    return render(request, 'payment.html')

@csrf_exempt
def create_order(request, id):
    if request.method == "GET":
        try:
            bike_rent = BikeRent.objects.get(id=id)
            print(bike_rent.price)
            amount = int(bike_rent.price * 100)  # Convert to paise

            client = razorpay.Client(auth=(settings.RAZORPAY_KEY_ID, settings.RAZORPAY_KEY_SECRET))
            order_data = {
                "amount": amount,
                "currency": "INR",
                "payment_capture": "1"
            }

            order = client.order.create(order_data)

            return JsonResponse({
                "razorpay_key": settings.RAZORPAY_KEY_ID,
                "order_id": order['id'],
                "amount": bike_rent.price,
                "currency": "INR",
                "rental_request_id": bike_rent.id
            })
        except BikeRent.DoesNotExist:
            return JsonResponse({"error": "Bike rental not found"}, status=404)
    else:
        return JsonResponse({"error": "Invalid request method"}, status=400)

@csrf_exempt
def verify_payment(request,id):
    if request.method == "POST":
        razorpay_order_id = request.POST.get('razorpay_order_id')
        razorpay_payment_id = request.POST.get('razorpay_payment_id')
        razorpay_signature = request.POST.get('razorpay_signature')

        generated_signature = hmac.new(
            settings.RAZORPAY_KEY_SECRET.encode(),
            f"{razorpay_order_id}|{razorpay_payment_id}".encode(),
            hashlib.sha256
        ).hexdigest()
        
        if generated_signature == razorpay_signature:
            bike_rent = BikeRent.objects.get(id=id)
            bike_rent.is_paid = True
            bike_rent.save()
            return JsonResponse({'status': 'Payment Verified', 'success': True})
        else:
            return JsonResponse({'status': 'Verification Failed', 'success': False}, status=400)


def payment_page(request):
    Total_Ride_Duration = request.GET.get("duration_minutes", 0)
    cost = request.GET.get("cost", 30)
    print(" Total_Ride_Duration", "cost")
    
    return render(request, "userapp/payment.html", {
        "razorpay_key_id": settings.RAZORPAY_KEY_ID,
        "rental_minutes": int(Total_Ride_Duration),
        "amount": int(cost),
        
    })


from django.shortcuts import render, redirect
from django.http import HttpResponse
from adminapp.models import Enquiry

def contact_view(request):
    if request.method == "POST":
        name = request.POST.get("name")
        email = request.POST.get("email")
        subject = request.POST.get("subject")
        message = request.POST.get("message")

        if name and email and subject and message:
            enquiry = Enquiry(name=name, email=email, subject=subject, message=message)
            enquiry.save()
            return render(request, 'userapp/contact.html', {
                "success": "Thank you for your message!"
            })
        else:
            return render(request, 'userapp/contact.html', {
                "error": "All fields are required."
            })

    return render(request, 'userapp/contact.html')


