from django.shortcuts import render, HttpResponse,redirect
from adminapp import forms
from adminapp import models
from adminapp.models import User
import qrcode
from io import BytesIO
from django.core.files.base import ContentFile
from django.contrib.auth import login,logout,authenticate
from adminapp.models import Category, bike, station,Feedback,User,Enquiry
from userapp.models import BikeRent
from django.db.models import Sum


def generate_qr_code(data):
    """
    Generates a QR code and returns it as an image file.
    """
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )
    # data_url =  'http://http://127.0.0.1:8000/userend/34/' + data + '/'
    print(data)
    qr.add_data(data)
    qr.make(fit=True)
    
    # Create an image from the QR code
    img = qr.make_image(fill='black', back_color='white')
    
    # Save the image to a BytesIO object
    img_io = BytesIO()
    img.save(img_io, 'PNG')
    img_io.seek(0)

    # Create a Django-friendly file object and return it
    return ContentFile(img_io.read(), name=f'qr_code_{data}.png')


def adminindex(request):
    payments = BikeRent.objects.all()
    total_pay = BikeRent.objects.aggregate(total=Sum('price'))['total']
    print("total_pay",total_pay)
    print("payments",payments)
    context = {
        'total_categories': Category.objects.count(),
        'total_bikes': bike.objects.count(),
        'total_stations': station.objects.count(),
        'total_feedback': Feedback.objects.count(),
        'total_user': User.objects.count(),
        'total_revenue':total_pay,
        'total_enquiry': Enquiry.objects.count(),
    }
    return render(request, 'adminapp/index.html', context)



def adminstation(request):
    return render(request,'adminapp/station.html')



def loginview(request):
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        phone = request.POST.get('phone')
        address = request.POST.get('address')
        user = authenticate(username=username,password=password,phone=phone,address=address)
        if user is not None:
            login(request,user)
            return redirect(adminindex)
        else:
            return HttpResponse("Username & Password incorrect")
    return render(request,'adminapp/login.html')

def logoutview(request):
    logout(request)
    return redirect(loginview)

def category_add(request):
    if request.method == "POST":
        form = forms.categoryForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.user = request.user
            obj.save()
            return redirect(category_list)
        else:
            print("error")      
            print(form.errors)
    return render(request,'adminapp/category_add.html')

def category_list(request):
    element = models.Category.objects.all()
    return render(request,'adminapp/category_list.html',{'element':element})

def category_delete(request,id):
    data = models.Category.objects.get(id=id)
    data.delete()
    return redirect(category_list)

def category_update(request,id):
    data = models.Category.objects.get(id=id)
    if request.method == "POST":
        form = forms.categoryForm(request.POST,instance=data)
        if form.is_valid():
            form.save()
            return redirect(category_list)
        else:
            print("error")      
            print(form.errors)
    context = {'data':data}
    return render(request,'adminapp/category_update.html',context)

def bike_add(request):
    category = models.Category.objects.all()
    station = models.station.objects.all()
    if request.method == "POST":
        form = forms.bikeForm(request.POST,request.FILES)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.user = request.user
            obj.save()
            return redirect(bike_list)
        else:
            print("error")      
            print(form.errors)
    context = {
        'category':category,
        'station':station
        }
    return render(request,'adminapp/bike_add.html',context)

def bike_list(request):
    element = models.bike.objects.all()
    return render(request,'adminapp/bike_list.html',{'element':element})

def bike_delete(request,id):
    data = models.bike.objects.get(id=id)
    data.delete()
    return redirect(bike_list)

def bike_update(request,id):
    data = models.bike.objects.get(id=id)
    category = models.Category.objects.all()
    station = models.station.objects.all()
    if request.method == "POST":
        form = forms.bikeForm(request.POST,instance=data)
        if form.is_valid():
            form.save()
            return redirect(bike_list)
        else:
            print("error")      
            print(form.errors)
    context = {'data':data,
               'category':category,
               'station':station,
               }
    return render(request,'adminapp/bike_update.html',context)

def station_add(request):
    station = models.station.objects.all()
    if request.method == "POST":
        form = forms.stationForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.user = request.user
            obj.save()
            return redirect(station_list)
        else:
            print("error")      
            print(form.errors)
    context = {
        'station':station,
        }
    return render(request,'adminapp/station_add.html',context)

def station_list(request):
    element = models.station.objects.all()
    return render(request,'adminapp/station_list.html',{'element':element})

def station_delete(request,id):
    data = models.station.objects.get(id=id)
    data.delete()
    return redirect(station_list)

def station_update(request,id):
    data = models.station.objects.get(id=id)
    if request.method == "POST":
        form = forms.stationForm(request.POST,instance=data)
        if form.is_valid():
            form.save()
            return redirect(station_list)
        else:
            print("error")      
            print(form.errors)
    context = {'data':data}
    return render(request,'adminapp/station_update.html',context)

def adminfeedback(request):
    data = models.Feedback.objects.all()
    context = {'data':data}
    return render(request,'adminapp/feedback.html',context)

def registered_users(request):
    users = User.objects.all()  
    return render(request, 'adminapp/registered_users.html', {'users': users})


from django.shortcuts import render
from adminapp.models import Enquiry  

def admin_enquiry(request):
    enquiries = Enquiry.objects.all().order_by('-id')
    return render(request, 'adminapp/contact.html', {'enquiries': enquiries})
