<?php
$order = $mysql->get_array($mysql->query("discount_code,shipping,sales_tax,email_address", "fs_shop_orderdata", "owner = '{$_SESSION['owner']}' AND temp = 'y' LIMIT 1"));
if(!empty($order['discount_code']))
{
$code = $mysql->get_array($mysql->query("ID,type,value,all_products,min_spend,one_per_cust", "fs_shop_discountcodes", "code = '{$order['discount_code']}' LIMIT 1"));
$discount = 0;
//if discount code applies to selected products only, pass the product IDs to work out the discount
$discount_few_products = '';
if($code['all_products'] == 'n')
{
$query = $mysql->query("pid", "fs_shop_discountcodes_products", "discount_id = {$code['ID']}");
if($mysql->num_rows($query) > 0)
{
while($pids = $mysql->get_array($query))
{
$discount_few_products .= $pids['pid'].',';
}
$discount_few_products = 'AND `pid` IN ('.substr($discount_few_products, 0, -1).')';
}
}
//cart total ex shipping, amount we need to discount
$total = 0;
$qty = 0;
$query = $mysql->query("price,qty", "fs_shop_cart", "owner = '{$_SESSION['owner']}' AND temp = 'y' $discount_few_products");
while($data = $mysql->get_array($query))
{
$total += number_format($data['price']*$data['qty'], 2, '.', '');
$qty += $data['qty'];
}
//work out how much user is spending
$spending = 0;
$query = $mysql->query("(price*qty) AS price", "fs_shop_cart", "owner = '{$_SESSION['owner']}' AND temp = 'y'");
while($data = $mysql->get_array($query))
{
$spending += $data['price'];
}
//if code is to be used once per customer, checking using email address
//if customer has already used it, set the min spend value really high
if($code['one_per_cust'] == 'y' && $order['email_address'] != '')
{
$check = $mysql->num_rows($mysql->query("ID", "fs_shop_orderdata", "email_address = '{$order['email_address']}' AND temp = 'n' AND discount_code = '{$order['discount_code']}' AND discount_value > 0 LIMIT 1"));
if($check == 1)
{
$code['min_spend'] = 100000;
}
}
//if code is $ - apply to order total once only
if($code['type'] == '$' && $spending > 0 && $spending >= $code['min_spend'])
{
$discount = ($total-$code['value']);
$discount = ($discount <= 0) ? $total : $code['value'];
}
//if code is $p - apply to all products selected in the promo X qty
if($code['type'] == '*' && $spending > 0 && $spending >= $code['min_spend'])
{
$discount = ($code['value']*$qty);
$discount = ($discount <= 0) ? $total : $discount;
}
//if code is %
if($code['type'] == '%' && $spending > 0 && $spending >= $code['min_spend'])
{
$discount = ($total/100)*$code['value'];
$discount = ($discount > $total) ? $total : $discount;
}
//if the code is using min spend, make sure the discounted value is > than min spend for 100% discount promo codes
if($code['type'] == '%' && $code['value'] == 100 && ($spending-$discount) < $code['min_spend'])
{
$discount = 0;
}
//update order
$mysql->update("discount_value", number_format($discount, 2, '.', ''), "fs_shop_orderdata", "owner = '{$_SESSION['owner']}' AND temp = 'y' LIMIT 1");
//end
}
?>