#!/usr/bin/python3
#####################################################################################
# Checkout page
#####################################################################################
import cgi
import cgitb
import shopcartFunc                     #import custom shopCart functions

cgitb.enable()
 
print('Content-type: text/html \n')

appName = 'XYZ'                         #enter a unique application name or leave it XYZ

elements   = cgi.FieldStorage()
firstname  = elements.getvalue('fname') or ''           
lastname   = elements.getvalue('lname') or ''            
address    = elements.getvalue('addr')  or ''      
email      = elements.getvalue('email') or ''      
creditCard = elements.getvalue('cc')    or ''      
itemName   = elements.getvalue('item')  or ''       #from query string       
option     = elements.getvalue('opt')   or ''       #which button was pressed

nameErr  = ''
addrErr  = ''
emailErr = ''
ccErr    = ''
error    = ''
msg      = ''

shopcartFunc.accessCart()                               #access shopping cart (if any)
cartId    = shopcartFunc.getCartId()                    #get the cart id
cartItems = shopcartFunc.getCartItems()                 #get all items as a dictionary

#-- Validate --------------------------------------------------------------------------------
if cartItems and option=='confirm':                     #validate input fields
    if not firstname or not lastname:
        nameErr  = '*'
    if not address:
        addrErr  = '*'
    if not email:
        emailErr  = '*'
    if not creditCard:
        ccErr  = '*'

if nameErr or addrErr or emailErr or ccErr:
    error = 'Please enter required fields above'
    
#-- Process --------------------------------------------------------------------------------
if not error:                                               #if no validation errors
    if option == 'confirm':                                 #confirm the order                        
        msg = 'Your order has been confirmed' 

#       add to database                                     #NOTE: this is where you add this shopping cart to database
#       clear the cart                                      #NOTE: you should also clear shopping cart

    if option == 'del':                                     #delete an item from shopping cart
        shopcartFunc.delCartItem(itemName)                                                                    
        msg = F"Item {itemName} deleted from your shopping cart"                              

#-- Display Input Form ------------------------------------------------------------------------
print(F"""
    <html>
    <head>
    <title>Shopping Cart Example</title>
    <style>
        button    {{width:110px; color:white; background-color:green}}
        td        {{vertical-align:top}}
        span      {{color:red; vertical-align:top}}
    </style> 
    </head>
    <body bgcolor=lightyellow>
    <h2>Shopping Cart Checkout</h2>
    <br>
    <form method=post name=frm > 
    <fieldset style='width:560px'>
    <table>
    <tr><td><b>First Name  <td>           <input type=text  name=fname value='{firstname}'  size=20> 
        <td><b>Last Name   <td>           <input type=text  name=lname value='{lastname}'   size=21>       <span>{nameErr}  </span>
    <tr><td><b>Address     <td colspan=3> <textarea         name=addr  rows=5 cols=58>{address}</textarea> <span>{addrErr}  </span> 
    <tr><td><b>Email       <td colspan=3> <input type=email name=email value='{email}'      size=59>       <span>{emailErr} </span> 
    <tr><td><b>Credit Card <td colspan=3> <input type=text  name=cc    value='{creditCard}' size=59>       <span>{ccErr}    </span> 
    <tr><td><td colspan=3> <font color=red>{error}  </font>
    </table>
    </fieldset>
    <br>
    <button type=submit name=opt value='confirm'>     Confirm your Order </button>
""")

#-- Display Shopping Cart ---------------------------------------------------------------------                                                     #if option is view 

cartItems = shopcartFunc.getCartItems()                 #get all items as a dictionary
if cartItems:    
    print(F"""<h4><i>Cart Id:</i> {cartId} </h4> 
          <table border=2 bgcolor=tan>
          <tr bgcolor=cccccc><th><i><nobr>Item<th width=500><i>Price & Quantity<th><i>Delete</th>
    """)        
    for name in sorted(cartItems):                                  #loop thru the cart items
        print("<tr><td><b>",name,"<td width=500>",cartItems[name])  #print the item name & values
        print(F"<td><a href=shopcheckout.py?opt=del&item={name}>")  #anchor to current script
        print("<img src=img/delete.png height=20 width=35></a>")    #add delete icon

    print("</table>")
else:    
    print("<h4>Your Shopping Cart is Empty</h4>")
    
print(F"<h4><font color=red>{msg}</font></h4>")




#=== link to see the python code =================================================
import os, sys
sys.path.insert(0,'/home/s/sultans/web/python/demo')
import zCode                          #import func to display the Python code
filename = os.path.abspath(__file__)  #get absolute file name 
zCode.display(filename)               #call it
#=================================================================================