#!/usr/bin/env python3
#===============================================================================
# List content of shopping cart
# if no cookie cust_id, redirect to login page
#===============================================================================
import config
import WEB
import COOKIE
import DB

input    = None								#global variables
cust_id  = ''
fname    = ''
address  = ''
cart     = []
msg      = ''

print('Content-type: text/html')            #required HTTP response header
if config.RUN_MODE=='test': print('\n')     #if 'test', end the headers, so everything prints 

#=============================================================================
# execute SQL against database
#=============================================================================
def exec(sql):
    global msg   
 
    msg  = ''
    conn = DB.connect('demo2','demo2','demo2','mysql')
    if isinstance(conn,str): msg=conn; return           #connection error 

    if 'select' in sql.lower():
        result = DB.select(sql)
    else:
        result = DB.update(sql)
    if isinstance(result,str): msg=result; return       #database error 

    return result
    conn.close()                                        #close the connection
    
#=============================================================================
# Read the customer from database
#=============================================================================
def read_customer():
    global fname, address, msg   
 
    sql = F""" SELECT * FROM shop_customer 
               WHERE cust_id = {cust_id} """ 
    result = exec(sql)             
    if (not result):       
        msg = F"Customer id {cust_id} does not exist in the database"
        return        
    row   = result[0]                                   #take first row
    fname   = row['fname']                             
    address = row['address']                             
    
#=============================================================================
# Read cart data from the database
#=============================================================================
def read_cart():
    global cart, msg;   
 
    sql = F""" SELECT * FROM shop_cart 
                WHERE cust_id = {cust_id} """
    result = exec(sql)       
    if (not result):       
        msg = F"Your shopping cart is empty"
        return        
    cart = result
    num  = len(result)
    msg  = F"You have {num} items in your shopping cart"
    
#=============================================================================
# Delete an item from the cart
#=============================================================================
def del_item(item_id):
    global msg;   
 
    sql = F""" DELETE FROM shop_cart
                WHERE cust_id = {cust_id}
                  AND item_id = {item_id} """  
    result = exec(sql)
    msg = 'Item deleted from your cart'
    
#=============================================================================
# Update quantity for all items
#=============================================================================
def upd_items():
    global msg  

    for item_id in input:
        qty = input.get(item_id)                #get the quantity entered
        if int(qty)==0:
            del_item(item_id)
        else:
            sql = F""" UPDATE shop_cart
                          SET qty = {qty}
                        WHERE cust_id = {cust_id}
                          AND item_id = {item_id} """
            result = exec(sql)
    msg = 'Item quantity adjusted'
    
#===============================================================================
# Display shopping cart in an HTML table
#===============================================================================
def display():
    global msg;   

    total_cart = 0

    print("""
        <html>
        <head>
        <title>Display Shopping cart</title>
        <style>
            a      {text-decoration:none; color:brown}
            table  {font-family:arial; font-size:11pt; background-color:f9f9f9; border:2px solid brown}
            td     {border:1px solid gray; text-align:center} 
            .left  {text-align:left}
            .right {text-align:right}
            .qty   {width:40px; text-align:center}
            .red   {color:white; background-color:brown; height:30px; border-radius:5px; cursor:pointer}
            .grn   {color:white; background-color:green; height:30px; border-radius:5px; cursor:pointer}
                 
        </style>
       </head>
       <body bgcolor=lightyellow>
       <h1><center>The Ice Cream Shop</center></h1>
    """)

    if(cart):
        print(F"<h3>{fname}, your shopping cart contains...</h3>")
        print(F"<form name=frm method=POST >")
        print("<table width=550>") 
        print("<tr bgcolor=tan><th>Delete<th>Qty<th>Product Id<th>Description<th>Product Type<th>Price<th>Total</th> \n")
        for item in cart:
            item_id = item['item_id']
            prod_id = item['prod_id']
            desc    = item['prod_desc']
            type    = item['type']
            price   = item['price']
            qty     = item['qty']
            tax     = 6.50
            if 'NY' in address: tax=8.85
            if 'NJ' in address: tax=6.62
            if 'CT' in address: tax=6.35
            total_amt   = int(qty) * float(price)
            total_cart += total_amt * (1+tax/100)  
            total_amt   = "{:.2f}".format(total_amt)
            print("<tr>")
            print(F"<th><a href=shopCart.py?del={item_id}><img src=img/delete.png title='delete' height=20px width=20px border=0></a></td>")
            print(F"<td><input class=qty type=number min=0 id={item_id} name={item_id} value={qty} onChange=document.frm.submit()>")
            print(F"<td>{prod_id}<td>{desc}<td>{type}<td class=right>${price}<td class=right>${total_amt}")
        total_cart = "{:.2f}".format(total_cart)
        print(F"<tr><th>-<td colspan=5 class=left><b>Sales Tax   <td class=right><b>  {tax:.2f}%")
        print(F"<tr><th>-<td colspan=5 class=left><b>Total Amount<td class=right><b>$ {total_cart}") 
        print("</table>")
        print("</form>")
    else:
        print("<font color=red>Your shopping cart is empty </font><br>")           

    print("""    
          <br> 
          <input type=button name=shop     value='Return to Shopping' class=red onClick=location.href='shopBrowse.py'>
             
          <input type=button name=checkout value='     Checkout     ' class=grn onClick=location.href='shopCheckout.py'>
          <hr> \n
          <center>
          <a href=shopBrowse.py>    shop          </a> |
                                    shopcart           |
          <a href=shopCheckoout.py> checkout      </a> | 
          <a href=shopQuery.py>     search orders </a> |
          <a href=shopProf.py>      profile       </a> |
          <a href=shop.py?out=y>    logout        </a>
          </center>
          </body>
          </html>
    """)
    
#===============================================================================
# main
#===============================================================================
cookies = COOKIE.getAll()                      		#get the cookies
cust_id = cookies.get('cust_id')  
if not cust_id:                                     #if there is no cust_id cookie --> not logged in
    print("Location: shop.py")  	         		#redirect to login page
    print('\n')										#end of response headers
    exit()

read_customer()

input   = WEB.input()                  				#obtain the input fields from screen
item_id = input.get('del')                     		#user wants to delete item 

if item_id:                                         #if delete cart item 
    del_item(item_id)
elif input:                                         #user wants to update quantity for item(s) 
    upd_items()

read_cart()        
print('\n')											#end of response headers
display()                                           #display the screen
 




#=== link to see the python code ================================================
import os
import 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
#================================================================================