import razorpay
from django import views
from django.contrib.auth.models import User
from django.contrib.auth.views import redirect_to_login
from django.shortcuts import render, redirect
from django.views import View
from .models import Customer, Product, Cart, OrderPlaced
from .forms import CustomerRegistrationForm, CustomerProfileForm
from django.contrib import messages
from django.db.models import Q
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required # this is for function based view
from django.utils.decorators import method_decorator # this is for class based view


# Create your views here.


class ProductView(View):  # CBV(Class based view) inherited View module from django to show the products by category with filter funtion
    def get(self, request):
        totalitem = 0
        topwear = Product.objects.filter(category='TW')
        bottomwear = Product.objects.filter(category='BW')
        mobile = Product.objects.filter(category='M')
        shoes = Product.objects.filter(category='SH')
        jeans = Product.objects.filter(category='J')
        watches = Product.objects.filter(category='WT')
        shirts = Product.objects.filter(category='S')
        laptop = Product.objects.filter(category='L')
        tv = Product.objects.filter(category='TV')
        if request.user.is_authenticated:
            totalitem = len(Cart.objects.filter(user=request.user))
        return render(request, 'app/home.html', {'topwear': topwear, 'bottomwear': bottomwear, 'mobile': mobile, 'shoes': shoes, 'jeans': jeans, 'watches': watches, 'shirts': shirts, 'laptop': laptop, 'tv': tv, 'totalitem':totalitem})
# def home(request):
#  return render(request, 'app/home.html')


class ProductDetail(View):  # CBV to show the product details
    def get(self, request, pk):
        totalitem = 0
        product = Product.objects.get(pk=pk)
        item_already_in_cart = False
        if request.user.is_authenticated:
            totalitem = len(Cart.objects.filter(user=request.user))
            item_already_in_cart = Cart.objects.filter(Q(product=product.id) & Q(user=request.user)).exists()
        return render(request, 'app/productdetail.html', {'product': product, 'item_already_in_cart':item_already_in_cart, 'totalitem':totalitem})


# def product_detail(request):
#  return render(request, 'app/productdetail.html')

def add_to_cart(request):
    user = request.user  # if user is the current is User
    # get the product id which is comming from the GET request
    product_id = request.GET.get('prod_id')
    # get the id objects of the product which matches the product_id
    product = Product.objects.get(id=product_id)
    # get the user & product id objects of products and save
    if user.is_authenticated:
        Cart(user=user, product=product).save()
    else:
        return redirect('/account/login')
    return redirect('/cart')

@login_required
def show_cart(request):  # this function is for showing the cart item only for the logged in user and the price calculations also done in this function it will redirect to addtocart.html
    totalitem = 0
    if request.user.is_authenticated:  # if the user is authenticated
        totalitem = len(Cart.objects.filter(user=request.user))
        user = request.user  # get the user
        # filter only the user if the user is sagar then filter only sagar's cart item
        cart = Cart.objects.filter(user=user)
        amount = 0.0
        shipping_amount = 70.0
        total_amount = 0.0
        # all objects in cart will be stored in p & check if the p.user(current user is logged in ) equal to current user
        cart_product = [p for p in Cart.objects.all() if p.user == user]
        if cart_product:  # if cartproducts has any object for the logged in user
            for p in cart_product:
                # quantity * product discounted price
                tempamount = (p.quantity * p.product.discounted_price)
                # amount = amount + tempamount it will calculate all the products by quantity
                amount += tempamount
                totalamount = amount + shipping_amount

            return render(request, 'app/addtocart.html', {'carts': cart, 'totalamount': totalamount, 'amount': amount, 'shipping_amount': shipping_amount, 'totalitem':totalitem})
        else:
            return render(request, 'app/emptycart.html')


def plus_cart(request):
    if request.method == 'GET':
        prod_id = request.GET['prod_id'] # take the id from js file to get the id 
        c = Cart.objects.get(Q(product=prod_id) & Q(user=request.user)) # get the product id from the same user which matches the id of the product
        c.quantity+=1 # incrementing the quantity from cart model
        c.save()
        amount = 0.0
        shipping_amount = 70.0
        cart_product = [p for p in Cart.objects.all() if p.user == request.user]
        for p in cart_product:
            # quantity * product discounted price
            tempamount = (p.quantity * p.product.discounted_price)  # 700
            # amount = amount + tempamount it will calculate all the products by quantity
            amount += tempamount
            

        data = {
            'quantity': c.quantity,
            'amount': amount,
            'totalamount': amount + shipping_amount
        }
        return JsonResponse(data)


def minus_cart(request):
    if request.method == 'GET':
        prod_id = request.GET['prod_id'] # take the id from js file to get the id 
        c = Cart.objects.get(Q(product=prod_id) & Q(user=request.user)) # get the product id from the same user which matches the id of the product
        c.quantity-=1 # incrementing the quantity from cart model
        c.save()
        amount = 0.0
        shipping_amount = 70.0
        cart_product = [p for p in Cart.objects.all() if p.user == request.user]
        for p in cart_product:
            # quantity * product discounted price
            tempamount = (p.quantity * p.product.discounted_price)  # 700
            # amount = amount + tempamount it will calculate all the products by quantity
            amount += tempamount

        data = {
            'quantity': c.quantity,
            'amount': amount,
            'totalamount': amount + shipping_amount

        }
        return JsonResponse(data)

def remove_cart(request):
    if request.method == 'GET':
        prod_id = request.GET['prod_id'] # take the id from js file to get the id 
        c = Cart.objects.get(Q(product=prod_id) & Q(user=request.user)) # get the product id from the same user which matches the id of the product
        c.delete()
        amount = 0.0
        shipping_amount = 70.0
        cart_product = [p for p in Cart.objects.all() if p.user == request.user]
        for p in cart_product:
            # quantity * product discounted price
            tempamount = (p.quantity * p.product.discounted_price)  # 700
            # amount = amount + tempamount it will calculate all the products by quantity
            amount += tempamount

        data = {
            'amount': amount,
            'totalamount': amount + shipping_amount
        }
        return JsonResponse(data)


def buy_now(request):
    return render(request, 'app/buynow.html')

# def profile(request):
#  return render(request, 'app/profile.html')

@method_decorator(login_required(login_url='/account/login/'), name='dispatch')
class ProfileView(View):
    def get(self, request):  # if the request is in get method
        form = CustomerProfileForm()  # take the empty form and to it to the user
        return render(request, 'app/profile.html', {'form': form})

    def post(self, request):
        # if the form is in post request
        form = CustomerProfileForm(request.POST)
        if form.is_valid():  # if form is valid then cleaned the data
            usr = request.user  # to get the user currently logged in to save posted data into database using this user which is currently requesting
            name = form.cleaned_data['name']
            locality = form.cleaned_data['locality']
            state = form.cleaned_data['state']
            city = form.cleaned_data['city']
            zipcode = form.cleaned_data['zipcode']
            # then save the data in the customer model
            reg = Customer(user=usr, name=name, locality=locality,
                           city=city, state=state, zipcode=zipcode)
            reg.save()
            # show the message using messages module
            messages.success(
                request, 'Contratulations !! Profile updated Sucessfully')
        return render(request, 'app/profile.html', {'form': form})

@login_required(login_url='/account/login/')
def address(request):
    totalitem = 0
    if request.user.is_authenticated:
        totalitem = len(Cart.objects.filter(user=request.user))
    # to show the address from database to user which is saved Profile view
    add = Customer.objects.filter(user=request.user)
    return render(request, 'app/address.html', {'add': add, 'totalitem':totalitem})

@login_required(login_url='/account/login/')
def orders(request):
    op = OrderPlaced.objects.filter(user=request.user)
    return render(request, 'app/orders.html', {'orderplaced':op})

# def change_password(request):
#  return render(request, 'app/changepassword.html')


def mobile(request, data=None):  # to show the products by mobile categories
    totalitem = 0
    if request.user.is_authenticated:
        totalitem = len(Cart.objects.filter(user=request.user))

    if data == None:  # if data which is passed by slug field is equal to none.
        # get the data by category M in var=mobile
        mobiles = Product.objects.filter(category='M')
    elif data == 'Redmi' or data == 'Samsung':  # if slug data is equal to redmi or samsung
        # then filter it using brand data which is in model
        mobiles = Product.objects.filter(category='M').filter(brand=data)
    elif data == 'below':
        mobiles = Product.objects.filter(
            category='M').filter(discounted_price__lt=10000)
    elif data == 'above':
        mobiles = Product.objects.filter(
            category='M').filter(discounted_price__gt=10000)
    return render(request, 'app/mobile.html', {'mobiles': mobiles, 'totalitem':totalitem})


def login(request):
    return render(request, 'app/login.html')


class CustomerRegistrationView(View):  # CBV of Customer registration (SignUp)
    def get(self, request):  # if the request is get by the user
        form = CustomerRegistrationForm()  # show the empty form to the user
        return render(request, 'app/customerregistration.html', {'form': form})

    def post(self, request):  # if the request is post by the user
        # collect the posted data in form variable
        form = CustomerRegistrationForm(request.POST)
        if form.is_valid():  # if the form is valid
            # send a success message to the user.
            messages.success(
                request, 'Congratulations ! Registered Sucessfully')
            form.save()  # save the form
        return render(request, 'app/customerregistration.html', {'form': form})


# def customerregistration(request):
#  return render(request, 'app/customerregistration.html')
@login_required(login_url='/account/login/')
def checkout(request):
    user = request.user
    add = Customer.objects.filter(user=user)
    cart_items = Cart.objects.filter(user=user)
    amount = 0.0
    shipping_amount = 70.0
    totalamount = 0.0
    cart_product = [p for p in Cart.objects.all() if p.user == request.user]
    if cart_product:
        for p in cart_product:
            # quantity * product discounted price
            tempamount = (p.quantity * p.product.discounted_price)  # 700
            # amount = amount + tempamount it will calculate all the products by quantity
            amount += tempamount
        totalamount = amount + shipping_amount
        client = razorpay.Client(auth = ("rzp_test_uMwzTjc2f1BK3Q", "7mmmdRdqenn3p7R0FUKUfz3l"))
        payment = client.order.create({'amount':totalamount, 'currency':'INR', 'payment_capture':'1'})


    return render(request, 'app/checkout.html', {'add':add, 'totalamount':totalamount, 'cart_items':cart_items})


def payment_done(request):
    user = request.user
    custid = request.GET.get('custid')
    customer = Customer.objects.get(id=custid)
    cart = Cart.objects.filter(user=user)
    for c in cart:
        OrderPlaced(user=user, customer=customer, product=c.product, quantity=c.quantity).save()
        c.delete()
    return redirect("orders")
import razorpay
from django import views
from django.contrib.auth.models import User
from django.contrib.auth.views import redirect_to_login
from django.shortcuts import render, redirect
from django.views import View
from .models import Customer, Product, Cart, OrderPlaced
from .forms import CustomerRegistrationForm, CustomerProfileForm
from django.contrib import messages
from django.db.models import Q
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required # this is for function based view
from django.utils.decorators import method_decorator # this is for class based view


# Create your views here.


class ProductView(View):  # CBV(Class based view) inherited View module from django to show the products by category with filter funtion
    def get(self, request):
        totalitem = 0
        topwear = Product.objects.filter(category='TW')
        bottomwear = Product.objects.filter(category='BW')
        mobile = Product.objects.filter(category='M')
        shoes = Product.objects.filter(category='SH')
        jeans = Product.objects.filter(category='J')
        watches = Product.objects.filter(category='WT')
        shirts = Product.objects.filter(category='S')
        laptop = Product.objects.filter(category='L')
        tv = Product.objects.filter(category='TV')
        if request.user.is_authenticated:
            totalitem = len(Cart.objects.filter(user=request.user))
        return render(request, 'app/home.html', {'topwear': topwear, 'bottomwear': bottomwear, 'mobile': mobile, 'shoes': shoes, 'jeans': jeans, 'watches': watches, 'shirts': shirts, 'laptop': laptop, 'tv': tv, 'totalitem':totalitem})
# def home(request):
#  return render(request, 'app/home.html')


class ProductDetail(View):  # CBV to show the product details
    def get(self, request, pk):
        totalitem = 0
        product = Product.objects.get(pk=pk)
        item_already_in_cart = False
        if request.user.is_authenticated:
            totalitem = len(Cart.objects.filter(user=request.user))
            item_already_in_cart = Cart.objects.filter(Q(product=product.id) & Q(user=request.user)).exists()
        return render(request, 'app/productdetail.html', {'product': product, 'item_already_in_cart':item_already_in_cart, 'totalitem':totalitem})


# def product_detail(request):
#  return render(request, 'app/productdetail.html')

def add_to_cart(request):
    user = request.user  # if user is the current is User
    # get the product id which is comming from the GET request
    product_id = request.GET.get('prod_id')
    # get the id objects of the product which matches the product_id
    product = Product.objects.get(id=product_id)
    # get the user & product id objects of products and save
    if user.is_authenticated:
        Cart(user=user, product=product).save()
    else:
        return redirect('/account/login')
    return redirect('/cart')

@login_required
def show_cart(request):  # this function is for showing the cart item only for the logged in user and the price calculations also done in this function it will redirect to addtocart.html
    totalitem = 0
    if request.user.is_authenticated:  # if the user is authenticated
        totalitem = len(Cart.objects.filter(user=request.user))
        user = request.user  # get the user
        # filter only the user if the user is sagar then filter only sagar's cart item
        cart = Cart.objects.filter(user=user)
        amount = 0.0
        shipping_amount = 70.0
        total_amount = 0.0
        # all objects in cart will be stored in p & check if the p.user(current user is logged in ) equal to current user
        cart_product = [p for p in Cart.objects.all() if p.user == user]
        if cart_product:  # if cartproducts has any object for the logged in user
            for p in cart_product:
                # quantity * product discounted price
                tempamount = (p.quantity * p.product.discounted_price)
                # amount = amount + tempamount it will calculate all the products by quantity
                amount += tempamount
                totalamount = amount + shipping_amount

            return render(request, 'app/addtocart.html', {'carts': cart, 'totalamount': totalamount, 'amount': amount, 'shipping_amount': shipping_amount, 'totalitem':totalitem})
        else:
            return render(request, 'app/emptycart.html')


def plus_cart(request):
    if request.method == 'GET':
        prod_id = request.GET['prod_id'] # take the id from js file to get the id 
        c = Cart.objects.get(Q(product=prod_id) & Q(user=request.user)) # get the product id from the same user which matches the id of the product
        c.quantity+=1 # incrementing the quantity from cart model
        c.save()
        amount = 0.0
        shipping_amount = 70.0
        cart_product = [p for p in Cart.objects.all() if p.user == request.user]
        for p in cart_product:
            # quantity * product discounted price
            tempamount = (p.quantity * p.product.discounted_price)  # 700
            # amount = amount + tempamount it will calculate all the products by quantity
            amount += tempamount
            

        data = {
            'quantity': c.quantity,
            'amount': amount,
            'totalamount': amount + shipping_amount
        }
        return JsonResponse(data)


def minus_cart(request):
    if request.method == 'GET':
        prod_id = request.GET['prod_id'] # take the id from js file to get the id 
        c = Cart.objects.get(Q(product=prod_id) & Q(user=request.user)) # get the product id from the same user which matches the id of the product
        c.quantity-=1 # incrementing the quantity from cart model
        c.save()
        amount = 0.0
        shipping_amount = 70.0
        cart_product = [p for p in Cart.objects.all() if p.user == request.user]
        for p in cart_product:
            # quantity * product discounted price
            tempamount = (p.quantity * p.product.discounted_price)  # 700
            # amount = amount + tempamount it will calculate all the products by quantity
            amount += tempamount

        data = {
            'quantity': c.quantity,
            'amount': amount,
            'totalamount': amount + shipping_amount

        }
        return JsonResponse(data)

def remove_cart(request):
    if request.method == 'GET':
        prod_id = request.GET['prod_id'] # take the id from js file to get the id 
        c = Cart.objects.get(Q(product=prod_id) & Q(user=request.user)) # get the product id from the same user which matches the id of the product
        c.delete()
        amount = 0.0
        shipping_amount = 70.0
        cart_product = [p for p in Cart.objects.all() if p.user == request.user]
        for p in cart_product:
            # quantity * product discounted price
            tempamount = (p.quantity * p.product.discounted_price)  # 700
            # amount = amount + tempamount it will calculate all the products by quantity
            amount += tempamount

        data = {
            'amount': amount,
            'totalamount': amount + shipping_amount
        }
        return JsonResponse(data)


def buy_now(request):
    return render(request, 'app/buynow.html')

# def profile(request):
#  return render(request, 'app/profile.html')

@method_decorator(login_required(login_url='/account/login/'), name='dispatch')
class ProfileView(View):
    def get(self, request):  # if the request is in get method
        form = CustomerProfileForm()  # take the empty form and to it to the user
        return render(request, 'app/profile.html', {'form': form})

    def post(self, request):
        # if the form is in post request
        form = CustomerProfileForm(request.POST)
        if form.is_valid():  # if form is valid then cleaned the data
            usr = request.user  # to get the user currently logged in to save posted data into database using this user which is currently requesting
            name = form.cleaned_data['name']
            locality = form.cleaned_data['locality']
            state = form.cleaned_data['state']
            city = form.cleaned_data['city']
            zipcode = form.cleaned_data['zipcode']
            # then save the data in the customer model
            reg = Customer(user=usr, name=name, locality=locality,
                           city=city, state=state, zipcode=zipcode)
            reg.save()
            # show the message using messages module
            messages.success(
                request, 'Contratulations !! Profile updated Sucessfully')
        return render(request, 'app/profile.html', {'form': form})

@login_required(login_url='/account/login/')
def address(request):
    totalitem = 0
    if request.user.is_authenticated:
        totalitem = len(Cart.objects.filter(user=request.user))
    # to show the address from database to user which is saved Profile view
    add = Customer.objects.filter(user=request.user)
    return render(request, 'app/address.html', {'add': add, 'totalitem':totalitem})

@login_required(login_url='/account/login/')
def orders(request):
    op = OrderPlaced.objects.filter(user=request.user)
    return render(request, 'app/orders.html', {'orderplaced':op})

# def change_password(request):
#  return render(request, 'app/changepassword.html')


def mobile(request, data=None):  # to show the products by mobile categories
    totalitem = 0
    if request.user.is_authenticated:
        totalitem = len(Cart.objects.filter(user=request.user))

    if data == None:  # if data which is passed by slug field is equal to none.
        # get the data by category M in var=mobile
        mobiles = Product.objects.filter(category='M')
    elif data == 'Redmi' or data == 'Samsung':  # if slug data is equal to redmi or samsung
        # then filter it using brand data which is in model
        mobiles = Product.objects.filter(category='M').filter(brand=data)
    elif data == 'below':
        mobiles = Product.objects.filter(
            category='M').filter(discounted_price__lt=10000)
    elif data == 'above':
        mobiles = Product.objects.filter(
            category='M').filter(discounted_price__gt=10000)
    return render(request, 'app/mobile.html', {'mobiles': mobiles, 'totalitem':totalitem})


def login(request):
    return render(request, 'app/login.html')


class CustomerRegistrationView(View):  # CBV of Customer registration (SignUp)
    def get(self, request):  # if the request is get by the user
        form = CustomerRegistrationForm()  # show the empty form to the user
        return render(request, 'app/customerregistration.html', {'form': form})

    def post(self, request):  # if the request is post by the user
        # collect the posted data in form variable
        form = CustomerRegistrationForm(request.POST)
        if form.is_valid():  # if the form is valid
            # send a success message to the user.
            messages.success(
                request, 'Congratulations ! Registered Sucessfully')
            form.save()  # save the form
        return render(request, 'app/customerregistration.html', {'form': form})


# def customerregistration(request):
#  return render(request, 'app/customerregistration.html')
@login_required(login_url='/account/login/')
def checkout(request):
    user = request.user
    add = Customer.objects.filter(user=user)
    cart_items = Cart.objects.filter(user=user)
    amount = 0.0
    shipping_amount = 70.0
    totalamount = 0.0
    cart_product = [p for p in Cart.objects.all() if p.user == request.user]
    if cart_product:
        for p in cart_product:
            # quantity * product discounted price
            tempamount = (p.quantity * p.product.discounted_price)  # 700
            # amount = amount + tempamount it will calculate all the products by quantity
            amount += tempamount
        totalamount = amount + shipping_amount
        client = razorpay.Client(auth = ("rzp_test_uMwzTjc2f1BK3Q", "7mmmdRdqenn3p7R0FUKUfz3l"))
        payment = client.order.create({'amount':totalamount, 'currency':'INR', 'payment_capture':'1'})


    return render(request, 'app/checkout.html', {'add':add, 'totalamount':totalamount, 'cart_items':cart_items})


def payment_done(request):
    user = request.user
    custid = request.GET.get('custid')
    customer = Customer.objects.get(id=custid)
    cart = Cart.objects.filter(user=user)
    for c in cart:
        OrderPlaced(user=user, customer=customer, product=c.product, quantity=c.quantity).save()
        c.delete()
    return redirect("orders")
# this is for function based view # this is for class based view # Create your views here. # CBV(Class based view) inherited View module from django to show the products by category with filter funtion # def home(request): #  return render(request, 'app/home.html') # CBV to show the product details # def product_detail(request): #  return render(request, 'app/productdetail.html') # if user is the current is User # get the product id which is comming from the GET request # get the id objects of the product which matches the product_id # get the user & product id objects of products and save # this function is for showing the cart item only for the logged in user and the price calculations also done in this function it will redirect to addtocart.html # if the user is authenticated # get the user # filter only the user if the user is sagar then filter only sagar's cart item # all objects in cart will be stored in p & check if the p.user(current user is logged in ) equal to current user # if cartproducts has any object for the logged in user # quantity * product discounted price # amount = amount + tempamount it will calculate all the products by quantity # take the id from js file to get the id # get the product id from the same user which matches the id of the product # incrementing the quantity from cart model # quantity * product discounted price # 700 # amount = amount + tempamount it will calculate all the products by quantity # take the id from js file to get the id # get the product id from the same user which matches the id of the product # incrementing the quantity from cart model # quantity * product discounted price # 700 # amount = amount + tempamount it will calculate all the products by quantity # take the id from js file to get the id # get the product id from the same user which matches the id of the product # quantity * product discounted price # 700 # amount = amount + tempamount it will calculate all the products by quantity # def profile(request): #  return render(request, 'app/profile.html') # if the request is in get method # take the empty form and to it to the user # if the form is in post request # if form is valid then cleaned the data # to get the user currently logged in to save posted data into database using this user which is currently requesting # then save the data in the customer model # show the message using messages module # to show the address from database to user which is saved Profile view # def change_password(request): #  return render(request, 'app/changepassword.html') # to show the products by mobile categories # if data which is passed by slug field is equal to none. # get the data by category M in var=mobile # if slug data is equal to redmi or samsung # then filter it using brand data which is in model # CBV of Customer registration (SignUp) # if the request is get by the user # show the empty form to the user # if the request is post by the user # collect the posted data in form variable # if the form is valid # send a success message to the user. # save the form # def customerregistration(request): #  return render(request, 'app/customerregistration.html') # quantity * product discounted price # 700 # amount = amount + tempamount it will calculate all the products by quantity