def checkout(request):
    # get Request
    if request.method == 'GET':
        form = CheckForm()
        cart = request.session.get('cart')
        if cart is None:
            cart = []

        for c in cart:
            size_str = c.get('size')
            tshirt_id = c.get('tshirt')
            size_obj = SizeVariant.objects.get(size=size_str, tshirt=tshirt_id)
            c['size'] = size_obj
            c['tshirt'] = size_obj.tshirt

        print(cart)

        return render(request, 'store/checkout.html', {
            "form": form,
            'cart': cart
        })
    else:
        # post request
        form = CheckForm(request.POST)
        user = None
        if request.user.is_authenticated:
            user = request.user
        if form.is_valid():
            # payment
            cart = request.session.get('cart')
            if cart is None:
                cart = []
            for c in cart:
                size_str = c.get('size')
                tshirt_id = c.get('tshirt')
                size_obj = SizeVariant.objects.get(size=size_str,
                                                   tshirt=tshirt_id)
                c['size'] = size_obj
                c['tshirt'] = size_obj.tshirt
            shipping_address = form.cleaned_data.get('shipping_address')
            phone = form.cleaned_data.get('phone')
            payment_method = form.cleaned_data.get('payment_method')
            total = cal_total_payable_amount(cart)
            print(shipping_address, phone, payment_method, total)

            order = Order()
            order.shipping_address = shipping_address
            order.phone = phone
            order.payment_method = payment_method
            order.total = total
            order.order_status = "PENDING"
            order.user = user
            order.save()

            # saving order items
            for c in cart:
                order_item = OrderItem()
                order_item.order = order
                size = c.get('size')
                tshirt = c.get('tshirt')
                order_item.price = floor(size.price -
                                         (size.price *
                                          (tshirt.discount / 100)))
                order_item.quantity = c.get('quantity')
                order_item.size = size
                order_item.tshirt = tshirt
                order_item.save()

            buyer_name = f'{user.first_name} {user.last_name}'
            print(buyer_name)
            # crating payment
            response = API.payment_request_create(
                amount=order.total,
                purpose="Payment For Tshirts",
                send_email=False,
                buyer_name=f'{user.first_name} {user.last_name}',
                email=user.email,
                redirect_url="http://localhost:8000/validate_payment")

            payment_request_id = response['payment_request']['id']
            url = response['payment_request']['longurl']

            payment = Payment()
            payment.order = order
            payment.payment_request_id = payment_request_id
            payment.save()
            return redirect(url)
        else:
            return redirect('/checkout/')
def checkout(request):
    if request.method == 'GET':     #for get Request
        form = CheckForm()
        cart=request.session.get('cart')
        if cart is None:
            cart=[]
        
        for c in cart:
            size_str = c.get('size')
            tshirt_id = c.get('tshirt')
            size_obj=SizeVariant.objects.get(size=size_str , tshirt=tshirt_id)   #now in cart list ,size is replaced by its object
            c['size']=size_obj
            c['tshirt']=size_obj.tshirt   #replacing in cart list , tshirt is id ,inplace of id tshirt object is stored

        return render(request,'store/checkout.html',{"form" : form, 'cart':cart})
    else:
        #this is for POST request
        form = CheckForm(request.POST)
        user = None
        if request.user.is_authenticated :
            user = request.user
        if form.is_valid():
            #payment should be done here
            cart=request.session.get('cart')
            if cart is None:
                cart = []
            for c in cart:
                size_str = c.get('size')
                tshirt_id = c.get('tshirt')
                size_obj=SizeVariant.objects.get(size=size_str , tshirt=tshirt_id)   #now in cart list ,size is replaced by its object
                c['size']=size_obj
                c['tshirt']=size_obj.tshirt
            shipping_address=form.cleaned_data.get('shipping_address')   #the shipping address entered will be stored in shipping_address variable
            phone=form.cleaned_data.get('phone')
            payment_method = form.cleaned_data.get('payment_method')
            total = cal_total_payable_amount(cart)
            print(shipping_address,phone,payment_method , total)
            order= Order()               #created Order Model object
            order.shipping_address = shipping_address   #entering data in ORDER table
            order.phone = phone
            order.payment_method= payment_method
            order.total = total
            order.order_status = "PENDING"
            order.user = user
            order.save()    
            #print(order.id)        # we will get order id 

            #saving to OrderItems Table
            for c in cart :
                order_item = OrderItem()   #creating new object for OrderItem Table
                order_item.order = order      #order id will be stored in order
                size=c.get('size')   #to access dictionary we use get('key')
                tshirt=c.get('tshirt')
                order_item.price = floor(size.price- (size.price*(tshirt.discount/100)))
                order_item.quantity = c.get('quantity')
                order_item.size = size
                order_item.tshirt = tshirt
                order_item.save()

            
            # CREATING PAYMENT
            # Create a new Payment Request
            response = API.payment_request_create(
                amount=order.total,
                purpose='Payment For Tshirts',
                buyer_name=f'{user.first_name} {user.last_name}',
                send_email=True,
                email=user.email,
                redirect_url="http://localhost:8000/validate_payment"
                )
            #print(response['payment_request'])
            payment_request_id = response['payment_request']['id']
            #the long URL of the payment request
            url =response['payment_request']['longurl']
            print(url)
            
            payment= Payment()
            payment.order= order
            payment.payment_request_id= payment_request_id
            payment.save()
            return redirect(url)
        else:
            return redirect('/checkout/')