This function successfully calculates a global percentage using a single discount code, although I’m having problems making the code discount a specific range of items instead of globally. The basket session holds id, name, desc, price, qty etc… but everything I’ve tried thus far has failed, I realize I need to implement it into the foreach loop (which I keep breaking or updates every item one way or another) or use a different method entirely but I’m really unsure as how to proceed.
I’m not an experienced PHP Dev by the way I just enjoy learning and working basic markup. Any helpful pointers someone can provide would be very much appreciated. Thanks!
$code = $this->request['code'];
$discount_status = 'NONE'; // no discount available / applied
if ( !empty($this->config['DISCOUNT_CODE']) && !empty($this->config['DISCOUNT_PERCENT']) && !empty($code) ) {
if ( $code == $this->config['DISCOUNT_CODE'] ) {
$discount_status = 'OK';
}
else {
$discount_status = 'ERROR';
}
}
// calculate basket total
$basket_value = 0;
$discount_factor = 1;
if ( $discount_status == 'OK' ) {
// apply discount
$discount_factor = ( 100 - $this->config['DISCOUNT_PERCENT'] ) / 100;
}
if ( !empty($_SESSION['basket']) && is_array($_SESSION['basket']) ) {
foreach( $_SESSION['basket'] as $basketItem ) {
// Apply discount to each item separately
$basket_value += sprintf("%.02f", $basketItem['detail_price'] * $discount_factor) * $basketItem['qty'];
}
}
// check delivery cost
$delivery_area = $this->DeliveryAreaManager->getRecord($this->request['da']);
if ( !empty($delivery_area['cost']) && ( $delivery_area['free_from'] <= 0 || $basket_value < $delivery_area['free_from'] ) ) {
$basket_value += $delivery_area['cost'];
}
// return JSON response
$data = JSONUtils::encode(
array(
'discount_status' => $discount_status,
'basket_value' => sprintf("%.02f", $basket_value),
)
);
return $data;
This:
Is saying to apply the discount to each item. It has no conditions. You would need to define the conditions that tell the code what to apply the discount to. This is extremely broad so we CAN’T tell you how to do this for YOU, but we CAN tell you how you MIGHT do it in a very horribly generic way…
Now, obviously I just made up $basketItem[‘discount_bracket’] to tell you that you can make discount tiers or some kind of discount identifier for an item via the database. In this case, I just use it to say if 1 then the item can be discounted. It’s up to you to make this do what you want it to do with what you have available. Seeing as we don’t know what you can do or what you have available, we are limited in what we can suggest.
This is just one way to handle things. If you narrow down your question I might update with a more specific example.