#!/usr/bin/env python3
#==================================================================================================
# Checkout - add an order to shop_order and shop_order_detail
# if no cookie cust_id, redirect to login page
#==================================================================================================
import cgi                            #cgi 
import cgitb                          #cgi with traceback error handling
import re
import config
import COOKIE
import DB

cgitb.enable()

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

customer = {}
cart     = []
firstname  = ""
lastname   = ""
address    = ""
email      = ""
ccType     = ""
creditCard = ""
tax        = ""

name_error  = ""
addr_error  = ""
email_error = ""
cc_error    = ""   
msg = "" 

#=============================================================================
# Validate all required input fields
#=============================================================================
def validate():
    global name_error,addr_error,email_error,cc_error,msg   
        
    if (not firstname or not lastname):
        msg         = 'error'      
        name_error  = '*' 
    if (not address):
        msg         = 'error'      
        addr_error  = '*' 
    if (not email):
        msg         = 'error'      
        email_error = '*' 
    if (not ccType or not creditCard):
        msg         = 'error'      
        cc_error    = '*' 

    if (msg == 'error'):
        msg  = "Please enter required field(s) above!"

#==============================================================================
# Display the HTML page
# repopulate the screen with previous entry data  
# if there are errors, highlight those with an error message
# product list comes from the database
#==============================================================================
def display():

    visa_checked = 'CHECKED' if (ccType == 'visa')        else ''
    mc_checked   = 'CHECKED' if (ccType == 'master-card') else ''
    amex_checked = 'CHECKED' if (ccType == 'amex')        else ''

    total_cart = 0

    print(F"""
        <html>
        <head>
        <style>
            a    {{text-decoration:none; color:brown}}
            .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>

        <h2>{firstname}, complete your order below</h2>
        <form method=POST >                          
        <fieldset style='width:580px;border-color:red'> 
        <legend>Enter Fields Below</legend> 
        <table> 
        <tr>
        <td><b>Enter First Name <font color=red> {name_error} </font>
        <td><input type=text name=firstname value='{firstname}'> 
            <b>  Last Name </b>
            <input type=text name=lastname value='{lastname}'>
        <tr>
        <td><b>Enter Address <font color=red> {addr_error} </font>
        <td><textarea name=address rows=4 style='width:430'>{address}</textarea> 
        <tr>
        <td><b>Email Address<font color=red> {email_error} </font>
        <td><input type=email name='email'  value='{email}' style='width:430'>
        <tr>        
        <td><b>Credit Card <font color=red> {cc_error} </font> 
        <td>
        <input type=radio name=ccType value='visa'        {visa_checked} /> Visa        
        <input type=radio name=ccType value='master-card' {mc_checked}   /> Master Card 
        <input type=radio name=ccType value='amex'        {amex_checked} /> Amex        
        <tr>
        <td><b>Card Number  
        <td><input type=text name='creditCard'  value='{creditCard}' style='width:430' placeholder='1234-1234-1234-1234' pattern='\d\d\d\d-\d\d\d\d-\d\d\d\d-\d\d\d\d' title='9999-9999-9999-9999'>
        </table>    
        </fieldset>
        <br><font color=red> {msg}  </font><br><br>         
    """)

    disabled = ''
    if(cart):
        print("""
            <fieldset style='width:580px;border-color:red'> 
            <legend>Your Shopping Cart</legend> 
            <table border=1>
            <tr bgcolor=tan><th>Product Id<th width=225>Description<th>Product Type<th width=50>Price<th>Qty<th width=60>Total</th> \n
        """)
        for item in cart:
            prod_id = item['prod_id']
            desc    = item['prod_desc']
            type    = item['type']
            price   = item['price']
            qty     = item['qty']
            tax     = compute_tax()
            total_amt   = int(qty) * float(price)
            total_cart += total_amt * (1+tax/100)  
            total_amt   = "{:.2f}".format(total_amt)
            print("<tr>")
            print(F"<td align=center>{prod_id}<td>{desc}<td>{type}<td align=right>${price}<td align=center>{qty}<td align=right>${total_amt}")
        total_cart = "{:.2f}".format(total_cart)
        print(F"<tr><td id=desc colspan=5><b>Sales Tax   <td align=right><b>  {tax:.2f}%")
        print(F"<tr><td id=desc colspan=5><b>Total Amount<td align=right><b>$ {total_cart}") 
        print("""
            </table>
            </fieldset> 
        """)        
    else:
        print("<h4>You Cart is Empty</h4>")
        disabled = 'disabled'

    print(F"""
        <br>           
        <input type=button class=red value='Return to Shopping' onClick=location.href='shopBrowse.py'>
        <input type=button class=red value='  Update Cart  '    onClick=location.href='shopCart.py'>
        <input type=submit class=grn value='  Place Order  '    name=order {disabled}>
        <br/>
         <hr/>
        <center>
        <a href=shopBrowse.py> shop          </a> |
        <a href=shopCart.py>   shopping cart </a> |
                               checkout           | 
        <a href=shopQuery.py>  search orders </a> |
        <a href=shopProf.py>   profile       </a> |
        <a href=shop.py?out=y> logout        </a>
        </center>
       </body>
       </html>
    """)
    
#=============================================================================
# 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)
        if isinstance(result,str): msg=result; return       #database error 
    else:
        result = DB.update(sql)

    return result
    conn.close()                                            #close the connection
    
#=============================================================================
# Read data from the customer table
#=============================================================================
def read_customer():
    global customer, firstname, lastname, address, email, 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        
    customer  = result[0]                                   #take first row
    firstname = customer.get('fname')
    lastname  = customer.get('lname')
    address   = customer.get('address')
    email     = customer.get('email')
                    
#=============================================================================
# Read data from shopping cart table
#=============================================================================
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
    
#===============================================================================
# Write data to database (cust_order & cust_order_detail tables)
#===============================================================================
def write_data():
    global msg

    firstname2  = re.sub("[;<>\/'&]","",firstname)               #eliminate ;<>\/'& characters 
    lastname2   = re.sub("[;<>\/'&]","",lastname) 
    address2    = re.sub("[;<>\/'&]","",address) 
    email2      = re.sub("[;<>\/'&]","",email) 
    creditCard2 = re.sub("[;<>\/'&]","",creditCard) 

    conn = DB.connect('demo2','demo2','demo2','mysql')

    sql = F"""INSERT INTO shop_order 
              VALUES(0,'{cust_id}','{firstname2}','{lastname2}',
                       '{address2}','{email2}','{creditCard}',NOW() ) """
    result = DB.insert(sql)             

    sql = "SELECT LAST_INSERT_ID()";                    #retrieve order_id PK       
    result = DB.select(sql)                    

    first_row = result[0]                               #take first row
    order_id  = first_row['LAST_INSERT_ID()']           #take the value of last_insert_id
    
    read_cart()                                         #read the shopping cart
    tax = compute_tax()

    for item in cart:
        sql = F"""INSERT INTO shop_order_detail 
                  VALUES(0,'{order_id}','{item['prod_id']}','{item['prod_desc']}',
                         '{item['type']}',{item['price']},{item['qty']},{tax}) """
        result = DB.insert(sql)             
       
    conn.close()                                        #close the connection
    msg = 'Order processed successfully!!!';

#=============================================================================
# Delete cart data from DB - Delete cart data from the database
#=============================================================================
def delete_cart():
 
    sql = F"""DELETE FROM shop_cart
               WHERE cust_id = '{cust_id}' """
    result = DB.delete(sql)             

#=============================================================================
# Delete cart data from DB - Delete cart data from the database
#=============================================================================
def compute_tax(): 
    tax  = 6.50
    if 'NY' in address: tax=8.85
    if 'NJ' in address: tax=6.62
    if 'CT' in address: tax=6.35
    return(tax)
        
#=============================================================================
# main code
#=============================================================================
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 the response headers
    exit()
    
read_customer()                                         #read customer data
read_cart()                                         	#read shopping cart data

input   = cgi.FieldStorage()                            #obtain the input fields from screen

if input:                                               #if 2nd & subsequent times
    firstname  = input.getvalue('firstname')  or ""     #get HTML form entry fields 
    lastname   = input.getvalue('lastname')   or ""
    address    = input.getvalue('address')    or ""
    email      = input.getvalue('email')      or ""
    ccType     = input.getvalue('ccType')     or ""
    creditCard = input.getvalue('creditCard') or ""
    validate()                                          #validate form fields   
    if not msg:                                         #if no error msg
        write_data();                                   #insert a new order into tables shop_order and shop_order_detail
        delete_cart();                                  #delete shopping cart
    
print('\n')                                             #end the 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
#================================================================================