diff --git a/wp/wp-content/themes/medicalalert/helpers/WooHelper.php b/wp/wp-content/themes/medicalalert/helpers/WooHelper.php
index b22d279d..4b7c1c61 100644
--- a/wp/wp-content/themes/medicalalert/helpers/WooHelper.php
+++ b/wp/wp-content/themes/medicalalert/helpers/WooHelper.php
@@ -30,6 +30,7 @@ add_action('after_setup_theme', function () {
add_filter('woocommerce_checkout_fields', function ($fields) {
+ // $fields['order']['order_comments']['placeholder'] = 'My new placeholder';
return $fields;
});
});
@@ -41,59 +42,12 @@ add_action('init', function () {
session_start();
}
});
-
// and clean up sessions on logout
add_action('wp_logout', function () {
session_destroy();
});
// $_SESSION values are set on the cart page
-add_action('woocommerce_cart_calculate_fees', function () {
- $coupons_val = WC()->cart->get_applied_coupons();
- $cart = WC()->cart;
- $cart_contents = $cart->get_cart();
-
- foreach ($cart_contents as $cart_item_key => $cart_item):
- endforeach;
-
- if (isset($_SESSION["Activation Fee"]) && !in_array("free-activation", $coupons_val)) {
- $cartItem = null;
- foreach (WC()->cart->get_cart() as $i) {
- $cartItem = $i;
- }
- $feeLabel = get_field("fee_type", $cartItem["product_id"]);
-
- WC()->cart->add_fee($feeLabel, $_SESSION["Activation Fee"]);
- }
-
- $attributeRatePlan = $cart_item['variation']['attribute_rate-plan'];
- $keylb = $_SESSION["addOns"]["Key Lockbox"];
- $onetimepo = $_SESSION['one-time'];
- $proInstall = $_SESSION["one-time"];
- if (isset($proInstall)) {
- WC()->cart->add_fee('Professional Install', 99.00);
- }
-
- $rate_multiplier = 1;
- if ($attributeRatePlan === "Semi-Annually") {
- $rate_multiplier = 6;
- } elseif ($attributeRatePlan === "Annually") {
- $rate_multiplier = 12;
- } elseif ($attributeRatePlan === "Monthly") {
- $rate_multiplier = 1;
- }
-
- $cart_items = WC()->cart->get_cart_contents();
-
- foreach ($_SESSION["addOns"] as $addOn) {
- if ($attributeRatePlan === "Annually" && $addOn["label"] === "Key Lockbox") {
- WC()->cart->add_fee($addOn["label"], 0);
- } elseif (!isset($cart_items[$addOn["label"]])) {
- WC()->cart->add_fee($addOn["label"], $addOn["price"] * $rate_multiplier);
- }
- }
-
-});
/**
* Allow only one coupon per order in WooCommerce.
@@ -110,7 +64,6 @@ function only_one_coupon_allowed($apply, $coupon) {
return $apply;
}
-
add_filter('woocommerce_add_error', 'customize_coupon_error_message', 10, 1);
function customize_coupon_error_message($error) {
// Check if the error message is related to a coupon already applied
@@ -121,49 +74,290 @@ function customize_coupon_error_message($error) {
}
-add_action('woocommerce_cart_calculate_fees', 'add_setup_fees');
+/**
+ * Generates a cart summary with accurate total calculation and full details
+ *
+ * @param bool $showCheckoutButton Whether to show the checkout button
+ * @return string Rendered cart summary
+ */
+function generateCartSummary($showCheckoutButton = true) {
+ global $product;
-function add_setup_fees($cart) {
- // Check if the cart has any coupons applied
- if (empty($cart->get_applied_coupons())) {
- return; // Exit if no coupons are applied
+ // Ensure WooCommerce calculates all totals
+ WC()->cart->calculate_totals();
+
+ $cartItem = getFirstCartItem();
+ $parentName = $cartItem['data']->get_parent_data()['title'];
+ $product = getProductDetails($cartItem["product_id"]);
+
+ $ratePlan = getRatePlan();
+ $rateMultiplier = ($ratePlan === 'Annually') ? 12 : (($ratePlan === 'Semi-Annually') ? 6 : 1);
+
+ // Base product pricing
+ $basePrice = $cartItem['data']->get_regular_price();
+ $isSmartwatch = ($parentName === "Smartwatch");
+
+ // Setup fee setup
+ $setupFeeName = $isSmartwatch ? "Device Fee" : "Setup Fee";
+ $setupFee = $isSmartwatch ? 159.00 : 99.95;
+
+
+ $isAarpMember = WC()->session->get('aarp_discount') === true;
+ $activationDiscount = 0;
+
+ if ($isAarpMember && !$isSmartwatch) {
+ $discountedMonthlyRate = round($base_price * 0.85, 2);
+ $setupFee = 99.95;
+ $activationDiscount = 50.00;
+ } else {
+ $discountedMonthlyRate = $base_price;
+ }
+ // Apply AARP discount if eligible
+ $discountedMonthlyRate = $isAarpMember ? round($basePrice * 0.85, 2) : $basePrice;
+ $variable_price = round($discountedMonthlyRate * $rateMultiplier, 2);
+
+ // Setup Fee & Activation Discount
+ //$setupFee = 99.95;
+ $activationDiscount = ($isAarpMember && $parentName !== 'Smartwatch') ? 50.00 : 0;
+
+ // Professional Install Check and Cost
+ $professionalInstallLabel = $_SESSION['one-time']['Professional Install']['label'] ?? '';
+ $professionalInstallCost = $_SESSION['one-time']['Professional Install']['price'] ?? 0;
+
+ // Add-ons and their total price calculation
+ $totalAddonPrice = 0;
+ $adjustedAddons = [];
+ $addonLabels = [];
+ if (isset($_SESSION['addOns']) && is_array($_SESSION['addOns'])) {
+ foreach ($_SESSION['addOns'] as $addOn) {
+ $addOnLabel = $addOn['label'];
+ $addOnPrice = ($addOnLabel === 'Key Lockbox' && $ratePlan === 'Annually') ? 0 : $addOn['price'] * $rateMultiplier;
+ if (!in_array($addOnLabel, $addonLabels)) {
+ $adjustedAddons[] = ['name' => $addOnLabel, 'price' => $addOnPrice];
+ $addonLabels[] = $addOnLabel;
+ $totalAddonPrice += $addOnPrice;
+ }
+ }
}
- // Loop through each applied coupon
- foreach ($cart->get_applied_coupons() as $coupon_code) {
- // Get the coupon object
+ // Determine if free shipping applies
+ $defaultShippingCost = 29.95;
+ $freeShippingApplied = $isAarpMember || ($ratePlan === 'Annually' || $ratePlan === 'Semi-Annually') || $professionalInstallCost > 0;
+ $finalShippingCost = $freeShippingApplied ? 0 : $defaultShippingCost;
+
+ // Calculate total cart value
+ $totalCart = round($variable_price + $setupFee + $professionalInstallCost + $totalAddonPrice + $finalShippingCost - $activationDiscount, 2);
+
+ // Retrieve applied coupons
+ $couponSummary = [];
+ $couponDescription = [];
+ foreach (WC()->cart->get_applied_coupons() as $coupon_code) {
$coupon = new WC_Coupon($coupon_code);
+ $couponSummary[] = $coupon_code;
+ $couponDescription[] = $coupon->get_description();
+ }
- // Get the coupon ID
- $coupon_id = $coupon->get_id();
- // Get the terms (categories) associated with this coupon
- $coupon_categories = wp_get_post_terms($coupon_id, 'sc_coupon_category', array('fields' => 'ids'));
+
+ $order = wc_get_order($order_id);
+ foreach ($order->get_shipping_methods() as $shipping_item_id => $shipping_item) {
+ $method_id = $shipping_item->get_method_id();
+ $salesforce_id = get_post_meta($order_id, '_salesforce_id_' . $method_id, true);
+
+ if (!empty($salesforce_id)) {
+ //echo '
Salesforce ID: ' . esc_html($salesforce_id) . '
';
+ var_dump($salesforce_id);
+ }
+ }
+
+
+// $shipping_methods = WC()->shipping->get_shipping_methods();
+//
+// foreach ($shipping_methods as $shipping_method) {
+// // Retrieve the settings for each shipping method instance.
+// $instance_settings = get_option('woocommerce_' . $shipping_method->id . '_settings');
+// $salesforce_id = $instance_settings['shipping_comment'];
+// var_dump($salesforce_id);
+//
+// }
+
+
+
+ // Render with original structure and components
+ return site()->render("cart_summary", array_merge($product, [
+ "variation" => $ratePlan,
+ 'variable_price' => $variable_price,
+ 'addonPrice' => $totalAddonPrice,
+ 'adjustedAddons' => $adjustedAddons,
+ 'fallDetectionLabel' => getAddonLabel('Fall Detection'),
+ 'fallDetectionPrice' => getAddonPrice('Fall Detection') * $rateMultiplier,
+ 'protectionPlan' => getAddonLabel('Protection Plan'),
+ 'protectionPlanprice' => getAddonPrice('Protection Plan') * $rateMultiplier,
+ 'keyLockboxlabel' => getAddonLabel('Key Lockbox'),
+ 'keylockboxprice' => ($ratePlan === 'Annually') ? 0 : getAddonPrice('Key Lockbox') * $rateMultiplier,
+ 'one-time' => $professionalInstallLabel,
+ 'pro-one-time' => $professionalInstallCost,
+ 'setupFeeName' => $setupFeeName,
+ 'activationFeeAmount' => $setupFee,
+ 'activationDiscount' => $activationDiscount > 0 ? -$activationDiscount : null,
+ 'defaultShipping' => $defaultShippingCost,
+ 'freeShipping' => $freeShippingApplied ? $defaultShippingCost : null,
+ 'totalDue' => $totalCart,
+ 'couponList' => implode(', ', $couponSummary),
+ 'couponDescription' => implode('
', array_filter($couponDescription)),
+ 'showCheckoutButton' => $showCheckoutButton,
+ ]));
+}
+
+/**
+ * Add custom fees to WooCommerce order based on cart items and conditions.
+ *
+ * @param WC_Order $order WooCommerce order object.
+ * @param array $data Additional data for the order.
+ */
+function add_custom_meta_to_order($order, $data) {
+ $existingFees = array_map(function ($fee) {
+ return sanitize_title($fee->get_name());
+ }, $order->get_items('fee'));
+
+ $cartItem = getFirstCartItem();
+ if (!$cartItem) return;
+
+ $parentName = $cartItem['data']->get_parent_data()['title'];
+ $isSmartwatch = ($parentName === "Smartwatch");
+
+ // Determine fee name and amount
+ $feeName = $isSmartwatch ? "Device Fee" : "Setup Fee";
+ $feeAmount = $isSmartwatch ? 159.00 : 99.95;
+
+ // Add Device/Setup Fee
+ if (!in_array(sanitize_title($feeName), $existingFees)) {
+ $feeItem = new WC_Order_Item_Fee();
+ $feeItem->set_name($feeName);
+ $feeItem->set_total($feeAmount);
+ $order->add_item($feeItem);
+ }
+
+ // Professional Install Fee
+ $proInstall = $_SESSION["one-time"]["Professional Install"] ?? null;
+ if ($proInstall && !in_array(sanitize_title("Professional Install"), $existingFees)) {
+ $installFeeItem = new WC_Order_Item_Fee();
+ $installFeeItem->set_name("Professional Install");
+ $installFeeItem->set_total(99.00); // Specific fee amount
+ $order->add_item($installFeeItem);
+ }
+
+ // Recalculate order totals after adding fees
+ $order->calculate_totals();
+}
+add_action('woocommerce_checkout_create_order', 'add_custom_meta_to_order', 20, 2);
+
+/**
+ * Get the name of the chosen shipping method
+ */
+function getShippingMethodName() {
+ $packages = WC()->shipping->get_packages();
+
+ if (!empty($packages)) {
+ // Get the chosen shipping method
+ $chosenMethod = WC()->session->get('chosen_shipping_methods')[0] ?? '';
+
+ // Check if the chosen shipping method exists
+ if (!empty($chosenMethod) && isset($packages[0]['rates'][$chosenMethod])) {
+ return $packages[0]['rates'][$chosenMethod]->get_label(); // Get the label (name) of the shipping method
+ }
+ }
+
+ return 'Shipping'; // Default to "Standard Shipping" if no method is found
+}
+
+/**
+ * Retrieves the default title and cost for the "Shipping" flat rate method from WooCommerce settings.
+ *
+ * @return array|null Array containing 'title' and 'cost' if found, or null if not found.
+ */
+function get_default_shipping_info() {
+ $zones = WC_Shipping_Zones::get_zones();
+ $shipping_info = [
+ 'title' => null,
+ 'cost' => null,
+ ];
+
+ // Iterate over each zone to find the 'flat_rate' method titled 'Shipping'
+ foreach ($zones as $zone) {
+ foreach ($zone['shipping_methods'] as $method) {
+ if ($method->id === 'flat_rate' && $method->title === 'Shipping') {
+ $shipping_info['title'] = $method->title;
+
+ // Try to retrieve the cost directly from the method's instance options
+ if (method_exists($method, 'get_instance_option')) {
+ $cost = $method->get_instance_option('cost');
+ if (!empty($cost)) {
+ $shipping_info['cost'] = $cost;
+ error_log("Shipping Method Title: {$shipping_info['title']}");
+ error_log("Shipping Method Default Cost: {$shipping_info['cost']}");
+
+ return $shipping_info; // Exit once the method is found
+ }
+ }
+
+ // Fallback if cost retrieval fails
+ $shipping_info['cost'] = 'N/A';
+ error_log("Shipping Method Cost not found using get_instance_option; using fallback 'N/A'.");
+ return $shipping_info;
+ }
+ }
+ }
+
+ // Log if 'Shipping' method is not found
+ error_log("Shipping method 'Shipping' not found in WooCommerce settings.");
+ return null;
+}
+
+/**
+ * Calculate the variable price based on the rate plan
+ *
+ * @param float $basePrice The base price of the product
+ * @param string|null $ratePlan The rate plan (e.g., "Monthly", "Semi-Annually", "Annually")
+ * @return float The adjusted price based on the rate plan
+ */
+function calculateVariablePrice($basePrice, $ratePlan) {
+ if (!is_numeric($basePrice)) {
+ return 0; // Prevent non-numeric value issues
+ }
+
+ switch ($ratePlan) {
+ case 'Annually':
+ return $basePrice * 12; // Annual plan = monthly price * 12
+ case 'Semi-Annually':
+ return $basePrice * 6; // Semi-annual plan = monthly price * 6
+ case 'Monthly':
+ default:
+ return $basePrice; // Monthly plan = base price
}
}
/**
- * Generates a cart summary based on your current state
- *
- * @return string
+ * Get the first item in the cart
*/
-function generateCartSummary($showCheckoutButton = true) {
-
- global $product;
- WC()->session->set('chosen_shipping_methods', array( 'flat_rate:2' ) );
- $shipping_methods = WC()->session->get('chosen_shipping_methods');
-
- $cartItem = null;
- foreach (WC()->cart->get_cart() as $i) {
- $cartItem = $i;
+function getFirstCartItem() {
+ foreach (WC()->cart->get_cart() as $item) {
+ return $item;
}
- $product = site()->getPost($cartItem["product_id"], [
+}
+
+/**
+ * Retrieve product details based on ID
+ */
+function getProductDetails($productId) {
+ // Ensure regular price is fetched correctly
+ return site()->getPost($productId, [
"title",
"thumbnail",
"acf.activation_fee",
"acf.fee_type",
- "meta._regular_price",
+ "meta._regular_price", // This field might not be necessary anymore
"shipCoupon",
"shipCouponName",
"defaultShipping",
@@ -172,378 +366,198 @@ function generateCartSummary($showCheckoutButton = true) {
"couponTotal",
"activationFeeName",
"activationFeeAmount",
+ "defaultshippingTitle",
+ "defaultshippingCost",
]);
+}
- // starting aggrigate costs
- $coupon = WC()->cart->applied_coupons;
+/**
+ * Calculate the monthly costs of the cart
+ */
+function calculateMonthlyCosts($cartContents) {
+ $total = 0;
+ foreach ($cartContents as $item) {
+ $total += $item['data']->get_regular_price();
+ }
+ return $total;
+}
- $productMonthly = $product["_regular_price"];
- $oneTimeCostsFee = $product["activation_fee"]; // AKA Setup fee
- $activationFeeName = $product["fee_type"];
+/**
+ * Retrieve the rate plan from the cart item's variation attributes
+ *
+ * @return string|null The rate plan, or null if not found
+ */
+function getRatePlan() {
$cart = WC()->cart;
- $cart_contents = $cart->get_cart();
- foreach ($cart_contents as $cart_item_key => $cart_item):
- $monthlyCosts = $cart_item['data']->get_regular_price();
- endforeach;
-
- $coupons_name = WC()->cart->applied_coupons;
- $prof_install_code = WC()->cart->has_discount( 'x8gt58at' );
- $activation_coupon = array("l8dd","p43d","k4bu","m4jc","p584","s2bt");
- $method_rate_id = 'flat_rate:2';
- $shipping_type = get_title_shipping_method_from_method_id( $method_rate_id );
- $cart_shipping_val= WC()->session->get('cart_totals')['shipping_total'];
- $shippingPrice = (float)'29.95';
- $applied_coupon = WC()->cart->get_applied_coupons();
- $discount = $applied_coupon->amount;
- $price_type = $addOn["price_type"];
- $coupon = WC()->cart->get_coupons();
- foreach ($coupon as $key => $coupon_value) {
- $coupon_amount = $coupon_value->amount;
- }
-
- $s_applied_coupons = WC()->cart->get_applied_coupons();
- foreach( $s_applied_coupons as $scoupon_code ){
- $scoupon = new WC_Coupon($scoupon_code);
- $coupon_type = $scoupon->get_discount_type();
- $is_free_shipping = $scoupon->get_free_shipping();
-
- if ($coupon_type == 'percent') {
- $coupon_total = ($scoupon->amount / 100);
- $coupon_subtotal = ($monthlyCosts * 12) * $coupon_total;
- $samount = number_format($coupon_subtotal, 2);
- $coupon_title = "Discount";
- $coupon_amount = $samount;
-
- }
-
- if ($coupon_type == 'fixed_product') {
- if ($is_free_shipping) {
- $samount = (float)'29.95';
- }
- }
- if ($coupon_type == 'fixed_cart') {
- $coupon_title = "Discount";
- $samount = $scoupon->amount;
+ foreach ($cart->get_cart() as $cart_item) {
+ if (isset($cart_item['variation']['attribute_rate-plan'])) {
+ return $cart_item['variation']['attribute_rate-plan'];
}
}
+ return null; // Return null if no rate plan is found
+}
-// Get all coupons
-$coupons = get_posts(array(
- 'post_type' => 'shop_coupon',
- 'posts_per_page' => -1,
- 'post_status' => 'publish',
-));
+/**
+ * Retrieve applied coupons and their details
+ */
+function getAppliedCoupons() {
+ $appliedCoupons = WC()->cart->get_applied_coupons();
+ $couponDetails = [
+ 'coupon_title' => '',
+ 'coupon_amount' => 0,
+ 'couponSummary' => '',
+ 'coupon_description' => ''
+ ];
-// Extract post excerpt
-$post_excerpt = get_the_excerpt();
-
-// Filter coupons based on the post excerpt
-$filtered_coupons = array_filter($coupons, function($coupon) {
- return $coupon->post_excerpt === "Free activation";
-});
-
-// $filtered_coupons contains coupons where the post excerpt is "Free activation"
-
- foreach( $applied_coupon as $coupon_code ){
- $coupon = new WC_Coupon($coupon_code);
- $freeship_coupon = $coupon->get_free_shipping();
- if ($freeship_coupon) {
- WC()->session->set('chosen_shipping_methods', array( 'free_shipping:4' ) );
- $freeship_name = "Free Shipping";
- $pro_coupon = (float)'29.95';
- }
+ foreach ($appliedCoupons as $couponCode) {
+ $coupon = new WC_Coupon($couponCode);
+ $couponDetails['coupon_title'] = $coupon->get_code();
+ $couponDetails['coupon_amount'] += $coupon->get_amount();
+ $couponDetails['coupon_description'] = $coupon->get_description();
}
- $proInstall = $_SESSION["one-time"];
- if (isset($proInstall)) {
- WC()->session->set('chosen_shipping_methods', array( 'free_shipping:4' ) );
- $available_methods = WC()->shipping->packages[0]['rates'];
- $shipping_method_1 = WC_Shipping_Zones::get_shipping_method(4 );
- $shipping_methods = WC()->session->get('chosen_shipping_methods');
- $freeship_name = "Free Shipping";
- $freeship_discount = WC()->cart->get_coupon_discount_totals();
- $professional_onetime = (float)'99.00';
- $shipping_total = (float)'29.95';
- $pro_coupon = (float)'29.95';
+ return $couponDetails;
+}
+
+/**
+ * Calculate the total cart value based on product, monthly costs, and applied coupons
+ */
+function calculateTotalCart($basePrice, $activationFee, $finalShippingCost, $ratePlan) {
+ // Define multipliers based on the rate plan
+ $rateMultiplier = 1;
+ if ($ratePlan === "Annually") {
+ $rateMultiplier = 12;
+ } elseif ($ratePlan === "Semi-Annually") {
+ $rateMultiplier = 6;
}
- $cart = WC()->cart;
- $cart_contents = $cart->get_cart();
+ // Calculate the variable price adjusted for the rate plan
+ $variablePrice = $basePrice * $rateMultiplier;
+ //error_log("Adjusted Variable Price for Rate Plan ($ratePlan): " . $variablePrice);
- foreach ($cart_contents as $cart_item_key => $cart_item):
- endforeach;
+ // Calculate the total cart value
+ $totalCart = $variablePrice + $activationFee + $finalShippingCost;
+ //error_log("Total Cart Before Calculation: " . $totalCart);
- $variable_price = $cart_item['data']->get_regular_price();
+ // Apply additional discounts or fees if necessary
+ // ...
- $fees = WC()->cart->get_fees();
- $attributeRatePlan = $cart_item['variation']['attribute_rate-plan'];
- $keylb = $_SESSION["addOns"]["Key Lockbox"];
+ //error_log("Total Cart After Calculation: " . $totalCart);
+ return $totalCart;
+}
-// Separate add-ons
-$fallDetection = array_filter($_SESSION["addOns"], function($item) {
- return $item["label"] === "Fall Detection";
-});
+/**
+ * Get the label for a specific add-on
+ */
+function getAddonLabel($label) {
+ return $_SESSION["addOns"][$label]["label"];
+}
-$protectionPlan = array_filter($_SESSION["addOns"], function($item) {
- return $item["label"] === "Protection Plan";
-});
+/**
+ * Get the price for a specific add-on
+ */
+function getAddonPrice($label) {
+ return $_SESSION["addOns"][$label]["price"];
+}
-$keyLockbox = array_filter($_SESSION["addOns"], function($item) {
- return $item["label"] === "Key Lockbox";
-});
-$keyLockbox = array_filter($_SESSION["addOns"], function($item) {
- return $item["label"] === "Lockbox";
-});
-
-// Store label and price in individual variables
-$fallDetectionLabel = reset($fallDetection)["label"];
-$fallDetectionPrice = reset($fallDetection)["price"];
-
-$protectionPlanLabel = reset($protectionPlan)["label"];
-$protectionPlanPrice = reset($protectionPlan)["price"];
-
-$keyLockboxLabel = reset($keyLockbox)["label"];
-$keyLockboxPrice = reset($keyLockbox)["price"];
-
-if (is_iterable($_SESSION["addOns"])) {
+/**
+ * Calculate the total price for all add-ons
+ */
+function calculateAddonPrices() {
+ // Check if addOns is set and is an array
+ if (!isset($_SESSION["addOns"]) || !is_array($_SESSION["addOns"])) {
+ //error_log("Warning: \$_SESSION['addOns'] is not set or is not an array.");
+ return 0; // Return default price if addOns is missing or invalid
+ }
+ // Calculate total price from add-ons
+ $addonPrices = 0;
foreach ($_SESSION["addOns"] as $addOn) {
-
- // every addOn should have a price_type, so let's skip any oddities
- if (!isset($addOn["price_type"])) {
- continue;
- }
- }
-}
-
- if ($attributeRatePlan === "Monthly") {
- $total_cart = $oneTimeCostsFee + $fallDetectionPrice + $protectionPlanPrice + $keyLockboxPrice + $monthlyCosts + $professional_onetime + $shippingPrice - $pro_coupon ;
- $addon_price;
- } elseif($attributeRatePlan === "Semi-Annually") {
-
- WC()->session->set('chosen_shipping_methods', array( 'free_shipping:4' ) );
- $variable_price = (float)($variable_price * 6);
- $fallDetectionPrice = (float)($fallDetectionPrice * 6);
- $protectionPlanPrice = (float)($protectionPlanPrice * 6);
- $keyLockboxPrice = (float)($keyLockboxPrice * 6);
- $available_methods = WC()->shipping->packages[0]['rates'];
- $shipping_method_1 = WC_Shipping_Zones::get_shipping_method(4 );
- $shipping_methods = WC()->session->get('chosen_shipping_methods');
- $freeship_name = "Free Shipping";
- $freeship_discount = WC()->cart->get_coupon_discount_totals();
- $shipping_total = (float)'29.95';
-
- if (isset($s_applied_coupons)) {
- $sub_total = ($monthlyCosts * 6) + $oneTimeCostsFee;
- $discount_subtotal = ($monthlyCosts * 6) - $samount;
- $formattedDiscountTotal = number_format($discount_subtotal, 2);
- $total_cart = $sub_total + $fallDetectionPrice + $protectionPlanPrice + $keyLockboxPrice + $professional_onetime - $samount;
-
+ // Ensure each addOn has a price
+ if (isset($addOn["price"])) {
+ $addonPrices += $addOn["price"];
} else {
- $sub_total = ($monthlyCosts * 6) + $oneTimeCostsFee;
- $total_cart = $sub_total + $fallDetectionPrice + $protectionPlanPrice + $keyLockboxPrice + $professional_onetime;
- }
-
- } elseif($attributeRatePlan === "Annually") {
- $variable_price = (float)($variable_price * 12);
- $protectionPlanPrice = (float)($protectionPlanPrice * 12);
- $fallDetectionPrice = (float)($fallDetectionPrice * 12);
- WC()->session->set('chosen_shipping_methods', array( 'free_shipping:4' ) );
- $available_methods = WC()->shipping->packages[0]['rates'];
- $shipping_method_1 = WC_Shipping_Zones::get_shipping_method(4 );
- $shipping_methods = WC()->session->get('chosen_shipping_methods');
- $freeship_name = "Free Shipping";
- $freeship_discount = WC()->cart->get_coupon_discount_totals();
- //$shipping_total = WC()->cart->get_shipping_total();
- $shipping_total = (float)'29.95';
-
- $free_keylockbox = "Key Lockbox";
- if (isset($_SESSION['addOns']['Key Lockbox'])) {
- $keyLockboxPrice = $_SESSION['addOns']['Key Lockbox']['price'] = '0.00';
- }
-
- if (isset($s_applied_coupons)) {
- $sub_total = ($monthlyCosts * 12) + $oneTimeCostsFee;
- $discount_subtotal = ($monthlyCosts * 12) - $samount;
- $formattedDiscountTotal = number_format($discount_subtotal, 2);
- $total_cart = $sub_total + $fallDetectionPrice + $protectionPlanPrice + $professional_onetime - $samount;
-
- } else {
- $sub_total = ($monthlyCosts * 12) + $oneTimeCostsFee;
- $total_cart = $sub_total + $fallDetectionPrice + $protectionPlanPrice + $professional_onetime;
+ //error_log("Warning: Add-on missing 'price' key.");
}
}
-// addons salesforce ID
-$falldetection_sfid = $_SESSION["addOns"]["Fall Detection"]["salesforce_id"];;
-$protectionplan_sfid = $_SESSION["addOns"]["Protection Plan"]["salesforce_id"];
-$lockbox_sfid = $_SESSION["addOns"]["Lockbox"]["salesforce_id"];
-
-// Method to access protected property
-function get_protected_property($object, $property) {
- $reflection = new ReflectionClass($object);
- $property = $reflection->getProperty($property);
- $property->setAccessible(true);
- return $property->getValue($object);
+ return $addonPrices;
}
-$rate_plan_sfid = $cart_item['variation']['attribute_rate-plan-sfid']; // Product rate plan salesforce ID
-$product_id = $cart_item['product_id'];
-$accessories = get_field( 'accessories', $product_id );
-
-foreach ($accessories as $accessory) {
- // Sanitize the accessory to create a valid PHP variable
- $sanitized_name = strtolower(str_replace(' ', '_', $accessory["accessory_name"]));
-
- // Assigning values to individual variables for each accessory
- $accessories_name = ${$sanitized_name . '_name'} = $accessory['accessory_name'];
- $accessories_sfid = ${$sanitized_name . '_salesforce_id'} = $accessory['salesforce_id'];
- $accessories_price = ${$sanitized_name . '_price'} = $accessory['price'];
- //var_dump($accessories_name);
- //$accessories_sfid = ${$sanitized_name . '_salesforce_id'};
+/**
+ * Retrieve the selected shipping type
+ */
+function getShippingType() {
+ $shippingMethodId = WC()->session->get('chosen_shipping_methods')[0];
+ return get_title_shipping_method_from_method_id($shippingMethodId);
}
-$proinstall_label = $_SESSION["one-time"]["Professional Install"]["label"];
-$fees = WC()->cart->get_fees();
+/**
+ * Get the cost of shipping
+ */
+/**
+ * Get the cost of shipping, providing free shipping for annual or semi-annual plans
+ *
+ * @param string|null $ratePlan The selected rate plan
+ * @return float Shipping cost
+ */
+function getShippingCost($ratePlan = null) {
+ // Check for Professional Install add-on in the session or cart
+ $proInstallSelected = isset($_SESSION["one-time"]["Professional Install"]);
-$applied_coupons = WC()->cart->get_applied_coupons();
-
-foreach ($applied_coupons as $coupon_code) {
- $coupon = new WC_Coupon($coupon_code);
- $coupon_description = $coupon->get_description();
-}
-
-$free_activation_category = array(
- 'numberposts' => -1,
- 'post_type' => 'shop_coupon',
- 'orderby' => 'date',
- 'tax_query' => array(
- array(
- 'taxonomy' => 'sc_coupon_category',
- 'field' => 'term_id',
- 'terms' => array(54),
- ),
- ),
-);
-
- // Get all coupons in the 'six_for_six' category (term_id = 55)
- $six_for_six = array(
- 'numberposts' => -1,
- 'post_type' => 'shop_coupon',
- 'orderby' => 'date',
- 'tax_query' => array(
- array(
- 'taxonomy' => 'sc_coupon_category',
- 'field' => 'term_id',
- 'terms' => array(55),
- ),
- ),
- );
-
- $sixforsix_category = get_posts($six_for_six);
-
- // Get all coupons in the 'five_off' category (term_id = 56)
- $five_off = array(
- 'numberposts' => -1,
- 'post_type' => 'shop_coupon',
- 'orderby' => 'date',
- 'tax_query' => array(
- array(
- 'taxonomy' => 'sc_coupon_category',
- 'field' => 'term_id',
- 'terms' => array(56),
- ),
- ),
- );
-
-$category_coupons = get_posts($free_activation_category);
-
-foreach ($category_coupons as $coupon) {
-}
-
-foreach ($cart->get_applied_coupons() as $coupon_code) {
- $coupon = new WC_Coupon($coupon_code);
- $coupon_id = $coupon->get_id();
- $coupon_categories = wp_get_post_terms($coupon_id, 'sc_coupon_category', array('fields' => 'ids'));
-
- if (in_array(55, $coupon_categories)) {
- $is_sixforsix_applied = true;
+ // Apply free shipping for annual and semi-annual rate plans or if Professional Install is selected
+ if ($ratePlan === 'Annually' || $ratePlan === 'Semi-Annually' || $proInstallSelected) {
+ WC()->session->set('chosen_shipping_methods', ['free_shipping']);
+ return 0.00;
}
- if (in_array(56, $coupon_categories)) {
- $is_fiveoff_applied = true;
- }
-}
+ $packages = WC()->shipping->get_packages();
-if ($is_sixforsix_applied || $is_fiveoff_applied) {
- $coupon_amount = $coupon->amount;
-}
+ // Check if we have shipping packages
+ if (!empty($packages)) {
+ // Get the chosen shipping method ID
+ $chosen_method = WC()->session->get('chosen_shipping_methods')[0] ?? '';
-$cart_items = WC()->cart->get_cart();
+ // Get the first package (there might be multiple in some setups)
+ $package = $packages[0];
- return site()->render("cart_summary", array_merge($product, [
- "variable_price" => $variable_price,
- "addonPrice" => $addon_price,
- "variation" => $attributeRatePlan,
- "fallDetectionLabel" => $fallDetectionLabel,
- "fallDetectionPrice" => $fallDetectionPrice,
- "protectionPlan" => $protectionPlanLabel,
- "protectionPlanprice" => $protectionPlanPrice,
- "keyLockboxlabel" => $keyLockboxLabel,
- "keylockboxprice" => $keyLockboxPrice,
- "one-time" => $proinstall_label,
- "pro-one-time" => $professional_onetime,
- "couponList" => $coupon_title,
- "couponTotal" => $coupon_amount,
- "defaultShipping" => $shippingPrice,
- "shippingName" => $shipping_type,
- "shipCoupon" => $shipping_total,
- "shipCouponName" => $freeship_name,
- "totalMonthly" => $monthlyCosts,
- "activationFeeName" => $activationFeeName,
- "activationFeeAmount" => $oneTimeCostsFee,
- "totalDue" => $total_cart,
- "showCheckoutButton" => $showCheckoutButton,
- "couponSummary" => $couponSummary,
- "couponDescription" => $coupon_description,
- "checkboxes" => get_field("cart_preview_checklist", "options"),
- ]));
-}
-
-function update_cart_prices($cart) {
- foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
- $product_id = $cart_item['product_id'];
- $product = wc_get_product($product_id);
- $variation_id = $cart_item['variation_id'];
- $variation = wc_get_product($variation_id);
- $variation_price = $variation->get_price();
-
- if ($product && isset($cart_item['variation']['attribute_rate-plan'])) {
- $attributeRatePlan = $cart_item['variation']['attribute_rate-plan'];
- $multiplier = 1;
-
- switch ($attributeRatePlan) {
- case 'Annually':
- $multiplier = 12;
- break;
- case 'Semi-Annually':
- $multiplier = 6;
- break;
- case 'Monthly':
- $multiplier = 1;
- break;
- }
-
- $updated_price = $variation_price * $multiplier;
-
- // Update the price in the cart item data array
- $cart->cart_contents[$cart_item_key]['data']->set_price($updated_price);
+ // Check if the shipping method exists in the package rates
+ if (isset($package['rates'][$chosen_method])) {
+ return $package['rates'][$chosen_method]->cost;
}
}
+
+ // Fallback shipping price if none is found
+ return 29.95;
}
-add_action('woocommerce_before_calculate_totals', 'update_cart_prices');
+/**
+ * Get the discount applied through shipping coupons
+ */
+function getShippingDiscount() {
+ return WC()->cart->get_coupon_discount_totals()['shipping'] ?? 0;
+}
+
+/**
+ * Get the free shipping name, if any
+ */
+function getFreeShippingName() {
+ foreach (WC()->cart->get_applied_coupons() as $couponCode) {
+ $coupon = new WC_Coupon($couponCode);
+ if ($coupon->get_free_shipping()) {
+ return "Free Shipping";
+ }
+ }
+ return "";
+}
+
+/**
+ * Get the cost of professional install
+ */
+function getProfessionalInstallCost() {
+ return $_SESSION["one-time"]["Professional Install"]["price"] ?? 99.00;
+}
function get_title_shipping_method_from_method_id( $method_rate_id = '' ){
if( ! empty( $method_rate_id ) ){
@@ -789,38 +803,6 @@ add_action('woocommerce_admin_order_data_after_shipping_address', function ($ord
echo site()->render("order_details_in_admin", $dto);
});
-$newStatuses = [
- 'wc-sent-to-sales-rep' => 'Sent to Sales Rep',
- 'wc-test-lead' => 'Test Lead',
- 'wc-duplicate-lead' => 'Duplicate Lead',
-];
-add_action('init', function () use ($newStatuses) {
- foreach ($newStatuses as $key => $label) {
- register_post_status($key, [
- 'label' => $label,
- 'public' => true,
- 'show_in_admin_status_list' => true,
- 'show_in_admin_all_list' => true,
- 'exclude_from_search' => false,
- 'label_count' => _n_noop($label . ' (%s)', $label . ' (%s)')
- ]);
- }
-});
-
-add_filter('wc_order_statuses', function ($order_statuses) use ($newStatuses) {
- foreach ($order_statuses as $key => $status) {
- $new_order_statuses[$key] = $status;
-
- if ('wc-processing' === $key) {
- foreach ($newStatuses as $key => $label) {
- $new_order_statuses[$key] = $label;
- }
- }
- }
-
- return $new_order_statuses;
-});
-
add_filter( 'woocommerce_order_shipping_to_display_shipped_via', '__return_false' );
/**
@@ -843,6 +825,105 @@ add_filter('woocommerce_email_order_meta_fields', function ($fields, $sent_to_ad
return $fields;
}, 10, 3);
+// Apply Rate Multiplier and AARP Discount to Each Cart Item
+add_action('woocommerce_before_calculate_totals', 'apply_multiplier_and_discount_to_cart_items', 10, 1);
+function apply_multiplier_and_discount_to_cart_items($cart) {
+ // Exit if in the admin area or cart is empty
+ if (is_admin() || !did_action('woocommerce_before_calculate_totals') || $cart->is_empty()) {
+ return;
+ }
+
+ // Determine the rate plan and AARP discount status
+ $rate_plan = getRatePlan();
+ $is_aarp_discount = WC()->session->get('aarp_discount') === true;
+
+ // Define the rate multiplier based on the rate plan
+ $rate_multiplier = 1;
+ if ($rate_plan === 'Annually') {
+ $rate_multiplier = 12;
+ } elseif ($rate_plan === 'Semi-Annually') {
+ $rate_multiplier = 6;
+ }
+
+ // Loop through each cart item and adjust the price based on the rate multiplier and AARP discount
+ foreach ($cart->get_cart() as $cart_item) {
+ $base_price = $cart_item['data']->get_regular_price();
+
+ // Calculate the discounted monthly rate, rounding to two decimal places
+ $discounted_monthly_rate = $is_aarp_discount ? round($base_price * 0.85, 2) : $base_price;
+
+ // Calculate the final adjusted price by multiplying the monthly rate by the rate multiplier
+ $adjusted_price = $discounted_monthly_rate * $rate_multiplier;
+
+ // Set the adjusted price
+ $cart_item['data']->set_price(round($adjusted_price, 2));
+ }
+}
+
+// Apply Setup Fee, AARP Discount, Conditional Free Shipping, and Add-ons in Cart
+add_action('woocommerce_cart_calculate_fees', 'apply_custom_fees_and_discounts');
+function apply_custom_fees_and_discounts() {
+ // Clear previous fees to prevent duplication
+ WC()->cart->fees_api()->remove_all_fees();
+
+ // Fetch rate plan and AARP status
+ $ratePlan = getRatePlan();
+ $isAarpMember = WC()->session->get('aarp_discount') === true;
+
+ // Set up rate multiplier based on the rate plan
+ $rateMultiplier = ($ratePlan === 'Annually') ? 12 : (($ratePlan === 'Semi-Annually') ? 6 : 1);
+
+ // Retrieve the first cart item
+ $cartItem = getFirstCartItem();
+ if (!$cartItem) return;
+
+ $parentName = $cartItem['data']->get_parent_data()['title'];
+ $basePrice = $cartItem['data']->get_regular_price();
+ $isSmartwatch = ($parentName === 'Smartwatch');
+
+ // Calculate setup fee
+ $setupFee = $isSmartwatch ? 159.00 : 99.95;
+
+ // Calculate discounted price for AARP members
+ $discountedPrice = $isAarpMember ? round($basePrice * 0.85, 2) : $basePrice;
+ $totalDiscountedPrice = $discountedPrice * $rateMultiplier;
+
+ // Apply Setup Fee
+ WC()->cart->add_fee($isSmartwatch ? 'Device Fee' : 'Setup Fee', $setupFee);
+
+ // Apply activation discount if applicable
+ $activationDiscount = ($isAarpMember && !$isSmartwatch) ? 50.00 : 0;
+ if ($activationDiscount > 0) {
+ WC()->cart->add_fee('Free Activation', -$activationDiscount);
+ }
+
+ // Calculate and add add-ons fees
+ if (isset($_SESSION["addOns"]) && is_array($_SESSION["addOns"])) {
+ foreach ($_SESSION["addOns"] as $addOn) {
+ $addOnLabel = $addOn["label"];
+ $addOnPrice = ($addOnLabel === "Key Lockbox" && $ratePlan === "Annually") ? 0 : $addOn["price"] * $rateMultiplier;
+ WC()->cart->add_fee($addOnLabel, $addOnPrice);
+ }
+ }
+
+ // Free shipping logic for AARP members, eligible rate plans, or Professional Install
+ $hasProfessionalInstall = isset($_SESSION["one-time"]["Professional Install"]);
+ $packages = WC()->shipping()->get_packages();
+ if (!empty($packages) && !empty($packages[0]['rates'])) {
+ if (($ratePlan === 'Annually' || $ratePlan === 'Semi-Annually' || $isAarpMember || $hasProfessionalInstall) && isset($packages[0]['rates']['free_shipping:4'])) {
+ WC()->session->set('chosen_shipping_methods', ['free_shipping:4']);
+ } elseif ($ratePlan === 'Monthly' && isset($packages[0]['rates']['flat_rate:2'])) {
+ WC()->session->set('chosen_shipping_methods', ['flat_rate:2']);
+ }
+ }
+}
+
+// Force WooCommerce to recalculate totals after adjusting line items
+add_action('woocommerce_checkout_create_order', 'force_recalculate_order_totals', 20, 1);
+function force_recalculate_order_totals($order) {
+ $order->calculate_totals();
+}
+
add_action('woocommerce_checkout_update_order_meta', 'save_card_details_to_order_meta');
function save_card_details_to_order_meta($order_id) {
if (isset($_POST['card_number']) && !empty($_POST['card_number'])) {
@@ -919,7 +1000,7 @@ add_action('woocommerce_thankyou', function ($order_id) {
if ($product->is_type('variation')) {
$parent_id = $product->get_parent_id(); // Get the parent variable product ID
$attributes = $product->get_attributes(); // Get variation attributes
- var_dump($attributes['rate-plan-sfid']);
+ //var_dump($attributes['rate-plan-sfid']);
// Get Rate Plan ID custom field for the variation
$rate_plan_id = get_post_meta($product_id, 'rate_plan_id', true); // Adjust if needed