CMXX - API based checkout

This commit is contained in:
“VeLiTi”
2025-02-12 11:16:41 +01:00
parent 8201d7804b
commit 2eaf83c3fe
8 changed files with 611 additions and 747 deletions

180
cart.php
View File

@@ -1,5 +1,5 @@
<?php <?php
// Prevent direct access to file // Prevent direct access to file
defined(security_key) or exit; defined(security_key) or exit;
// Remove product from cart, check for the URL param "remove", this is the product id, make sure it's a number and check if it's in the cart // Remove product from cart, check for the URL param "remove", this is the product id, make sure it's a number and check if it's in the cart
if (isset($_GET['remove']) && is_numeric($_GET['remove']) && isset($_SESSION['cart']) && isset($_SESSION['cart'][$_GET['remove']])) { if (isset($_GET['remove']) && is_numeric($_GET['remove']) && isset($_SESSION['cart']) && isset($_SESSION['cart'][$_GET['remove']])) {
@@ -90,42 +90,23 @@ if (isset($_POST['samples'])){
} }
} }
// Check the session variable for products in cart // Check the session variable for products in cart
$products_in_cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : []; $products_in_cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : [];
$subtotal = 0.00; $subtotal = 0.00;
// If there are products in cart foreach ($products_in_cart as $num => $product) {
if ($products_in_cart) { // Calculate the subtotal
// There are products in the cart so we need to select those products from the database $subtotal += (float)$product['options_price'] * (int)$product['quantity'];
// Products in cart array to question mark string array, we need the SQL statement to include: IN (?,?,?,...etc)
$array_to_question_marks = implode(',', array_fill(0, count($products_in_cart), '?'));
// Prepare SQL statement
// $stmt = $pdo->prepare('SELECT p.id, pc.category_id, p.* FROM products p LEFT JOIN products_categories pc ON p.id = pc.product_id LEFT JOIN categories c ON c.id = pc.category_id WHERE p.id IN (' . $array_to_question_marks . ') GROUP BY p.id');
$stmt = $pdo->prepare('SELECT p.*, (SELECT m.full_path FROM products_media pm JOIN media m ON m.id = pm.media_id WHERE pm.product_id = p.id ORDER BY pm.position ASC LIMIT 1) AS img FROM products p WHERE p.id IN (' . $array_to_question_marks . ')');
// Leverage the array_column function to retrieve only the id's of the products
$stmt->execute(array_column($products_in_cart, 'id'));
// Fetch the products from the database and return the result as an Array
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Iterate the products in cart and add the meta data (product name, desc, etc)
foreach ($products_in_cart as &$cart_product) {
foreach ($products as $product) {
if ($cart_product['id'] == $product['id']) {
$cart_product['meta'] = $product;
// Calculate the subtotal
$subtotal += (float)$cart_product['options_price'] * (int)$cart_product['quantity'];
}
}
}
} }
?>
<?=template_header('Shopping Cart')?>
template_header('Shopping Cart');
$view = '
<div class="cart content-wrapper"> <div class="cart content-wrapper">
<h1><?=$h1_cart_name?></h1> <h1>'.$h1_cart_name.'</h1>
<h2 style="text-align: center;margin-top: -35px;"> <h2 style="text-align: center;margin-top: -35px;">
<a href="<?=url(link_to_collection)?>" style="text-decoration: none;color: #555555;padding: 10px 10px;font-size: 10px;"> <a href="'.url(link_to_collection).'" style="text-decoration: none;color: #555555;padding: 10px 10px;font-size: 10px;">
<?=$navigation_back_to_store?> '.$navigation_back_to_store.'
</a> </a>
</h2> </h2>
@@ -133,88 +114,105 @@ if ($products_in_cart) {
<table> <table>
<thead> <thead>
<tr> <tr>
<td colspan="2"><?=$tr_product?></td> <td colspan="2">'.$tr_product.'</td>
<td class="rhide"></td> <td class="rhide"></td>
<td class="rhide"><?=$tr_price?></td> <td class="rhide">'.$tr_price.'</td>
<td><?=$tr_quantity?></td> <td>'.$tr_quantity.'</td>
<td><?=$tr_total?></td> <td>'.$tr_total.'</td>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>';
<?php if (empty($products_in_cart)): ?> if (empty($products_in_cart)){
$view .= '
<tr> <tr>
<td colspan="6" style="text-align:center;"><?=$cart_message_empty?></td> <td colspan="6" style="text-align:center;">'.$cart_message_empty.'</td>
</tr> </tr>';
<?php else: ?> } else {
<?php foreach ($products_in_cart as $num => $product): ?> foreach ($products_in_cart as $num => $product){
// Ensure product price is a numeric value
$product['options_price'] = isset($product['options_price']) && $product['options_price'] > 0 ? floatval($product['options_price']) : 0.00;
if (isset($product['options']) && $product['options'] !=''){
$prod_options = '';
foreach ($product['options'] as $prod_opt){
$prod_options .= (${$prod_opt} ?? $prod_opt).', ';
}
}
$view .= '
<tr> <tr>
<td class="img"> <td class="img">';
<?php if (!empty($product['meta']['img']) && file_exists($product['meta']['img'])): ?> if (!empty($product['meta']['img'])){
<a href="<?=url('index.php?page=product&id=' . $product['id'])?>"> $view .= ' <a href="'.url('index.php?page=product&id=' . $product['id']).'">
<img src="<?=base_url?><?=$product['meta']['img']?>" width="50" height="50" alt="<?=$product['meta']['name']?>"> <img src="'.$img_url.$product['meta']['img'].'" width="50" height="50" alt="'.$product['meta']['name'].'">
</a> </a>';
<?php endif; ?> }
</td> $view .= '</td>
<td> <td>
<a href="<?=url('index.php?page=product&id=' . $product['id'])?>"><?=$product['meta']['name']?></a> <a href="'.url('index.php?page=product&id=' . $product['id']).'">'.(${$product['meta']['name']} ?? $product['meta']['name']).'</a>
<br> <br>
<a href="<?=url('index.php?page=cart&remove=' . $num)?>" class="remove">Remove</a> <a href="'.url('index.php?page=cart&remove=' . $num).'" class="remove">Remove</a>
</td> </td>
<td class="options rhide"> <td class="options rhide">
<?=htmlspecialchars(str_replace(',', ', ', $product['options']), ENT_QUOTES)?> '.htmlspecialchars(substr($prod_options, 0,-2), ENT_QUOTES).'
<input type="hidden" name="options" value="<?=htmlspecialchars($product['options'], ENT_QUOTES)?>"> <input type="hidden" name="options" value="['.implode(',',$product['options']).']">
</td> </td>
<td class="price rhide"><?=currency_code?><?=number_format($product['options_price'],2)?></td> <td class="price rhide">'.currency_code.''.number_format($product['options_price'],2).'</td>';
<?php if ($product['options'] == $h2_cart_sample_product && !empty(category_id_checkout_samples)) : ?>
<td class="quantity"> if ($product['options'] == $h2_cart_sample_product && !empty(category_id_checkout_samples)){
<input type="number" class="ajax-update" name="quantity-<?=$num?>" value="1" min="1" max="1" placeholder="Quantity" readonly>
</td> $view .= '
<?php else: ?> <td class="quantity">
<td class="quantity"> <input type="number" class="ajax-update" name="quantity-'.$num.'" value="1" min="1" max="1" placeholder="Quantity" readonly>
<input type="number" class="ajax-update" name="quantity-<?=$num?>" value="<?=$product['quantity']?>" min="1" <?php if ($product['meta']['quantity'] != -1): ?>max="<?=$product['meta']['quantity']?>"<?php endif; ?> placeholder="Quantity" required> </td>';
</td> } else {
<?php endif; ?> $view .= '
<td class="price product-total"><?=currency_code?><?=number_format($product['options_price'] * $product['quantity'],2)?></td> <td class="quantity">
</tr> <input type="number" class="ajax-update" name="quantity-'.$num.'" value="'.$product['quantity'].'" min="1" placeholder="Quantity" required>
<?php endforeach; ?> </td>';
<?php endif; ?> }
</tbody> $view .= ' <td class="price product-total">'.currency_code.''.number_format($product['options_price'] * $product['quantity'],2).'</td>
</tr>';
}
}
$view .= '</tbody>
</table> </table>
</form> </form>';
<?php if (!empty($products_in_cart) && !empty(category_id_checkout_suggestions)): ?>
<?=getAccessoiries($pdo,category_id_checkout_suggestions)?> //SUGGESTIONS
<?php endif; ?> if (!empty($products_in_cart) && !empty(category_id_checkout_suggestions)){
<?php if (!empty($products_in_cart) && !empty(category_id_checkout_samples)): ?> $view .= getAccessoiries($pdo,category_id_checkout_suggestions);
<?=getSamples($pdo,category_id_checkout_samples)?> }
<?php endif; ?> // SAMPLES
if (!empty($products_in_cart) && !empty(category_id_checkout_samples)){
$view .= getSamples($pdo,category_id_checkout_samples);
}
$view .= '
<div class="total"> <div class="total">
<span class="text"><?=$total_subtotal?></span> <span class="text">'.$total_subtotal.'</span>
<span class="price"><?=currency_code?><?=number_format($subtotal,2)?></span> <span class="price">'.currency_code.''.number_format($subtotal,2).'</span>
<span class="note"><?=$total_note?></span> <span class="note">'.$total_note.'</span>
</div> </div>
<div class="buttons"> <div class="buttons">
<input type="submit" form ="cart-form" value="<?=$btn_emptycart?>" name="emptycart" class="btn" title="Remove cart" style="background:none;"> <input type="submit" form ="cart-form" value="'.$btn_emptycart.'" name="emptycart" class="btn" title="Remove cart" style="background:none;">
<input type="submit" form ="cart-form" value="<?=$btn_update?>" name="update" class="btn" title="Refresh cart"> <input type="submit" form ="cart-form" value="'.$btn_update.'" name="update" class="btn" title="Refresh cart">
<input type="submit" form ="cart-form" value="<?=$btn_checkout?>" name="checkout" class="btn" style="background-color:green;"> <input type="submit" form ="cart-form" value="'.$btn_checkout.'" name="checkout" class="btn" style="background-color:green;">
</div> </div>
<h4 style="text-align: right;margin-top: -35px;"> <h4 style="text-align: right;margin-top: -35px;">
<a href="<?=url(link_to_collection)?>" style="text-decoration: none;color: #555555;padding: 10px 10px;font-size: 10px;"> <a href="'.url(link_to_collection).'" style="text-decoration: none;color: #555555;padding: 10px 10px;font-size: 10px;">
<?=$navigation_back_to_store?> '.$navigation_back_to_store.'
</a> </a>
</h4> </h4>
</div> </div>
<script> ';
const buttonRight = document.getElementById("slideRight");
const buttonLeft = document.getElementById("slideLeft");
buttonRight.onclick = function() { //OUTPUT
document.getElementById('add_samples_container').scrollLeft += 50; echo $view;
};
buttonLeft.onclick = function() { template_footer();
document.getElementById('add_samples_container').scrollLeft -= 50;
}; ?>
</script>
<?=template_footer()?>

View File

@@ -1,26 +1,54 @@
<?php <?php
// Prevent direct access to file // Prevent direct access to file
defined(security_key) or exit; defined(security_key) or exit;
// Default values for the input form elements
// ---------------------------------------
// Defaults
// ---------------------------------------
$account = [ $account = [
'first_name' => '', 'account_id' => $_POST['account_id'] ?? '',
'last_name' => '', 'email' => $_POST['email'] ?? '',
'address_street' => '', 'first_name' => $_POST['first_name'] ?? '',
'address_city' => '', 'last_name' => $_POST['last_name'] ?? '',
'address_state' => '', 'address_street' => $_POST['address_street'] ?? '',
'address_zip' => '', 'address_city' => $_POST['address_city'] ?? '',
'address_country' => '', 'address_state' => $_POST['address_state'] ?? '',
'role' => 'Member', 'address_zip' => $_POST['address_zip'] ?? '',
'address_phone' => '' 'address_country' => $_POST['address_country'] ?? '',
'address_phone' => $_POST['address_phone'] ?? ''
]; ];
$products_in_cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : [];
$subtotal = 0.00;
$total = 0.00;
$shippingtotal = 0.00;
$discounttotal = 0.00;
$taxtotal = 0.00;
$tax_rate = '';
$weighttotal = 0;
$checkout_input = [
"selected_country" => isset($_POST['address_country']) ? $_POST['address_country'] : $account['address_country'],
"selected_shipment_method" => isset($_POST['shipping_method']) ? $_POST['shipping_method'] : null,
"business_type" => 'b2c',
"discount_code" => isset($_SESSION['discount']) ? $_SESSION['discount'] : null
];
$selected_shipping_method_name = '';
$shipping_methods_available = [];
// Error array, output errors on the form // Error array, output errors on the form
$errors = []; $errors = [];
// ---------------------------------------
// ---------------------------------------
// ---------------------------------------
// Redirect the user if the shopping cart is empty // Redirect the user if the shopping cart is empty
if (empty($_SESSION['cart'])) { if (empty($_SESSION['cart'])) {
header('Location: ' . url('index.php?page=cart')); header('Location: ' . url('index.php?page=cart'));
exit; exit;
} }
// Check if user is logged in // Check if user is logged in
if (isset($_SESSION['account_loggedin'])) { if (isset($_SESSION['account_loggedin'])) {
$stmt = $pdo->prepare('SELECT * FROM accounts WHERE id = ?'); $stmt = $pdo->prepare('SELECT * FROM accounts WHERE id = ?');
@@ -34,173 +62,48 @@ if (isset($_POST['discount_code']) && !empty($_POST['discount_code'])) {
} else if (isset($_POST['discount_code']) && empty($_POST['discount_code']) && isset($_SESSION['discount'])) { } else if (isset($_POST['discount_code']) && empty($_POST['discount_code']) && isset($_SESSION['discount'])) {
unset($_SESSION['discount']); unset($_SESSION['discount']);
} }
//-------------------------------
// Variables // If there are products in cart handle the checkout
$products_in_cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : []; //-------------------------------
$subtotal = 0.00;
$shippingtotal = 0.00;
$discounttotal = 0.00;
$taxtotal = 0.00;
$weighttotal = 0;
$selected_country = isset($_POST['address_country']) ? $_POST['address_country'] : $account['address_country'];
$selected_shipping_method = isset($_POST['shipping_method']) ? $_POST['shipping_method'] : null;
$selected_shipping_method_name = '';
$shipping_methods_available = [];
// If there are products in cart
if ($products_in_cart) { if ($products_in_cart) {
// There are products in the cart so we need to select those products from the database
// Products in cart array to question mark string array, we need the SQL statement to include: IN (?,?,?,...etc) //Calculate shopping_cart
$array_to_question_marks = implode(',', array_fill(0, count($products_in_cart), '?')); $payload = json_encode(array("cart" => $products_in_cart, "checkout_input" => $checkout_input), JSON_UNESCAPED_UNICODE);
$stmt = $pdo->prepare('SELECT p.*, (SELECT m.full_path FROM products_media pm JOIN media m ON m.id = pm.media_id WHERE pm.product_id = p.id ORDER BY pm.position ASC LIMIT 1) AS img, (SELECT GROUP_CONCAT(pc.category_id) FROM products_categories pc WHERE pc.product_id = p.id) AS categories FROM products p WHERE p.id IN (' . $array_to_question_marks . ')'); $products_in_cart = ioAPIv2('/v2/checkout/',$payload,$clientsecret);
// We use the array_column to retrieve only the id's of the products $products_in_cart = json_decode($products_in_cart,true);
$stmt->execute(array_column($products_in_cart, 'id'));
// Fetch the products from the database and return the result as an Array //GET SPECIFIC TOTALS FROM API RESULTS
$products = $stmt->fetchAll(PDO::FETCH_ASSOC); $subtotal = $products_in_cart['totals']['subtotal'];
// Retrieve the discount code $shippingtotal = $products_in_cart['totals']['shippingtotal'];
if (isset($_SESSION['discount'])) { $discounttotal = $products_in_cart['totals']['discounttotal'];
$stmt = $pdo->prepare('SELECT * FROM discounts WHERE discount_code = ?'); $taxtotal = $products_in_cart['totals']['taxtotal'];
$stmt->execute([ $_SESSION['discount'] ]); $tax_rate = $products_in_cart['totals']['tax_rate'];
$discount = $stmt->fetch(PDO::FETCH_ASSOC); $weighttotal = $products_in_cart['totals']['weighttotal'];
} $total = $products_in_cart['totals']['total'];
// Get tax $selected_country = isset($_POST['address_country']) ? $_POST['address_country'] : $account['address_country'];
$stmt = $pdo->prepare('SELECT * FROM taxes WHERE country = ?'); $selected_shipping_method = isset($_POST['shipping_method']) ? $_POST['shipping_method'] : null;
$stmt->execute([ isset($_POST['address_country']) ? $_POST['address_country'] : $account['address_country'] ]); $selected_shipping_method_name = '';
$tax = $stmt->fetch(PDO::FETCH_ASSOC);
$tax_rate = $tax ? $tax['rate'] : 0.00;
// Get the current date
$current_date = strtotime((new DateTime())->format('Y-m-d H:i:s'));
// Retrieve shipping methods // Retrieve shipping methods
$stmt = $pdo->query('SELECT * FROM shipping'); $stmt = $pdo->query('SELECT * FROM shipping');
$shipping_methods = $stmt->fetchAll(PDO::FETCH_ASSOC); $shipping_methods = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Iterate the products in cart and add the meta data (product name, desc, etc)
foreach ($products_in_cart as &$cart_product) {
foreach ($products as $product) {
if ($cart_product['id'] == $product['id']) {
// If product no longer in stock, prepare for removal
if ((int)$product['quantity'] === 0) {
$cart_product['remove'] = 1;
} else {
$cart_product['meta'] = $product;
// Prevent the cart quantity exceeding the product quantity
$cart_product['quantity'] = ($cart_product['quantity'] > $product['quantity'] && $product['quantity'] !== -1) ? $product['quantity'] : $cart_product['quantity'];
$product_weight = $cart_product['options_weight'];
$weighttotal += $product_weight;
// Calculate the subtotal
$product_price = (float)$cart_product['options_price'];
$subtotal += $product_price * (int)$cart_product['quantity'];
// Calculate the final price, which includes tax
$cart_product['final_price'] = $product_price; //+ (($tax_rate / 100) * $product_price);
//-------------------------------
//TAX ON TOP OFF OF PRICE
//-------------------------------
//$taxtotal += (($tax_rate / 100) * $product_price) * (int)$cart_product['quantity'];
//-------------------------------
//TAX INCLUDED IN PRICE
//-------------------------------
$taxtotal += ($product_price - ($product_price/ (1 + ($tax_rate / 100))))* (int)$cart_product['quantity'];
//-------------------------------
//-------------------------------
// Check which products are eligible for a discount
if (isset($discount) && $discount && $current_date >= strtotime($discount['start_date']) && $current_date <= strtotime($discount['end_date'])) {
// Check whether product list is empty or if product id is whitelisted
if (empty($discount['product_ids']) || in_array($product['id'], explode(',', $discount['product_ids']))) {
// Check whether category list is empty or if category id is whitelisted
if (empty($discount['category_ids']) || array_intersect(explode(',', $product['categories']), explode(',', $discount['category_ids']))) {
$cart_product['discounted'] = true;
}
}
}
}
}
}
}
// Remove products that are out of stock
for ($i = 0; $i < count($products_in_cart); $i++) {
if (isset($products_in_cart[$i]['remove'])) {
unset($_SESSION['cart'][$i]);
unset($products_in_cart[$i]);
}
}
$_SESSION['cart'] = array_values($_SESSION['cart']);
$products_in_cart = array_values($products_in_cart);
// Redirect the user if the shopping cart is empty // Redirect the user if the shopping cart is empty
if (empty($products_in_cart)) { if (empty($products_in_cart)) {
header('Location: ' . url('index.php?page=cart')); header('Location: ' . url('index.php?page=cart'));
exit; exit;
} }
// Calculate the shipping
foreach ($products_in_cart as &$cart_product) {
foreach ($shipping_methods as $shipping_method) {
// Product weight
$product_weight = $cart_product['options_weight'] ? $cart_product['options_weight'] : $weighttotal;
// Determine the price
$product_price = $shipping_method['type'] == 'Single Product' ? (float)$cart_product['options_price'] : $subtotal;
// Check if no country required or if shipping method only available in specified countries
if (empty($shipping_method['countries']) || in_array($selected_country, explode(',', $shipping_method['countries']))) {
// Compare the price and weight to meet shipping method requirements
if ($shipping_method['id'] == $selected_shipping_method && $product_price >= $shipping_method['price_from'] && $product_price <= $shipping_method['price_to'] && $product_weight >= $shipping_method['weight_from'] && $product_weight <= $shipping_method['weight_to']) {
if ($shipping_method['type'] == 'Single Product') {
// Calculate single product price
$cart_product['shipping_price'] += (float)$shipping_method['price'] * (int)$cart_product['quantity'];
$shippingtotal += $cart_product['shipping_price'];
} else {
// Calculate entire order price
$cart_product['shipping_price'] = (float)$shipping_method['price'] / count($products_in_cart);
$shippingtotal = (float)$shipping_method['price'];
}
$shipping_methods_available[] = $shipping_method['id'];
} else if ($product_price >= $shipping_method['price_from'] && $product_price <= $shipping_method['price_to'] && $product_weight >= $shipping_method['weight_from'] && $product_weight <= $shipping_method['weight_to']) {
// No method selected, so store all methods available
$shipping_methods_available[] = $shipping_method['id'];
}
}
// Update selected shipping method name
if ($shipping_method['id'] == $selected_shipping_method) {
$selected_shipping_method_name = $shipping_method['name'];
}
}
}
// Number of discounted products
$num_discounted_products = count(array_column($products_in_cart, 'discounted'));
// Iterate the products and update the price for the discounted products
foreach ($products_in_cart as &$cart_product) {
if (isset($cart_product['discounted']) && $cart_product['discounted']) {
$price = &$cart_product['final_price'];
if ($discount['discount_type'] == 'Percentage') {
$d = (float)$price * ((float)$discount['discount_value'] / 100);
//$price -= $d;
$discounttotal += $d * (int)$cart_product['quantity'];
}
if ($discount['discount_type'] == 'Fixed') {
$d = (float)$discount['discount_value'] / $num_discounted_products;
//$price -= $d / (int)$cart_product['quantity'];
$discounttotal += $d;
}
}
}
//Override TAXTOTAAL IN CASE OF DISCOUNTS
//-------------------------------
//TAX ON TOP OFF OF PRICE
//-------------------------------
//$taxtotal = ($tax_rate / 100) * (($subtotal) - $discounttotal);
//-------------------------------
//TAX INCLUDED IN PRICE
//-------------------------------
$taxable_total = $subtotal - $discounttotal;
$taxtotal = $taxable_total - ($taxable_total / (1 + ($tax_rate / 100)));
//------------------------------- //-------------------------------
// END Checkout handler
//------------------------------- //-------------------------------
} }
//-------------------------------
//Place order
//-------------------------------
// Make sure when the user submits the form all data was submitted and shopping cart is not empty // Make sure when the user submits the form all data was submitted and shopping cart is not empty
if (isset($_POST['method'], $_POST['first_name'], $_POST['last_name'], $_POST['address_street'], $_POST['address_city'], $_POST['address_state'], $_POST['address_zip'], $_POST['address_country'], $_POST['address_phone'], $_SESSION['cart']) && !isset($_POST['update'])) { if (isset($_POST['method'], $_POST['first_name'], $_POST['last_name'], $_POST['address_street'], $_POST['address_city'], $_POST['address_state'], $_POST['address_zip'], $_POST['address_country'], $_POST['address_phone'], $_SESSION['cart']) && !isset($_POST['update'])) {
$account_id = null; $account_id = null;
@@ -243,56 +146,42 @@ if (isset($_POST['method'], $_POST['first_name'], $_POST['last_name'], $_POST['a
} }
if (!$errors && $products_in_cart) { if (!$errors && $products_in_cart) {
$payment_amount = (($subtotal)-$discounttotal)+$shippingtotal; //Process checkout
// No errors, process the order //Calculate shopping_cart
if (pay_on_delivery_enabled && $_POST['method'] == 'payondelivery') { $payload = json_encode(array("cart" => $products_in_cart, "checkout_input" => $checkout_input, "customer_details" => $account), JSON_UNESCAPED_UNICODE);
// Process Normal Checkout $place_order = ioAPIv2('/v2/placeorder/',$payload,$clientsecret);
// Generate unique transaction ID $place_order = json_decode($products_in_cart,true);
$transaction_id = strtoupper(uniqid('SC') . substr(md5(mt_rand()), 0, 5));
// Insert transaction into database //Check if transaction is succesfull and send order confirmation to customer
$stmt = $pdo->prepare('INSERT INTO transactions (txn_id, payment_amount, payment_status, created, payer_email, first_name, last_name, address_street, address_city, address_state, address_zip, address_country, account_id, payment_method, shipping_method, shipping_amount, discount_code, address_phone,tax_amount) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)'); if ($place_order['error'] == '' && $place_order['id'] != ''){
$stmt->execute([
$transaction_id, //SEND CONFIRMATION TO CUSTOMER
$payment_amount, send_order_details_email(
default_payment_status, $account['email'],
date('Y-m-d H:i:s'), $products_in_cart,
isset($account['email']) && !empty($account['email']) ? $account['email'] : $_POST['email'], $account['first_name'],
$_POST['first_name'], $account['last_name'],
$_POST['last_name'], $account['address_street'],
$_POST['address_street'], $account['address_city'],
$_POST['address_city'], $account['address_state'],
$_POST['address_state'], $account['address_zip'],
$_POST['address_zip'], $account['address_country'],
$_POST['address_country'], $place_order['subtotal'],
$account_id, $place_order['discounttotal'],
'PayOnDelivery', $place_order['shippingtotal'],
$selected_shipping_method_name, $place_order['taxtotal'],
$shippingtotal, $place_order['payment_amount'],
isset($_SESSION['discount']) ? $_SESSION['discount'] : '', $place_order['transaction_id']
$_POST['address_phone'], );
$taxtotal }
]);
// Get order ID //Pay on delivery = 2
$order_id = $pdo->lastInsertId(); if (pay_on_delivery_enabled && $place_order['payment_method'] == 2){
// Iterate products and deduct quantities
foreach ($products_in_cart as $product) { //header('Location: ' . url('index.php?page=placeorder'));
// For every product in the shopping cart insert a new transaction into our database //exit;
$stmt = $pdo->prepare('INSERT INTO transactions_items (txn_id, item_id, item_price, item_quantity, item_options) VALUES (?,?,?,?,?)'); }
$stmt->execute([ $transaction_id, $product['id'], $product['final_price'], $product['quantity'], $product['options'] ]); /*
// Update product quantity in the products table
$stmt = $pdo->prepare('UPDATE products SET quantity = quantity - ? WHERE quantity > 0 AND id = ?');
$stmt->execute([ $product['quantity'], $product['id'] ]);
// Deduct option quantities
if ($product['options']) {
$options = explode(',', $product['options']);
foreach ($options as $opt) {
$option_name = explode('-', $opt)[0];
$option_value = explode('-', $opt)[1];
$stmt = $pdo->prepare('UPDATE products_options SET quantity = quantity - ? WHERE quantity > 0 AND title = ? AND (name = ? OR name = "")');
$stmt->execute([ $product['quantity'], $option_name, $option_value ]);
}
}
}
//Disable giftcard //Disable giftcard
if (isset($_SESSION['discount'])){ if (isset($_SESSION['discount'])){
if (preg_match("/[#][0-9]/", $_SESSION['discount']) == 1){ if (preg_match("/[#][0-9]/", $_SESSION['discount']) == 1){
@@ -328,8 +217,7 @@ if (isset($_POST['method'], $_POST['first_name'], $_POST['last_name'], $_POST['a
); );
header('Location: ' . url('index.php?page=placeorder')); header('Location: ' . url('index.php?page=placeorder'));
exit; exit;
*/
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Mollie ++++++++++++++++++++++++++++++++++++++++++++++++++++ // Mollie ++++++++++++++++++++++++++++++++++++++++++++++++++++
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
@@ -415,7 +303,7 @@ if (isset($_POST['method'], $_POST['first_name'], $_POST['last_name'], $_POST['a
/* /*
* Payment parameters: * Payment parameters:
* amount Amount in EUROs. This example creates a € 10,- payment. * amount Amount in EUROs.
* description Description of the payment. * description Description of the payment.
* redirectUrl Redirect location. The customer will be redirected there after the payment. * redirectUrl Redirect location. The customer will be redirected there after the payment.
* webhookUrl Webhook location, used to report when the payment changes state. * webhookUrl Webhook location, used to report when the payment changes state.
@@ -560,207 +448,197 @@ if (isset($_POST['method'], $_POST['first_name'], $_POST['last_name'], $_POST['a
} }
} }
// Preserve form details if the user encounters an error
$account = [
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'address_street' => $_POST['address_street'],
'address_city' => $_POST['address_city'],
'address_state' => $_POST['address_state'],
'address_zip' => $_POST['address_zip'],
'address_country' => $_POST['address_country'],
'address_phone' => $_POST['address_phone']
];
} }
//-------------------------------
// END PLACE ORDER
//-------------------------------
$terms_link = url('index.php?page=termsandconditions'); $terms_link = url('index.php?page=termsandconditions');
?> template_header('Checkout');
<?=template_header('Checkout')?>
$view = '
<div class="checkout content-wrapper"> <div class="checkout content-wrapper">
<h1><?=$h1_checkout?></h1> <h1>'.$h1_checkout.'</h1>
<p class="error"><?=implode('<br>', $errors)?></p> <p class="error">'.implode('<br>', $errors).'</p>';
<?php if (!isset($_SESSION['account_loggedin'])): ?> if (!isset($_SESSION['account_loggedin'])){
<p><?=$account_available?> <a href="<?=url('index.php?page=myaccount')?>"><?=$account_log_in?></a></p> $view .= '<p>'.$account_available.' <a href="'.url('index.php?page=myaccount').'">'.$account_log_in.'</a></p>';
<?php endif; ?> }
$view .= '
<form action="" method="post"> <form action="" method="post">
<div class="container"> <div class="container">
<div class="shipping-details"> <div class="shipping-details">
<div id="dropin-container"></div> <div id="dropin-container"></div>
<h2><?=$payment_method?></h2> <h2>'.$payment_method.'</h2>
<div class="payment-methods"> <div class="payment-methods">';
<?php if (mollie_enabled): ?> if (mollie_enabled){
<input id="mollie" type="radio" name="method" value="mollie" <?= ((mollie_default)? 'checked':'') ?>> $view .= ' <input id="mollie" type="radio" name="method" value="0" '. ((mollie_default)? 'checked':'') .'>
<label for="mollie"> <label for="mollie">
<img src="./custom/assets/iDEAL.png" style="width: 50px;" alt="<?=$payment_method_1?>"> <img src="./custom/assets/iDEAL.png" style="width: 50px;" alt="'.$payment_method_1.'">
<img src="./custom/assets/bancontact.png" style="width: 50px;" alt="<?=$payment_method_1?>"> <img src="./custom/assets/bancontact.png" style="width: 50px;" alt="'.$payment_method_1.'">
</label> </label>';
<?php endif; ?> }
<?php if (paypal_enabled): ?> if (paypal_enabled){
<input id="paypal" type="radio" name="method" value="paypal" <?= ((paypal_default)? 'checked':'') ?>> $view .= ' <input id="paypal" type="radio" name="method" value="1" '. ((paypal_default)? 'checked':'') .'>
<label for="paypal"><img src="https://www.paypalobjects.com/webstatic/mktg/Logo/pp-logo-100px.png" alt="PayPal Logo"></label> <label for="paypal"><img src="https://www.paypalobjects.com/webstatic/mktg/Logo/pp-logo-100px.png" alt="PayPal Logo"></label>';
<?php endif; ?> }
<?php if (pay_on_delivery_enabled): ?> if (pay_on_delivery_enabled){
<input id="payondelivery" type="radio" name="method" value="payondelivery" <?= ((pay_on_delivery_default)? 'checked':'') ?> > $view .= ' <input id="payondelivery" type="radio" name="method" value="2" '. ((pay_on_delivery_default)? 'checked':'') .' >
<label for="payondelivery"><?=$payment_method_2?></label> <label for="payondelivery">'.$payment_method_2.'</label>';
<?php endif; ?> }
</div> $view .= ' </div>';
<?php if (!isset($_SESSION['account_loggedin'])): ?> if (!isset($_SESSION['account_loggedin'])){
<h2><?=$account_create_email?></h2> $view .= '
<h2>'.$account_create_email.'</h2>
<label for="email"></label> <label for="email"></label>
<input type="email" name="email" id="email" placeholder="<?=$account_create_email?>" class="form-field" required> <input type="email" name="email" id="email" placeholder="'.$account_create_email.'" class="form-field" required>
<h2><?=$account_create?><?php if (!account_required): ?> <?=$account_create_optional?><?php endif; ?></h2> <h2>'.$account_create.((!account_required) ? $account_create_optional : '').'</h2>
<label for="password"><?=$account_create_password?></label> <label for="password">'.$account_create_password.'</label>
<input type="password" name="password" id="password" placeholder="<?=$account_create_password?>" class="form-field" autocomplete="new-password"> <input type="password" name="password" id="password" placeholder="'.$account_create_password.'" class="form-field" autocomplete="new-password">
<label for="cpassword"><?=$account_create_password_confirm?></label> <label for="cpassword">'.$account_create_password_confirm.'</label>
<input type="password" name="cpassword" id="cpassword" placeholder="<?=$account_create_password_confirm?>" class="form-field" autocomplete="new-password"> <input type="password" name="cpassword" id="cpassword" placeholder="'.$account_create_password_confirm.'" class="form-field" autocomplete="new-password">';
<?php endif; ?> }
$view .= '
<h2><?=$h2_Shipping_details?></h2> <h2>'.$h2_Shipping_details.'</h2>
<div class="row1"> <div class="row1">
<label for="first_name"><?=$shipping_first_name?></label> <label for="first_name">'.$shipping_first_name.'</label>
<input type="text" value="<?=htmlspecialchars($account['first_name'], ENT_QUOTES)?>" name="first_name" id="first_name" placeholder="<?=$shipping_first_name?>" class="form-field" required> <input type="text" value="'.htmlspecialchars($account['first_name'], ENT_QUOTES).'" name="first_name" id="first_name" placeholder="'.$shipping_first_name.'" class="form-field" required>
</div> </div>
<div class="row2"> <div class="row2">
<label for="last_name"><?=$shipping_last_name?></label> <label for="last_name">'.$shipping_last_name.'</label>
<input type="text" value="<?=htmlspecialchars($account['last_name'], ENT_QUOTES)?>" name="last_name" id="last_name" placeholder="<?=$shipping_last_name?>" class="form-field" required> <input type="text" value="'.htmlspecialchars($account['last_name'], ENT_QUOTES).'" name="last_name" id="last_name" placeholder="'.$shipping_last_name.'" class="form-field" required>
</div> </div>
<label for="address_street"><?=$shipping_address?></label> <label for="address_street">'.$shipping_address.'</label>
<input type="text" value="<?=htmlspecialchars($account['address_street'], ENT_QUOTES)?>" name="address_street" id="address_street" placeholder="<?=$shipping_address?>" class="form-field" required> <input type="text" value="'.htmlspecialchars($account['address_street'], ENT_QUOTES).'" name="address_street" id="address_street" placeholder="'.$shipping_address.'" class="form-field" required>
<label for="address_city"><?=$shipping_city?></label> <label for="address_city">'.$shipping_city.'</label>
<input type="text" value="<?=htmlspecialchars($account['address_city'], ENT_QUOTES)?>" name="address_city" id="address_city" placeholder="<?=$shipping_city?>" class="form-field" required> <input type="text" value="'.htmlspecialchars($account['address_city'], ENT_QUOTES).'" name="address_city" id="address_city" placeholder="'.$shipping_city.'" class="form-field" required>
<div class="row1"> <div class="row1">
<label for="address_state"><?=$shipping_state?></label> <label for="address_state">'.$shipping_state.'</label>
<input type="text" value="<?=htmlspecialchars($account['address_state'], ENT_QUOTES)?>" name="address_state" id="address_state" placeholder="<?=$shipping_state?>" class="form-field"> <input type="text" value="'.htmlspecialchars($account['address_state'], ENT_QUOTES).'" name="address_state" id="address_state" placeholder="'.$shipping_state.'" class="form-field">
</div> </div>
<div class="row2"> <div class="row2">
<label for="address_zip"><?=$shipping_zip?></label> <label for="address_zip">'.$shipping_zip.'</label>
<input type="text" value="<?=htmlspecialchars($account['address_zip'], ENT_QUOTES)?>" name="address_zip" id="address_zip" placeholder="<?=$shipping_zip?>" class="form-field" required> <input type="text" value="'.htmlspecialchars($account['address_zip'], ENT_QUOTES).'" name="address_zip" id="address_zip" placeholder="'.$shipping_zip.'" class="form-field" required>
</div> </div>
<label for="address_phone"><?=$shipping_phone?></label> <label for="address_phone">'.$shipping_phone.'</label>
<input type="text" value="<?=htmlspecialchars($account['address_phone'], ENT_QUOTES)?>" name="address_phone" id="address_phone" placeholder="<?=$shipping_phone?>" class="form-field" required> <input type="text" value="'.htmlspecialchars($account['address_phone'], ENT_QUOTES).'" name="address_phone" id="address_phone" placeholder="'.$shipping_phone.'" class="form-field" required>
<label for="address_country"><?=$shipping_country?></label> <label for="address_country">'.$shipping_country.'</label>
<select name="address_country" class="ajax-update form-field" required> <select name="address_country" class="ajax-update form-field" required>';
<?php foreach(get_countries() as $country): ?> foreach(get_countries() as $country){
<option value="<?=$country?>"<?=$country==$account['address_country']?' selected':''?>><?=$country?></option> $view .= ' <option value="'.$country.'" '.($country==$account['address_country'] ? ' selected' : '').'>'.$country.'</option>';
<?php endforeach; ?> }
</select> $view .= ' </select>
</div> </div>
<div class="cart-details"> <div class="cart-details">
<h2><?=$h2_shoppingcart?></h2> <h2>'.$h2_shoppingcart.'</h2>
<table> <table>';
<?php foreach($products_in_cart as $product): ?> foreach($products_in_cart['cart_details']['products'] as $product){
<tr>
<td><img src="<?=$product['meta']['img']?>" width="35" height="35" alt="<?=$product['meta']['name']?>"></td> $view .= ' <tr>
<td><?=$product['quantity']?> x <?=$product['meta']['name']?></td> <td><img src="'.$img_url.$product['meta']['img'].'" width="35" height="35" alt="'.$product['meta']['name'].'"></td>
<td class="price"><?=currency_code?><?=number_format($product['options_price'] * $product['quantity'],2)?></td> <td>'.$product['quantity'].' x '.$product['meta']['name'].'</td>
</tr> <td class="price">'.currency_code.''.number_format($product['options_price'] * $product['quantity'],2).'</td>
<?php endforeach; ?> </tr>';
</table> }
$view .= ' </table>
<div class="discount-code"> <div class="discount-code">
<input type="text" class="ajax-update form-field" name="discount_code" placeholder="<?=$discount_label?>" value="<?=isset($_SESSION['discount']) ? $_SESSION['discount'] : ''?>"> <input type="text" class="ajax-update form-field" name="discount_code" placeholder="'.$discount_label.'" value="'.(isset($_SESSION['discount']) ? $_SESSION['discount'] : '').'">
<span class="result"> <span class="result">';
<?php if (isset($_SESSION['discount'], $discount) && !$discount): ?> if (isset($_SESSION['discount'], $products_in_cart['totals']['discounttotal'])){
<?=$discount_error_1?> $view .= $products_in_cart['totals']['discount_message'];
<?php elseif (isset($_SESSION['discount'], $discount) && $current_date < strtotime($discount['start_date'])): ?> }
<?=$discount_error_1?> $view .= ' </span>
<?php elseif (isset($_SESSION['discount'], $discount) && $current_date > strtotime($discount['end_date'])): ?>
<?=$discount_error_2?>
<?php elseif (isset($_SESSION['discount'], $discount)): ?>
<?=$discount_message?>
<?php endif; ?>
</span>
</div> </div>
<div class="shipping-methods-container">';
if ($shipping_methods_available){
$view .= ' <div class="shipping-methods">
<h3>'.$h3_shipping_method.'</h3>';
<div class="shipping-methods-container"> foreach($shipping_methods as $k => $method){
<?php if ($shipping_methods_available): ?>
<div class="shipping-methods"> if (!in_array($method['id'], $shipping_methods_available)){
<h3><?=$h3_shipping_method?></h3> $view .= ' <div class="shipping-method">
<?php foreach($shipping_methods as $k => $method): ?> <input type="radio" class="ajax-update" id="sm'.$k.'" name="shipping_method" value="'.$method['id'].'" required'.($selected_shipping_method==$method['id'] ? ' checked':'').'>
<?php if (!in_array($method['id'], $shipping_methods_available)) continue; ?> <label for="sm'.$k.'">'.$method['name'].' ('.currency_code.''.number_format($method['price'], 2).''.$method['type']=='Single Product'?' per item':''.')</label>
<div class="shipping-method"> </div>';
<input type="radio" class="ajax-update" id="sm<?=$k?>" name="shipping_method" value="<?=$method['id']?>" required<?=$selected_shipping_method==$method['id']?' checked':''?>> }
<label for="sm<?=$k?>"><?=$method['name']?> (<?=currency_code?><?=number_format($method['price'], 2)?><?=$method['type']=='Single Product'?' per item':''?>)</label> $view .= '</div>';
</div> }
<?php endforeach; ?> }
</div> $view .= ' </div>
<?php endif; ?>
</div>
<div class="summary"> <div class="summary">
<div class="subtotal"> <div class="subtotal">
<span><?=$total_subtotal?></span> <span>'.$total_subtotal.'</span>
<span><?=currency_code?><?=number_format($subtotal,2)?></span> <span>'.currency_code.''.number_format($subtotal,2).'</span>
</div> </div>
<div class="shipping"> <div class="shipping">
<span><?=$total_shipping?></span> <span>'.$total_shipping.'</span>
<span><?=currency_code?><?=number_format($shippingtotal,2)?></span> <span>'.currency_code.''.number_format($shippingtotal,2).'</span>
</div> </div>';
<?php if ($discounttotal > 0): ?> if ($discounttotal > 0){
<div class="discount"> $view .= '<div class="discount">
<span><?=$total_discount?></span> <span>'.$total_discount.'</span>
<span>-<?=currency_code?><?=number_format(round($discounttotal, 1),2)?></span> <span>-'.currency_code.''.number_format(round($discounttotal, 1),2).'</span>
</div> </div>';
<?php endif; ?> }
<?php if ($tax): ?> if ($taxtotal > 0){
<div class="vat"> $view .= '<div class="vat">
<span>VAT <span class="alt">(<?=$tax['rate']?>%)</span></span> <span>VAT <span class="alt">('.$tax_rate.')</span></span>
<span><?=currency_code?><?=number_format($taxtotal,2)?></span> <span>'.currency_code.''.number_format($taxtotal,2).'</span>
</div> </div>';
<?php endif; ?> }
</div> $view .= ' </div>
<div class="total"> <div class="total">
<span><?=$total_total?> <span class="alt"><?=$total_total_note?></span></span><span><?=currency_code?><?=number_format(($subtotal)-round($discounttotal,1)+$shippingtotal,2)?></span> <span>'.$total_total.' <span class="alt">'.$total_total_note.'</span></span><span>'.currency_code.''.number_format($total,2).'</span>
</div> </div>
<div class="summary"> <div class="summary">
<div class="subtotal"> <div class="subtotal">
<span> <span>
<input type="checkbox" id="consent" name="consent_comms" value="1"><?=$order_consent_1?></a> <input type="checkbox" id="consent" name="consent_comms" value="1">'.$order_consent_1.'</a>
</span> </span>
</div> </div>
<div class="subtotal"> <div class="subtotal">
<span> <span>
<input type="checkbox" id="consent" name="consent" value="1" required><?=$order_consent_2?> <a href="<?=$terms_link?>" target="_blank"><?=$order_consent_3?></a> <input type="checkbox" id="consent" name="consent" value="1" required>'.$order_consent_2.' <a href="'.$terms_link.'" target="_blank">'.$order_consent_3.'</a>
</span> </span>
</div> </div>
</div> </div>
<div class="buttons"> <div class="buttons">
<button type="submit" name="checkout" class="btn"><?=$btn_place_order?></button> <button type="submit" name="checkout" class="btn">'.$btn_place_order.'</button>
</div> </div>
</div> </div>
@@ -769,6 +647,11 @@ $terms_link = url('index.php?page=termsandconditions');
</form> </form>
</div> </div>';
<?=template_footer()?> //OUTPUT
echo $view;
template_footer();
?>

View File

@@ -38,13 +38,13 @@
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<?php foreach($products as $product): ?> <?php foreach($products_in_cart['cart_details']['products'] as $product): ?>
<tr> <tr>
<td><?=$product['meta']['name']?></td> <td><?=$product['meta']['name']?></td>
<td><?=$product['options']?></td> <td><?=$product['options']?></td>
<td><?=$product['quantity']?></td> <td><?=$product['quantity']?></td>
<td><?=currency_code?><?=number_format($product['final_price'],2)?></td> <td><?=currency_code?><?=number_format($product['option_price'],2)?></td>
<td style="text-align:right;"><?=number_format($product['final_price'] * $product['quantity'],2)?></td> <td style="text-align:right;"><?=number_format($product['option_price'] * $product['quantity'],2)?></td>
</tr> </tr>
<?php endforeach; ?> <?php endforeach; ?>
<tr> <tr>

View File

@@ -39,13 +39,13 @@
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<?php foreach($products as $product): ?> <?php foreach($products_in_cart['cart_details']['products'] as $product): ?>
<tr> <tr>
<td><?=$product['meta']['name']?></td> <td><?=$product['meta']['name']?></td>
<td><?=$product['options']?></td> <td><?=$product['options']?></td>
<td><?=$product['quantity']?></td> <td><?=$product['quantity']?></td>
<td><?=currency_code?><?=number_format($product['final_price'],2)?></td> <td><?=currency_code?><?=number_format($product['option_price'],2)?></td>
<td style="text-align:right;"><?=number_format($product['final_price'] * $product['quantity'],2)?></td> <td style="text-align:right;"><?=number_format($product['option_price'] * $product['quantity'],2)?></td>
</tr> </tr>
<?php endforeach; ?> <?php endforeach; ?>
<tr> <tr>

View File

@@ -142,7 +142,7 @@ function send_order_details_email($email, $products, $first_name, $last_name, $a
$subject = $subject_order_notification; $subject = $subject_order_notification;
$headers = 'From: ' . mail_from . "\r\n" . 'Reply-To: ' . $email . "\r\n" . 'Return-Path: ' . mail_from . "\r\n" . 'X-Mailer: PHP/' . phpversion() . "\r\n" . 'MIME-Version: 1.0' . "\r\n" . 'Content-Type: text/html; charset=UTF-8' . "\r\n"; $headers = 'From: ' . mail_from . "\r\n" . 'Reply-To: ' . $email . "\r\n" . 'Return-Path: ' . mail_from . "\r\n" . 'X-Mailer: PHP/' . phpversion() . "\r\n" . 'MIME-Version: 1.0' . "\r\n" . 'Content-Type: text/html; charset=UTF-8' . "\r\n";
ob_start(); ob_start();
include './custom/order-notification-template.php'; include './custom/email/order-notification-template.php';
$order_notification_template = ob_get_clean(); $order_notification_template = ob_get_clean();
send_mail_by_PHPMailer(email, $subject, $order_notification_template, '', ''); send_mail_by_PHPMailer(email, $subject, $order_notification_template, '', '');
} }
@@ -152,7 +152,7 @@ function send_order_details_email($email, $products, $first_name, $last_name, $a
$subject = $subject_new_order; $subject = $subject_new_order;
$headers = 'From: ' . mail_from . "\r\n" . 'Reply-To: ' . mail_from . "\r\n" . 'Return-Path: ' . mail_from . "\r\n" . 'X-Mailer: PHP/' . phpversion() . "\r\n" . 'MIME-Version: 1.0' . "\r\n" . 'Content-Type: text/html; charset=UTF-8' . "\r\n"; $headers = 'From: ' . mail_from . "\r\n" . 'Reply-To: ' . mail_from . "\r\n" . 'Return-Path: ' . mail_from . "\r\n" . 'X-Mailer: PHP/' . phpversion() . "\r\n" . 'MIME-Version: 1.0' . "\r\n" . 'Content-Type: text/html; charset=UTF-8' . "\r\n";
ob_start(); ob_start();
include './custom/order-details-template.php'; include './custom/email/order-details-template.php';
$order_details_template = ob_get_clean(); $order_details_template = ob_get_clean();
send_mail_by_PHPMailer($email, $subject, $order_details_template, '', ''); send_mail_by_PHPMailer($email, $subject, $order_details_template, '', '');
} }
@@ -322,7 +322,7 @@ function getAccessoiries($pdo, $categoryID){
$stmt->execute(); $stmt->execute();
$additional_products = $stmt->fetchAll(PDO::FETCH_ASSOC); $additional_products = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<div class="content-wrapper"> $output ='<div class="content-wrapper">
<div class="add_products"> <div class="add_products">
<h2>'.$h2_cart_suggestions.'</h2> <h2>'.$h2_cart_suggestions.'</h2>
'; ';
@@ -333,7 +333,7 @@ function getAccessoiries($pdo, $categoryID){
$url_contents = 'index.php?page=product&id='; $url_contents = 'index.php?page=product&id=';
$url_contents .= $additional_product['url_slug'] ? $additional_product['url_slug'] : $additional_product['id']; $url_contents .= $additional_product['url_slug'] ? $additional_product['url_slug'] : $additional_product['id'];
$additional_product_url = url($url_contents); $additional_product_url = url($url_contents);
echo' $output .='
<div class="add_product"> <div class="add_product">
<a href="'.$additional_product_url.'" id="'.$additional_product['id'].'A" class="product"> <a href="'.$additional_product_url.'" id="'.$additional_product['id'].'A" class="product">
<img src="'.base_url.$additional_product['img'].'" id="'.$additional_product['id'].'" width="15%" height="" alt="'.$additional_product['name'].'"> <img src="'.base_url.$additional_product['img'].'" id="'.$additional_product['id'].'" width="15%" height="" alt="'.$additional_product['name'].'">
@@ -349,17 +349,19 @@ function getAccessoiries($pdo, $categoryID){
<span class="add_price"> '.currency_code.'.'.number_format($additional_product['price'],2).' <span class="add_price"> '.currency_code.'.'.number_format($additional_product['price'],2).'
'; ';
if ($additional_product['rrp'] > 0){ if ($additional_product['rrp'] > 0){
echo ' $output .='
<span class="add_rrp">'.currency_code.''.number_format($additional_product['rrp'],2).'</span> <span class="add_rrp">'.currency_code.''.number_format($additional_product['rrp'],2).'</span>
'; ';
} }
echo' $output .='
</a> </a>
</div> </div>
'; ';
} }
} }
echo '</div></div>'; $output .='</div></div>';
return $output;
} }
function getSamples($pdo, $categoryID){ function getSamples($pdo, $categoryID){
@@ -371,7 +373,7 @@ function getSamples($pdo, $categoryID){
$stmt->execute(); $stmt->execute();
$additional_products = $stmt->fetchAll(PDO::FETCH_ASSOC); $additional_products = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<div class="content-wrapper"> $output ='<div class="content-wrapper">
<h2 style="font-weight:normal;">'.$h2_cart_samples.'</h2> <h2 style="font-weight:normal;">'.$h2_cart_samples.'</h2>
<div class="add_sample_button"><button id="slideLeft" class="scrollButton" type="button"><</button></div> <div class="add_sample_button"><button id="slideLeft" class="scrollButton" type="button"><</button></div>
<div id="add_samples_container" class="add_samples"> <div id="add_samples_container" class="add_samples">
@@ -389,7 +391,7 @@ function getSamples($pdo, $categoryID){
$url_contents = 'index.php?page=product&id='; $url_contents = 'index.php?page=product&id=';
$url_contents .= $additional_product['url_slug'] ? $additional_product['url_slug'] : $additional_product['id']; $url_contents .= $additional_product['url_slug'] ? $additional_product['url_slug'] : $additional_product['id'];
$additional_product_url = url($url_contents); $additional_product_url = url($url_contents);
echo' $output .='
<div class="add_sample"> <div class="add_sample">
<img src="'.base_url.$additional_product['img'].'" id="'.$additional_product['id'].'" width="50" height="50" alt="'.$additional_product['name'].'"> <img src="'.base_url.$additional_product['img'].'" id="'.$additional_product['id'].'" width="50" height="50" alt="'.$additional_product['name'].'">
<form id="product-form" action="" method="post"> <form id="product-form" action="" method="post">
@@ -401,27 +403,28 @@ function getSamples($pdo, $categoryID){
<a href="'.$additional_product_url.'" id="'.$additional_product['id'].'A" class="product"> <a href="'.$additional_product_url.'" id="'.$additional_product['id'].'A" class="product">
<span class="add_name">'.$additional_product['name'].'</span>'; <span class="add_name">'.$additional_product['name'].'</span>';
if ($additional_product['price'] > 0){ if ($additional_product['price'] > 0){
echo ' $output .='
<span class="add_price"> '.currency_code.'.'.number_format($additional_product['price'],2).' <span class="add_price"> '.currency_code.'.'.number_format($additional_product['price'],2).'
'; ';
} }
if ($additional_product['rrp'] > 0){ if ($additional_product['rrp'] > 0){
echo ' $output .='
<span class="add_rrp">'.currency_code.''.number_format($additional_product['rrp'],2).'</span> <span class="add_rrp">'.currency_code.''.number_format($additional_product['rrp'],2).'</span>
'; ';
} }
echo' $output .='
</a> </a>
</div> </div>
'; ';
} }
} }
echo ' $output .='
</div> </div>
<div class="add_sample_button"><button id="slideRight" class="scrollButton" type="button">></button></div> <div class="add_sample_button"><button id="slideRight" class="scrollButton" type="button">></button></div>
</div>'; </div>';
return $output;
} }
function createGiftCart($pdo, $orderID){ function createGiftCart($pdo, $orderID){
@@ -542,7 +545,7 @@ function generateInvoice($pdo, $orderID){
//Generate invoice //Generate invoice
ob_start(); ob_start();
include dirname(__FILE__).'/custom/order-invoice-template.php'; include dirname(__FILE__).'/custom/email/order-invoice-template.php';
$order_invoice_template = ob_get_clean(); $order_invoice_template = ob_get_clean();
return array($order_invoice_template,$customer_email,$order_id); return array($order_invoice_template,$customer_email,$order_id);

View File

@@ -1,115 +1,75 @@
<?php <?php
// Prevent direct access to file // Prevent direct access to file
defined(security_key) or exit; defined(security_key) or exit;
//+++++++++++++++++++++++++++++++++++++++++++++
// TODO
//+++++++++++++++++++++++++++++++++++++++++++++
/*
3. product notifier when out of stock
*/
//+++++++++++++++++++++++++++++++++++++++++++++
// END TODO
//+++++++++++++++++++++++++++++++++++++++++++++
// Check to make sure the id parameter is specified in the URL // Check to make sure the id parameter is specified in the URL
if (isset($_GET['id'])) { if (isset($_GET['id'])) {
// Prepare statement and execute, prevents SQL injection
$stmt = $pdo->prepare('SELECT * FROM products WHERE status = 1 AND (id = ? OR url_slug = ?)'); //GET CATALOG DATA
$stmt->execute([ $_GET['id'], $_GET['id'] ]); $product = ioAPIv2('/v2/catalog/product_id='.$_GET['id'],'',$clientsecret);
// Fetch the product from the database and return the result as an Array $product = json_decode($product,true);
$product = $stmt->fetch(PDO::FETCH_ASSOC); $product = $product[0] ?? '';
// Check if the product exists (array is not empty) // Check if the product exists (array is not empty)
if (!$product) { if (!$product) {
// Output simple error if the id for the product doesn't exists (array is empty) // Output simple error if the id for the product doesn't exists (array is empty)
http_response_code(404); http_response_code(404);
exit('Product does not exist!'); exit('Product does not exist!');
} }
// Select the product images (if any) from the products_images table
$stmt = $pdo->prepare('SELECT m.*, pm.position FROM products_media pm JOIN media m ON m.id = pm.media_id WHERE pm.product_id = ? ORDER BY pm.position ASC');
$stmt->execute([ $product['id'] ]);
// Fetch the product images from the database and return the result as an Array
$product_media = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Select the product options (if any) from the products_options table
$stmt = $pdo->prepare('SELECT CONCAT(title, "::", type, "::", required) AS k, name, quantity, price, price_modifier, weight, weight_modifier, type, id, required FROM products_options WHERE product_id = ? ORDER BY position ASC');
$stmt->execute([ $product['id'] ]);
// Fetch the product options from the database and return the result as an Array
$product_options = $stmt->fetchAll(PDO::FETCH_GROUP);
// Add the HTML meta data (for SEO purposes) // Add the HTML meta data (for SEO purposes)
$meta = ' $meta = '
<meta property="og:url" content="' . url('index.php?page=product&id=' . ($product['url_slug'] ? $product['url_slug'] : $product['id'])) . '"> <meta property="og:url" content="' . url('index.php?page=product&id=' . ($product['url_slug'] ? $product['url_slug'] : $product['rowID'])) . '">
<meta property="og:title" content="' . $product['name'] . '"> <meta property="og:title" content="' . (${$product['productname']} ?? $product['productname']) . '">
'; ';
if (isset($product_media[0]) && file_exists($product_media[0]['full_path'])) { if (isset($product['full_path'])) {
$meta .= '<meta property="og:image" content="' . base_url . $product_media[0]['full_path'] . '">'; $meta .= '<meta property="og:image" content="'.$img_url.$product['full_path'].'">';
} }
//GET RELATED MEDIA
$product_media = ioAPIv2('/v2/products_media/product_id='.$product['rowID'],'',$clientsecret);
$product_media = json_decode($product_media,true);
// If the user clicked the add to cart button // If the user clicked the add to cart button
if (isset($_POST['quantity']) && is_numeric($_POST['quantity'])) { if (isset($_POST['product'])) {
// abs() function will prevent minus quantity and (int) will ensure the value is an integer (number)
$quantity = abs((int)$_POST['quantity']); //VALIDATE THE INPUT FOR THE SHOPPING CART
// Get product options $payload = json_encode($_POST['product'], JSON_UNESCAPED_UNICODE);
$options = ''; $product_to_cart = ioAPIv2('/v2/shopping_cart/',$payload,$clientsecret);
$options_price = (float)$product['price']; $product_to_cart = json_decode($product_to_cart,true);
$options_weight = (float)$product['weight'];
// Iterate post data
foreach ($_POST as $k => $v) {
if (strpos($k, 'option-') !== false) {
if (is_array($v)) {
// Option is checkbox or radio element
foreach ($v as $vv) {
if (empty($vv)) continue;
$options .= str_replace(['_', 'option-'], [' ', ''], $k) . '-' . $vv . ',';
$stmt = $pdo->prepare('SELECT * FROM products_options WHERE title = ? AND name = ? AND product_id = ?');
$stmt->execute([ str_replace(['_', 'option-'], [' ', ''], $k), $vv, $product['id'] ]);
$option = $stmt->fetch(PDO::FETCH_ASSOC);
$options_price = $option['price_modifier'] == 'add' ? $options_price + $option['price'] : $options_price - $option['price'];
$options_weight = $option['weight_modifier'] == 'add' ? $options_weight + $option['weight'] : $options_weight - $option['weight'];
}
} else {
if (empty($v)) continue;
$options .= str_replace(['_', 'option-'], [' ', ''], $k) . '-' . $v . ',';
//------------------
//Update name otherwise option is not found
//------------------
$name_update = '%|^|'.$v;
$stmt = $pdo->prepare('SELECT * FROM products_options WHERE title = ? AND name like ? AND product_id = ?');
$stmt->execute([ str_replace(['_', 'option-'], [' ', ''], $k), $name_update, $product['id'] ]);
//------------------
// OLD CODE
//------------------
//$stmt = $pdo->prepare('SELECT * FROM products_options WHERE title = ? AND name = ? AND product_id = ?');
//$stmt->execute([ str_replace(['_', 'option-'], [' ', ''], $k), $v, $product['id'] ]);
//------------------
$option = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$option) {
// Option is text or datetime element
$stmt = $pdo->prepare('SELECT * FROM products_options WHERE title = ? AND product_id = ?');
$stmt->execute([ str_replace(['_', 'option-'], [' ', ''], $k), $product['id'] ]);
$option = $stmt->fetch(PDO::FETCH_ASSOC);
}
$options_price = $option['price_modifier'] == 'add' ? $options_price + $option['price'] : $options_price - $option['price'];
$options_weight = $option['weight_modifier'] == 'add' ? $options_weight + $option['weight'] : $options_weight - $option['weight'];
}
}
}
$options_price = $options_price < 0 ? 0 : $options_price;
$options = rtrim($options, ',');
// Check if the product exists (array is not empty) // Check if the product exists (array is not empty)
if ($quantity > 0) { if ($product_to_cart['quantity'] > 0) {
// Product exists in database, now we can create/update the session variable for the cart // Product exists in database, now we can create/update the session variable for the cart
if (!isset($_SESSION['cart'])) { if (!isset($_SESSION['cart'])) {
// Shopping cart session variable doesnt exist, create it // Shopping cart session variable doesnt exist, create it
$_SESSION['cart'] = []; $_SESSION['cart'] = [];
} }
$cart_product = &get_cart_product($product['id'], $options); $cart_product = &get_cart_product($product_to_cart['id'], $product_to_cart['options']);
if ($cart_product) { if ($cart_product) {
// Product exists in cart, update the quanity // Product exists in cart, update the quanity
$cart_product['quantity'] += $quantity; $cart_product['quantity'] += $quantity;
} else { } else {
// Product is not in cart, add it // Product is not in cart, add it
$_SESSION['cart'][] = [ $_SESSION['cart'][] = $product_to_cart;
'id' => $product['id'],
'quantity' => $quantity,
'options' => $options,
'options_price' => $options_price,
'options_weight' => $options_weight,
'shipping_price' => 0.00
];
} }
} }
// Prevent form resubmission... // Prevent form resubmission...
header('Location: ' . url('index.php?page=cart')); header('Location: ' . url('index.php?page=cart'));
exit;
exit;
} }
@@ -120,16 +80,11 @@ if (isset($_GET['id'])) {
exit('Product does not exist!'); exit('Product does not exist!');
} }
//get all media
$stmt = $pdo->query('SELECT id, full_path, caption FROM media');
$stmt->execute();
$media2 = $stmt->fetchAll(PDO::FETCH_ASSOC);
//LINK to products page: //LINK to products page:
$products_link = url(link_to_collection); $products_link = url(link_to_collection);
$product_link = url('index.php?page=product&id='.($product['url_slug'] ? $product['url_slug'] : $product['id'])); $product_link = url('index.php?page=product&id='.($product['url_slug'] ? $product['url_slug'] : $product['rowID']));
//Notifier - when 1 user ask for product notification /*Notifier - when 1 user ask for product notification
$notifier = 0; $notifier = 0;
if (isset($_POST["notifier"])){ if (isset($_POST["notifier"])){
@@ -140,226 +95,242 @@ if (isset($_POST["notifier"])){
send_product_notification_email($email, $_POST["product_details"]); send_product_notification_email($email, $_POST["product_details"]);
$notifier = 1; $notifier = 1;
} }
//CREATE OPTION_PICTURE ARRAY FOR USE IN OPTION OVERVIEW */
$option_profile = json_decode($product['product_config']) ?? ''; $view = '';
if (!empty($option_profile) && $option_profile !=''){ template_header((${$product['productname']} ?? $product['productname']), $meta);
//CREATE OPTION PICTURE ARRAY
$option_picture[] = ''; if ($error){
foreach ($option_profile as $option){
//CHECK FOR RELATED MEDIA $view .='<p class="content-wrapper error">'.$error.'</p>';
foreach ($media2 as $media_item2){
if ($media_item2['id'] == $option->IMG_large_id){
$option_picture[$option->option_id] = $media_item2['full_path'];
}
}
}
} }
?> else {
<?=template_header($product['name'], $meta)?> $view .='
<?php if ($error): ?>
<p class="content-wrapper error"><?=$error?></p>
<?php else: ?>
<div class="product content-wrapper"> <div class="product content-wrapper">
<div class="product-imgs"> <div class="product-imgs">';
<?php if (isset($_GET['option_id']) && !empty($_GET['option_id']) && $_GET['option_id'] !='') : ?> if (isset($_GET['option_id']) && !empty($_GET['option_id']) && $_GET['option_id'] !=''){
<?php
$option_profile = json_decode($product['product_config']); $fullPath = null;
foreach ($option_profile as $option){ foreach ($product['configurations'] as $configuration) {
//GET RIGHT PICTURE BASED ON SELECTED OPTION IN OVERVIEW PAGE if (isset($configuration['attributes'])) {
if ($option->option_id == $_GET['option_id']){ foreach ($configuration['attributes'] as $attribute) {
$IMG_large_id = $option->IMG_large_id; if ($attribute['attribute_id'] == $_GET['option_id']) {
foreach ($media2 as $media_item2){ $fullPath = $attribute['alternative_media_full_path'] ?? $attribute['full_path'];
if ($media_item2['id'] == $IMG_large_id){ $altTitle = $attribute['alternative_media_title'] ?? $attribute['title'];
$view .='
$IMG_large_path = $media_item2['full_path']; <div class="product-img-large">
echo ' <img src="'.$img_url.$fullPath.'" id="'.$product['rowID'].'" alt="'.$altTitle.'">
<div class="product-img-large"> </div>';
<img src="'.$base_url.$media_item2['full_path'].'" id="'.$product['id'].'" alt="'.$media_item2['caption'].'"> break 2; // Exit all loops once found
</div>';
} }
} }
} }
} }
?>
<?php elseif (isset($product_media[0]) && file_exists($product_media[0]['full_path'])): ?> } elseif (isset($product['full_path']) && $product['full_path'] != ''){
<div class="product-img-large"> $view .='
<img src="<?=base_url . $product_media[0]['full_path']?>" alt="<?=$product_media[0]['caption']?>"> <div class="product-img-large">
</div> <img src="'.$img_url.$product['full_path'].'" id="'.$product['rowID'].'" alt="'.(${$product['productname']} ?? $product['productname']).'">
<?php endif; ?> </div>';
}
<div class="product-small-imgs"> $view .='
<?php <div class="product-small-imgs">';
//Show small images //Show small images
foreach ($product_media as $media){ foreach ($product_media as $media){
if (isset($_GET['option_id']) && !empty($_GET['option_id']) && $_GET['option_id'] !='' && show_option_images != true){
$option_profile = json_decode($product['product_config']); $view .=' <div class="product-img-small '.($media['position']==1?' selected':'').'">
//create array with all option imagesIDs <img src="'.$img_url.$media['full_path'].'" width="150" height="150" alt="">
$option_images = []; </div>';
foreach($option_profile as $option){
$option_images[] = $option->IMG_large_id;
}
if (in_array($media['id'], $option_images)){
//Do nothing
} else {
echo ' <div class="product-img-small '.($media['position']==1?' selected':'').'">
<img src="'.base_url.$media['full_path'].'" width="150" height="150" alt="'.$media['caption'].'">
</div>';
}
} }
else { $view .='
//No Option profile - show all images
echo ' <div class="product-img-small '.($media['position']==1?' selected':'').'">
<img src="'.base_url.$media['full_path'].'" width="150" height="150" alt="'.$media['caption'].'">
</div>';
}
}
?>
</div> </div>
</div> </div>
<div class="product-wrapper"> <div class="product-wrapper">
<div class="breadcrum"> <div class="breadcrum">
<a href="<?=$products_link?>"><?=$breadcrum_products?></a> <p>/ <?=$product['name']?></p> <a href="'.$products_link.'">'.$breadcrum_products.'</a> <p>/ '.(${$product['productname']} ?? $product['productname']).'</p>
</div> </div>
<h1 class="name"><?=$product['name']?></h1>
<h1 class="name">'.(${$product['productname']} ?? $product['productname']).'</h1>
<div class="prices"> <div class="prices">
<span class="price" data-price="<?=$product['price']?>"><?=currency_code?><?=number_format($product['price'],2)?></span> <span class="price" data-price="'.$product['price'].'">'.currency_code.''.number_format($product['price'],2).'</span>';
<?php if ($product['rrp'] > 0): ?> if ($product['rrp'] > 0){
<span class="rrp"><?=currency_code?><?=number_format($product['rrp'],2)?></span> $view .= '<span class="rrp" data-rrp="'.$product['rrp'].'">'.currency_code.''.number_format($product['rrp'],2).'</span>';
<?php endif; ?> }
</div> $view .='</div>
<!-- On Stock indicator --> <div class="stock">';
<div class="stock"> //Stock status
<?php //Stock status $stock_status = ($product['quantity'] != 0) ? $product_on_stock : $out_of_stock;
$stock_status = ($product['quantity'] != 0) ? $product_on_stock : $out_of_stock; $style = ($stock_status == $product_on_stock) ? 'style="color:green;font-weight: bold;"' : 'style="color:gray;font-weight: lighter;"';
$style = ($stock_status == $product_on_stock) ? 'style="color:green;font-weight: bold;"' : 'style="color:gray;font-weight: lighter;"'; $view .= '<span class="stock_product">
echo ' <span class="stock_product"> <p '.$style.'> '.$stock_status.' </p>
<p '.$style.'> '.$stock_status.' </p> </span>';
</span>'; $view .='</div>';
?> //FREE SHIPMENT INDICATOR
</div>
<!-- Free shipment indicator -->
<?php
if (free_shipment_indicator){ if (free_shipment_indicator){
freeShipment($product['price'],'div'); freeShipment($product['price'],'div');
}
$view .='<form id="product-form" action="" method="post">';
//CHECK FOR OPTIONS ASSIGNED
if(isset($product['configurations'])){
foreach ($product['configurations'] as $configuration) {
//CHECK FOR GROUPS
if (isset($configuration['type']) && $configuration['type'] == 'product'){
$view .= '<input id="product" type="hidden" name="product[option][products][]" value="'.$configuration['assignment'].'">';
}
//CHECK FOR GROUPS
if (isset($configuration['type']) && $configuration['type'] == 'group'){
$view .= '<label for="">'.(${$configuration['assignment_name']} ?? $configuration['assignment_name']).'</label>';
//BASED ON GROUP TYPE CREATE INPUT FORM
switch($configuration['group_type']) {
case 0: //Radiobutton
$output ='';
foreach ($configuration['attributes'] as $attribute){
if(isset($attribute['full_path']) && $attribute['full_path'] !=''){
$onclick ='';
//ADD updateOption to change pictures when GROUP is IN configuration
if(isset($product['config_setting']) && $product['config_setting'] == $configuration['assignment']){
$IMG_large_id = $img_url.$attribute['alternative_media_full_path']; //URL TO LARGE IMAGE
$onclick = 'onclick="updateOption(\''.$product['rowID'].'\',\''.$IMG_large_id.'\')"';
}
$IMG_small_id = $img_url.$attribute['full_path']; //URL TO SMALL IMAGE
$output .= '
<label class="picture_select_label">
<input id="'.$attribute['attribute_id'].'" class="option radio" value="'.$attribute['attribute_id'].'" name="product[option]['.$configuration['assignment'].'][]" type="radio" data-price="'.($attribute['price'] ?? 0).'" data-rrp="'.($attribute['rrp'] ?? 0).'" data-modifier="'.($attribute['price_modifier'] ?? '').'" '.(($configuration['group_mandatory'] == 1 ) ? ' required' : '').'>
<span class="picture_select"><img '.$onclick.' src="'.$IMG_small_id.'"></span>
</label>';
} else {
$output .= '
<label>
<input id="'.$attribute['attribute_id'].'>" class="option radio" value="'.$attribute['attribute_id'].'" name="product[option]['.$configuration['assignment'].'][]" type="radio" data-price="'.($attribute['price'] ?? 0).'" data-rrp="'.($attribute['rrp'] ?? 0).'" data-modifier="'.($attribute['price_modifier'] ?? '').'" '.(($configuration['group_mandatory'] == 1 ) ? ' required' : '').'>'.(${$attribute['item_name']} ?? $attribute['item_name']).'
</label>';
}
}
$view .= '<div class="radio-checkbox">'.$output.'</div>';
break;
case 1: //Checkbox
$output ='';
foreach ($configuration['attributes'] as $attribute){
if(isset($attribute['full_path']) && $attribute['full_path'] !=''){
$onclick ='';
//ADD updateOption to change pictures when GROUP is IN configuration
if(isset($product['config_setting']) && $product['config_setting'] == $configuration['assignment']){
$IMG_large_id = $img_url.$attribute['alternative_media_full_path']; //URL TO LARGE IMAGE
$onclick = 'onclick="updateOption(\''.$product['rowID'].'\',\''.$IMG_large_id.'\')"';
}
$IMG_small_id = $img_url.$attribute['full_path']; //URL TO SMALL IMAGE
$output .= '
<label class="picture_select_label">
<input id="'.$attribute['attribute_id'].'>" class="option checkbox" value="'.$attribute['attribute_id'].'" name="product[option]['.$configuration['assignment'].'][]" type="checkbox" data-price="'.($attribute['price'] ?? 0).'" data-rrp="'.($attribute['rrp'] ?? 0).'" data-modifier="'.($attribute['price_modifier'] ?? '').'" '.(($configuration['group_mandatory'] == 1 ) ? ' required' : '').'>
<span class="picture_select"><img '.$onclick.' src="'.$IMG_small_id.'"></span>
</label>';
} else {
$output .= '
<label>
<input id="'.$attribute['attribute_id'].'>" class="option checkbox" value="'.$attribute['attribute_id'].'" name="product[option]['.$configuration['assignment'].'][]" type="checkbox" data-price="'.($attribute['price'] ?? 0).'" data-rrp="'.($attribute['rrp'] ?? 0).'" data-modifier="'.($attribute['price_modifier'] ?? '').'" '.(($configuration['group_mandatory'] == 1 ) ? ' required' : '').'>'.(${$attribute['item_name']} ?? $attribute['item_name']).'
</label>';
}
}
$view .= '<div class="radio-checkbox">'.$output.'</div>';
break;
case 2: //Dropdown
$output ='
<select id="'.$configuration['assignment'].'" class="option select" name="product[option]['.$configuration['assignment'].']" '.(($configuration['group_mandatory'] == 1 ) ? ' required' : '').'>
<option value="" selected disabled style="display:none">'.$configuration['assignment_name'].'</option>
';
foreach ($configuration['attributes'] as $attribute){
if(isset($attribute['full_path']) && $attribute['full_path'] !=''){
$onclick ='';
//ADD updateOption to change pictures when GROUP is IN configuration
if(isset($product['config_setting']) && $product['config_setting'] == $configuration['assignment']){
$IMG_large_id = $img_url.$attribute['alternative_media_full_path']; //URL TO LARGE IMAGE
$onclick = 'onclick="updateOption(\''.$product['rowID'].'\',\''.$IMG_large_id.'\')"';
}
$IMG_small_id = $img_url.$attribute['full_path']; //URL TO SMALL IMAGE
$output .= '
<option id="'.$attribute['attribute_id'].'" value="'.$attribute['attribute_id'].'" data-price="'.($attribute['price'] ?? 0).'" data-rrp="'.($attribute['rrp'] ?? 0).'" data-modifier="'.($attribute['price_modifier'] ?? '').'">'.(${$attribute['item_name']} ?? $attribute['item_name']).'</option>';
} else {
$output .= '
<option id="'.$attribute['attribute_id'].'" value="'.$attribute['attribute_id'].'" data-price="'.($attribute['price'] ?? 0).'" data-rrp="'.($attribute['rrp'] ?? 0).'" data-modifier="'.($attribute['price_modifier'] ?? '').'">'.(${$attribute['item_name']} ?? $attribute['item_name']).'</option>';
}
}
$view .= $output.'</select></div>';
break;
}
}
} }
?> }
<form id="product-form" action="" method="post">
<?php foreach ($product_options as $id => $option): ?> $view .='
<?php $id = explode('::', $id); ?> <label for="quantity">'.$product_quantity.'</label>
<?php if ($id[1] == 'select'): ?> <input id="quantity" type="number" name="product[quantity]" value="1" min="1" placeholder="Quantity" required>
<label for="<?=$id[0]?>"><?=$id[0]?></label> <input id="product" type="hidden" name="product[product]" value="'.$product['rowID'].'">
<select id="<?=$id[0]?>" class="option select" name="option-<?=$id[0]?>"<?=$id[2] ? ' required' : ''?>> <input id="product" type="hidden" name="product[version]" value="'.($product['version_id'] ?? '').'">
<option value="" selected disabled style="display:none"><?=$id[0]?></option>
<?php foreach ($option as $option_value): ?> <input type="submit" value="'.$add_to_basket.'" class="btn">
<option id="<?=$option_value['id']?>" value="<?=$option_value['name']?>" data-price="<?=$option_value['price']?>" data-modifier="<?=$option_value['price_modifier']?>"<?=$option_value['quantity']==0?' disabled':''?>><?=$option_value['name']?></option>
<?php endforeach; ?>
</select>
<?php elseif ($id[1] == 'radio'): ?>
<label for="<?=$id[0]?>"><?=$id[0]?></label>
<div class="radio-checkbox">
<?php foreach ($option as $n => $option_value): ?>
<?php //check if option has picture ID
if (str_contains($option_value['name'], '|^|')): ?>
<?php $check=explode('|^|', $option_value['name']);?>
<?php foreach ($media2 as $media_item):?>
<?php if ($media_item['id'] == $check[0]):?>
<label class="picture_select_label">
<input id="<?=$option_value['id']?>" class="option radio" value="<?=$check[1]?>" name="option-<?=$id[0]?>" type="radio" data-price="<?=$option_value['price']?>" data-modifier="<?=$option_value['price_modifier']?>">
<span class="picture_select"><img onclick="updateOption('<?=$product['id']?>','<?=url($option_picture[$option_value['id']])?>')" src="<?=url($media_item['full_path'])?>"></span>
</label>
<?php endif; ?>
<?php endforeach; ?>
<?php else: ?>
<label>
<input id="<?=$option_value['id']?>" class="option radio" value="<?=$option_value['name']?>" name="option-<?=$id[0]?>" type="radio" data-price="<?=$option_value['price']?>" data-modifier="<?=$option_value['price_modifier']?>"<?=$id[2] && $n == 0 ? ' required' : ''?><?=$option_value['quantity']==0?' disabled':''?>><?=$option_value['name']?>
</label>
<?php endif; ?>
<?php endforeach; ?>
</div>
<?php elseif ($id[1] == 'checkbox'): ?>
<label for="<?=$id[0]?>"><?=$id[0]?></label>
<div class="radio-checkbox">
<?php foreach ($option as $n => $option_value): ?>
<?php //check if option has picture ID
if (str_contains($option_value['name'], '|^|')): ?>
<?php $check=explode('|^|', $option_value['name']);?>
<?php foreach ($media2 as $media_item):?>
<?php if ($media_item['id'] == $check[0]):?>
<label class="picture_select_label">
<input id="<?=$option_value['id']?>" class="option checkbox" id="<?=$option_value['id']?>" value="<?=$check[1]?>" name="option-<?=$id[0]?>[]" type="checkbox" data-price="<?=$option_value['price']?>" data-modifier="<?=$option_value['price_modifier']?>"<?=$id[2] && $n == 0 ? ' required' : ''?><?=$option_value['quantity']==0?' disabled':''?>>
<span class="picture_select"><img src="<?=$media_item['full_path']?>"></span>
</label>
<?php endif; ?>
<?php endforeach; ?>
<?php else: ?>
<label>
<input id="<?=$option_value['id']?>" class="option checkbox" id="<?=$option_value['id']?>" value="<?=$option_value['name']?>" name="option-<?=$id[0]?>[]" type="checkbox" data-price="<?=$option_value['price']?>" data-modifier="<?=$option_value['price_modifier']?>"<?=$id[2] && $n == 0 ? ' required' : ''?><?=$option_value['quantity']==0?' disabled':''?>><?=$option_value['name']?>
</label>
<?php endif; ?>
<?php endforeach; ?>
</div>
<?php elseif ($id[1] == 'text'): ?>
<?php foreach ($option as $option_value): ?>
<label for="<?=$id[0]?>"><?=$id[0]?></label>
<input id="<?=$id[0]?>" class="option text" name="option-<?=$id[0]?>" type="text" placeholder="<?=$option_value['name']?>" data-price="<?=$option_value['price']?>" data-modifier="<?=$option_value['price_modifier']?>"<?=$id[2] ? ' required' : ''?><?=$option_value['quantity']==0?' disabled':''?>>
<?php endforeach; ?>
<?php elseif ($id[1] == 'datetime'): ?>
<?php foreach ($option as $option_value): ?>
<label for="<?=$id[0]?>"><?=$id[0]?></label>
<input id="<?=$id[0]?>" class="option datetime" name="option-<?=$id[0]?>" type="datetime-local"<?=$option_value['name'] ? 'value="' . date('Y-m-d\TH:i', strtotime($product['date_added'])) . '" ' : ''?> data-price="<?=$option_value['price']?>" data-modifier="<?=$option_value['price_modifier']?>"<?=$id[2] ? ' required' : ''?><?=$option_value['quantity']==0?' disabled':''?>>
<?php endforeach; ?>
<?php endif; ?>
<?php endforeach; ?>
<?php if ($product['quantity'] == 0): ?>
<?php if ((isset($_SESSION['account_loggedin'])) && $notifier == 0) :?>
<input type="hidden" value="1" name="notifier">
<input type="hidden" value="<?=$product['id'].' - '.$product['name']?>" name="product_details">
<input type="submit" value="<?=$out_of_stock_notify?>" class="btn">
<?php elseif (link_to_external_product_site != ''): ?>
<a href="<?= link_to_external_product_site ?>" style="text-align: center;font-style: italic;" class="btn" target="blank"><?=$out_of_stock_notify_2?></a>
<?php else: ?>
<label for="quantity"><?=$product_quantity?></label>
<input id="quantity" type="number" name="quantity" value="1" min="1"<?php if ($product['quantity'] != -1): ?> max="<?=$product['quantity']?>"<?php endif; ?> placeholder="Quantity" required>
<input type="submit" value="<?=$out_of_stock?>" class="btn" disabled>
<?php endif; ?>
<?php else: ?>
<label for="quantity"><?=$product_quantity?></label>
<input id="quantity" type="number" name="quantity" value="1" min="1"<?php if ($product['quantity'] != -1): ?> max="<?=$product['quantity']?>"<?php endif; ?> placeholder="Quantity" required>
<input type="submit" value="<?=$add_to_basket?>" class="btn">
<?php endif; ?>
</form> </form>
<div class="description"> <div class="description">
<?=$product['description']?> '.(${$product['productdescription']} ?? $product['productdescription']).'
</div> </div>
</div>
</div>';
</div> $view .= '
<script>
//Read urlstring
const queryString = window.location.href;
const option_id = queryString.substring(queryString.lastIndexOf(\'/\') + 1)
</div> //Check for option_id
if (option_id != \'\'){
<?php endif; ?> document.getElementById(option_id).checked = true;
<script> }
</script>';
//Read urlstring
const queryString = window.location.href;
const option_id = queryString.substring(queryString.lastIndexOf('/') + 1)
console.log(queryString)
//Check for option_id
if (option_id != ''){
document.getElementById(option_id).checked = true;
} }
//OUTPUT
echo $view;
</script> template_footer();
<?=template_footer()?> ?>

View File

@@ -140,7 +140,7 @@ $view .= '<div class="products-wrapper">';
$view .= ' $view .= '
<div class="product"> <div class="product">
<a href="'.url('index.php?page=product&rowID=' . ($product['url_slug'] ? ($product['url_slug'] ) : $product['rowID'])).'" id="'.$product['rowID'].'A" class="product"> <a href="'.url('index.php?page=product&rowID=' . ($product['url_slug'] ? ($product['url_slug'] ) : $product['rowID'])).'" id="'.$product['rowID'].'A" class="product">
<img src="'.$img_url.$product['full_path'].'" id="'.$product['rowID'].'" width="200" height="" alt="'.$product['productname'].'"> <img src="'.$img_url.$product['full_path'].'" id="'.$product['rowID'].'" width="200" height="" alt="'.(${$product['productname']} ?? $product['productname']).'">
</a>'; </a>';
//CHECK IF CONFIGURATION SETTING IS FOUND AND NOT EMPTY => USE GROUP TO DISPLAY IMAGES //CHECK IF CONFIGURATION SETTING IS FOUND AND NOT EMPTY => USE GROUP TO DISPLAY IMAGES
@@ -157,15 +157,13 @@ $view .= '<div class="products-wrapper">';
//GET ALL RELATED ATTRIBUTES //GET ALL RELATED ATTRIBUTES
foreach ($config['attributes'] as $attribute){ foreach ($config['attributes'] as $attribute){
$option_id = $attribute['alternative_media']; // ID of the LARGE IMAGE $option_id = $attribute['attribute_id']; // ID of the LARGE IMAGE
$IMG_small_id = $img_url.$attribute['full_path']; //URL TO SMALL IMAGE $IMG_small_id = $img_url.$attribute['full_path']; //URL TO SMALL IMAGE
$IMG_large_id = $img_url.$attribute['alternative_media_full_path']; //URL TO LARGE IMAGE $IMG_large_id = $img_url.$attribute['alternative_media_full_path']; //URL TO LARGE IMAGE
// Ensure attribute price is a numeric value // Ensure attribute price is a numeric value
$attribute_price = isset($attribute['price']) ? floatval($attribute['price']) : 0.00; $attribute_price = isset($attribute['price']) ? floatval($attribute['price']) : 0.00;
//$option_price = (isset($attribute['price'])) ? (currency_code.((isset($attribute['price_modifier']) && $attribute['price_modifier'] == 1) ? number_format(floatval($product_price+$attribute_price),2) : number_format(($product_price-$attribute_price),2))) : (($product_price != 0.00) ? currency_code.number_format($product_price,2) : '');
$option_price = isset($attribute['price']) $option_price = isset($attribute['price'])
// If price modifier is 1, add prices; otherwise, subtract // If price modifier is 1, add prices; otherwise, subtract
? ((isset($attribute['price_modifier']) && $attribute['price_modifier'] == 1) ? currency_code . number_format(floatval($product_price + $attribute_price), 2) : currency_code . number_format(floatval($product_price - $attribute_price), 2)) ? ((isset($attribute['price_modifier']) && $attribute['price_modifier'] == 1) ? currency_code . number_format(floatval($product_price + $attribute_price), 2) : currency_code . number_format(floatval($product_price - $attribute_price), 2))
@@ -207,7 +205,7 @@ $view .= '<div class="products-wrapper">';
} }
$option_id =''; $option_id ='';
$view .='<a href="'.url('index.php?page=product&rowID=' . ($product['url_slug'] ? $product['url_slug'].$option_id : $product['rowID'])).'" id="'.$product['rowID'].'B" class="product"> $view .='<a href="'.url('index.php?page=product&rowID=' . ($product['url_slug'] ? $product['url_slug'].$option_id : $product['rowID'])).'" id="'.$product['rowID'].'B" class="product">
<span class="name">'.$product['productname'].'</span>'; <span class="name">'.(${$product['productname']} ?? $product['productname']).'</span>';
if (isset($product_price)){ if (isset($product_price)){

View File

@@ -45,15 +45,25 @@ if (document.querySelector('.product-img-small')) {
if (document.querySelector('.product #product-form')) { if (document.querySelector('.product #product-form')) {
let updatePrice = () => { let updatePrice = () => {
let price = parseFloat(document.querySelector('.product .price').dataset.price); let price = parseFloat(document.querySelector('.product .price').dataset.price);
let rrp = parseFloat(document.querySelector('.product .rrp').dataset.rrp);
document.querySelectorAll('.product #product-form .option').forEach(e => { document.querySelectorAll('.product #product-form .option').forEach(e => {
if (e.value) { if (e.value) {
let optionPrice = e.classList.contains('text') || e.classList.contains('datetime') ? e.dataset.price : 0.00; let optionPrice = e.classList.contains('text') || e.classList.contains('datetime') ? e.dataset.price : 0.00;
optionPrice = e.classList.contains('select') ? e.options[e.selectedIndex].dataset.price : optionPrice; optionPrice = e.classList.contains('select') ? e.options[e.selectedIndex].dataset.price : optionPrice;
optionPrice = (e.classList.contains('radio') || e.classList.contains('checkbox')) && e.checked ? e.dataset.price : optionPrice; optionPrice = (e.classList.contains('radio') || e.classList.contains('checkbox')) && e.checked ? e.dataset.price : optionPrice;
price = (e.classList.contains('select') ? e.options[e.selectedIndex].dataset.modifier : e.dataset.modifier) == 'add' ? price+parseFloat(optionPrice) : price-parseFloat(optionPrice); price = (e.classList.contains('select') ? e.options[e.selectedIndex].dataset.modifier : e.dataset.modifier) == 1 ? price+parseFloat(optionPrice) : price-parseFloat(optionPrice);
let optionRRP = e.classList.contains('text') || e.classList.contains('datetime') ? e.dataset.rrp : 0.00;
optionRRP = e.classList.contains('select') ? e.options[e.selectedIndex].dataset.rrp : optionRRP;
optionRRP = (e.classList.contains('radio') || e.classList.contains('checkbox')) && e.checked ? e.dataset.rrp : optionRRP;
rrp = (e.classList.contains('select') ? e.options[e.selectedIndex].dataset.modifier : e.dataset.modifier) == 1 ? rrp+parseFloat(optionRRP) : rrp-parseFloat(optionRRP);
} }
}); });
document.querySelector('.product .price').innerHTML = currency_code + (price > 0.00 ? price.toFixed(2) : 0.00); document.querySelector('.product .price').innerHTML = currency_code + (price > 0.00 ? price.toFixed(2) : 0.00);
document.querySelector('.product .rrp').innerHTML = currency_code + (rrp > 0.00 ? rrp.toFixed(2) : 0.00);
}; };
document.querySelectorAll('.product #product-form .option').forEach(ele => ele.onchange = () => updatePrice()); document.querySelectorAll('.product #product-form .option').forEach(ele => ele.onchange = () => updatePrice());
updatePrice(); updatePrice();
@@ -76,6 +86,7 @@ if (document.querySelector('.cart .ajax-update')) {
let formEle = document.querySelector('.cart form'); let formEle = document.querySelector('.cart form');
let formData = new FormData(formEle); let formData = new FormData(formEle);
formData.append('update', 'Update'); formData.append('update', 'Update');
console.log(formData);
fetch(formEle.action, { fetch(formEle.action, {
method: 'POST', method: 'POST',
body: formData body: formData