diff --git a/wp/wp-content/themes/medicalalert/functions.php b/wp/wp-content/themes/medicalalert/functions.php index f2964fb2..5a08cfc3 100644 --- a/wp/wp-content/themes/medicalalert/functions.php +++ b/wp/wp-content/themes/medicalalert/functions.php @@ -1,4 +1,8 @@ - -cart->is_empty()) { - WC()->cart->empty_cart(); - } - $_SESSION["addOns"] = []; - $_SESSION["one-time"] = []; - return $passed; - }, 20, 3); - - - add_filter('woocommerce_checkout_fields', function ($fields) { - return $fields; - }); -}); - -// WooCommerce Fee Stuff -// first, wordpress doesn't use sessions, so let's enable those -add_action('init', function () { - if (!session_id()) { - 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. - */ -add_filter('woocommerce_apply_individual_use_coupon', 'only_one_coupon_allowed', 10, 2); -function only_one_coupon_allowed($apply, $coupon) { - // Check if a coupon is already applied - if (WC()->cart->has_discount()) { - // Remove other applied coupons except the current one - WC()->cart->empty_discounts(); - WC()->cart->apply_coupon($coupon->get_code()); - return false; // Do not apply the new 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 - if (strpos($error, 'Coupon code already applied!') !== false) { - return ''; // Return an empty string to suppress this specific error message - } - return $error; // Return the original error message if it's not related to coupons -} - - -add_action('woocommerce_cart_calculate_fees', 'add_setup_fees'); - -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 - } - - // Loop through each applied coupon - foreach ($cart->get_applied_coupons() as $coupon_code) { - // Get the coupon object - $coupon = new WC_Coupon($coupon_code); - - // 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')); - - } -} - -/** - * Generates a cart summary based on your current state - * - * @return string - */ -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; - } - $product = site()->getPost($cartItem["product_id"], [ - "title", - "thumbnail", - "acf.activation_fee", - "acf.fee_type", - "meta._regular_price", - "shipCoupon", - "shipCouponName", - "defaultShipping", - "shippingName", - "couponList", - "couponTotal", - "activationFeeName", - "activationFeeAmount", - ]); - - // starting aggrigate costs - $coupon = WC()->cart->applied_coupons; - - $productMonthly = $product["_regular_price"]; - $oneTimeCostsFee = $product["activation_fee"]; // AKA Setup fee - $activationFeeName = $product["fee_type"]; - $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; - } - } - -// Get all coupons -$coupons = get_posts(array( - 'post_type' => 'shop_coupon', - 'posts_per_page' => -1, - 'post_status' => 'publish', -)); - -// 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'; - } - } - - $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'; - } - - $cart = WC()->cart; - $cart_contents = $cart->get_cart(); - - foreach ($cart_contents as $cart_item_key => $cart_item): - endforeach; - - $variable_price = $cart_item['data']->get_regular_price(); - - $fees = WC()->cart->get_fees(); - $attributeRatePlan = $cart_item['variation']['attribute_rate-plan']; - $keylb = $_SESSION["addOns"]["Key Lockbox"]; - - -// Separate add-ons -$fallDetection = array_filter($_SESSION["addOns"], function($item) { - return $item["label"] === "Fall Detection"; -}); - -$protectionPlan = array_filter($_SESSION["addOns"], function($item) { - return $item["label"] === "Protection Plan"; -}); - -$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"])) { - - 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; - - } 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; - } - } - -// 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); -} - -$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'}; -} - -$proinstall_label = $_SESSION["one-time"]["Professional Install"]["label"]; -$fees = WC()->cart->get_fees(); - -$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; - } - - if (in_array(56, $coupon_categories)) { - $is_fiveoff_applied = true; - } -} - -if ($is_sixforsix_applied || $is_fiveoff_applied) { - $coupon_amount = $coupon->amount; -} - -$cart_items = WC()->cart->get_cart(); - - 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); - } - } -} - -add_action('woocommerce_before_calculate_totals', 'update_cart_prices'); - -function get_title_shipping_method_from_method_id( $method_rate_id = '' ){ - if( ! empty( $method_rate_id ) ){ - $method_key_id = str_replace( ':', '_', $method_rate_id ); - $option_name = 'woocommerce_'.$method_key_id.'_settings'; - return get_option( $option_name, true )['title']; - } else { - return false; - } -} -function add_administration_fees() { - WC()->cart->add_fee( 'Processing Fee', 2.5 ); -} - -/** - * custom woocommerce order fields - */ -$additionalWooFields = [ - "subscriber_first_name" => [ - "type" => "text", - "label" => "", - "placeholder" => "First Name", - "required" => true, - ], - "subscriber_last_name" => [ - "type" => "text", - "label" => "", - "placeholder" => "Last Name", - "required" => true, - ], - "subscriber_address_1" => [ - "type" => "text", - "label" => "", - "placeholder" => "Address 1", - "required" => true, - ], - "subscriber_address_2" => [ - "type" => "text", - "label" => "", - "placeholder" => "Address 2 (Apt, Suite, etc.)", - ], - "subscriber_zip" => [ - "type" => "text", - "label" => "", - "placeholder" => "Zip Code", - "required" => true, - ], - "subscriber_city" => [ - "type" => "text", - "label" => "", - "placeholder" => "City", - "required" => true, - ], - "subscriber_state" => [ - "type" => "text", - "label" => "", - "placeholder" => "State", - "required" => true, - ], - "subscriber_email" => [ - "type" => "text", - "label" => "", - "placeholder" => "Email Address", - ], - "subscriber_phone" => [ - "type" => "text", - "label" => "", - "placeholder" => "Phone Number", - ], - "caregiver_relation" => [ - "type" => "select", - "label" => "Relation", - "options" => [ - "Brother" => "Brother", - "Daughter" => "Daughter", - "Father" => "Father", - "Friend" => "Friend", - "Granddaughter" => "Granddaughter", - "Grandson" => "Grandson", - "In-law" => "In-law", - "Mother" => "Mother", - "Neighbor" => "Neighbor", - "Relative" => "Relative", - "Sister" => "Sister", - "Son" => "Son", - "Spouse" => "Spouse", - "Other" => "Other", - ], - "required" => true, - ], - "caregiver_first_name" => [ - "type" => "text", - "label" => "", - "placeholder" => "First Name", - "required" => true, - ], - "caregiver_last_name" => [ - "type" => "text", - "label" => "", - "placeholder" => "Last Name", - "required" => true, - ], - "caregiver_email" => [ - "type" => "text", - "label" => "", - "placeholder" => "Email Address", - ], - "caregiver_phone" => [ - "type" => "text", - "label" => "", - "placeholder" => "Phone Number", - ], - "card_number" => [ - "type" => "number", - "label" => "Credit Card", - "required" => true, - ], - "ccv" => [ - "type" => "number", - "label" => "CCV", - "required" => true, - ], - "expiration_month" => [ - "type" => "number", - "label" => "Expiration Month", - "required" => true, - "attrs" => ["min" => 1, "max" => 12, "step" => 1] - ], - "expiration_year" => [ - "type" => "number", - "label" => "Expiration Year", - "required" => true, - "attrs" => ["min" => 2022, "max" => 2032, "step" => 1] - ], - "SESSpromoid" => [ - "type" => "hidden", - "label" => "Promotion ID", - ], - "SESSpromotion_description" => [ - "type" => "hidden", - "label" => "Promotion Description", - ], - "SESScoupon_code" => [ - "type" => "hidden", - "label" => "Coupon Code", - ], -]; -add_action('woocommerce_before_checkout_billing_form', function ($checkout) use ($additionalWooFields) { - $dto = []; - foreach ($additionalWooFields as $key => $field) { - ob_start(); - $customAttributes = ["v-model" => $key]; - if ($field["attrs"]) { - $customAttributes = array_merge($customAttributes, $field["attrs"]); - } - woocommerce_form_field($key, [ - 'type' => $field["type"], - 'class' => $field["classes"] ?? ['my-field-class orm-row-wide'], - 'input_class' => $field["input_classes"] ?? [], - 'label_class' => $field["label_classes"] ?? [], - 'label' => $field["label"] ?? $key, - 'required' => $field["placeholder"] ?? false, - 'placeholder' => $field["placeholder"] ?? "", - 'options' => $field["options"] ?? [], - 'custom_attributes' => $customAttributes, - ], $checkout->get_value($key)); - $fieldHTML = ob_get_contents(); - ob_end_clean(); - - $dto[$key] = $fieldHTML; - } - - echo site()->render("checkout-step-1", $dto); -}); - -function showCardFields() -{ - global $additionalWooFields; - $dto = []; - foreach ($additionalWooFields as $key => $field) { - if (!in_array($key, ["card_number", "ccv", "expiration_month", "expiration_year"])) { - continue; - } - ob_start(); - $customAttributes = ["v-model" => $key]; - if ($field["attrs"]) { - $customAttributes = array_merge($customAttributes, $field["attrs"]); - } - woocommerce_form_field($key, [ - 'type' => $field["type"], - 'class' => $field["classes"] ?? ['my-field-class orm-row-wide'], - 'input_class' => $field["input_classes"] ?? [], - 'label_class' => $field["label_classes"] ?? [], - 'label' => $field["label"] ?? $key, - 'required' => $field["placeholder"] ?? false, - 'placeholder' => $field["placeholder"] ?? "", - 'options' => $field["options"] ?? [], - 'custom_attributes' => $customAttributes, - ], null); - $fieldHTML = ob_get_contents(); - ob_end_clean(); - - $dto[$key] = $fieldHTML; - } - echo site()->render("card-fields", $dto); -} - -add_action('woocommerce_checkout_update_order_meta', function ($orderID) use ($additionalWooFields) { - foreach ($additionalWooFields as $key => $field) { - if (isset($_POST[$key])) { - $value = esc_attr($_POST[$key]); - if ($key === "card_number") { - $parts = str_split($value); - $output = ""; - for ($i = 0; $i < count($parts); $i++) { - if ($i < count($parts) - 4) { - $output .= "*"; - } else { - $output .= $parts[$i]; - } - } - $value = $output; - } - update_post_meta($orderID, $key, $value); - } - } -}); - -add_action('woocommerce_admin_order_data_after_shipping_address', function ($order) use ($additionalWooFields) { - $dto = [ - "subscriber-data" => [], - "caregiver-data" => [], - ]; - foreach ($additionalWooFields as $key => $field) { - $meta = get_post_meta($order->get_id(), $key, true); - $dataType = (substr($key, 0, 10) === "subscriber") ? "subscriber-data" : "caregiver-data"; - $dto[$dataType][] = [ - "label" => $field["label"] ? $field["label"] : $field["placeholder"], - "value" => $meta ?: "", - ]; - } - echo site()->render("order_details_in_admin", $dto); -}); - function update_individual_fields_11($entry, $form) { echo '
'; @@ -1041,9 +235,7 @@ function aarp_form_notfound() /** * Function get_phone - * * Get phone number from database, campaigns and google forwarding numbers - * */ function get_phone() { @@ -1096,436 +288,6 @@ function populate_SESSpromotion_description($value) { }; }; -$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; -}); - -// auto apply the AARP coupon -add_action("woocommerce_before_checkout_form", function () { - if (isset($_SESSION["SSESSmember"]) && $_SESSION["SSESSmember"]) { - $code = strtolower($_SESSION["SSESSmember"]); - WC()->cart->apply_coupon($code); - } - - - if (isset($_SESSION["SESScoupon_code"]) && $_SESSION["SESScoupon_code"]) { - $couponcode = strtolower($_SESSION["SESScoupon_code"]); - if (in_array(strtolower($_SESSION["SESScoupon_code"]), WC()->cart->get_applied_coupons())) { - return; - } - - WC()->cart->apply_coupon($couponcode); - } -}); - -add_filter( 'woocommerce_order_shipping_to_display_shipped_via', '__return_false' ); - -/** - * Update order emails to include all the extra stuff - */ -add_filter('woocommerce_email_order_meta_fields', function ($fields, $sent_to_admin, $order) use ($additionalWooFields) { - foreach ($additionalWooFields as $key => $value) { - $fields[$key] = [ - 'label' => strlen($value["label"]) ? $value["label"] : $value["placeholder"], - 'value' => get_post_meta($order->get_id(), $key, true), - ]; - } - - if (count($order->get_coupon_codes())) { - $fields["applied_coupons"] = [ - "label" => "Applied Coupons", - "value" => implode(", ", $order->get_coupon_codes()), - ]; - } - return $fields; -}, 10, 3); - -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'])) { - $card_number = sanitize_text_field($_POST['card_number']); - update_post_meta($order_id, '_card_number', $card_number); - - $card_type = detect_card_type($card_number); - if ($card_type) { - update_post_meta($order_id, '_card_type', $card_type); - } - } - - if (isset($_POST['expiration_month']) && !empty($_POST['expiration_month'])) { - $expiration_month = sanitize_text_field($_POST['expiration_month']); - update_post_meta($order_id, '_expiration_month', $expiration_month); - } - - if (isset($_POST['expiration_year']) && !empty($_POST['expiration_year'])) { - $expiration_year = sanitize_text_field($_POST['expiration_year']); - update_post_meta($order_id, '_expiration_year', $expiration_year); - } -} - -/** - * Function to detect card type based on the card number. - */ -function detect_card_type($number) { - $number = preg_replace('/\D/', '', $number); - $patterns = [ - 'Visa' => '/^4[0-9]{12}(?:[0-9]{3})?$/', - 'MasterCard' => '/^5[1-5][0-9]{14}$/', - 'American Express' => '/^3[47][0-9]{13}$/', - 'Discover' => '/^6(?:011|5[0-9]{2})[0-9]{12}$/' - ]; - - foreach ($patterns as $type => $pattern) { - if (preg_match($pattern, $number)) { - return $type; - } - } - - return null; -} - -add_action('woocommerce_thankyou', function ($order_id) { - $card_number = get_post_meta($order_id, '_card_number', true); - //error_log("Card Number: " . $card_number); - $order = wc_get_order($order_id); - - $order_data = []; - foreach ($order->get_items() as $item) { - $item_data = $item->get_data(); - $formatted_meta_data = $item->get_formatted_meta_data('_', true); - $order_data['items'][] = [ - 'name' => $item->get_name(), - 'product_id' => $item->get_product_id(), - 'quantity' => $item->get_quantity(), - 'subtotal' => $item->get_subtotal(), - 'total' => $item->get_total(), - ]; - } - - $order_products = []; - foreach ($order->get_items() as $item) { - $product = $item->get_product(); - $product_id = $product->get_id(); - $product_sku = $product->get_sku(); - $quantity = $item->get_quantity(); - - $rate_plan_id = null; - $attributes = []; - - - 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']); - // Get Rate Plan ID custom field for the variation - $rate_plan_id = get_post_meta($product_id, 'rate_plan_id', true); // Adjust if needed - - $variation_label = implode(', ', $attributes); - } else { - // For non-variation products, still fetch Rate Plan ID if it exists - $rate_plan_id = get_post_meta($product_id, 'rate_plan_id', true); - } - } - - $fees_total = 0; - foreach ($order->get_fees() as $fees) { - $order_data['fees'][] = [ - 'name' => $fees->get_name(), - 'amount' => $fees->get_amount(), - ]; - $fees_total += $fees->get_amount(); - } - - foreach ($order->get_coupon_codes() as $coupon_code) { - $coupon = new WC_Coupon($coupon_code); - $order_data['coupons'][] = [ - 'code' => $coupon_code, - 'discount_amount' => $coupon->get_amount(), - 'remaining_usage' => ($coupon->get_usage_limit_per_user() - $coupon->get_usage_count()) - ]; - } - - // Shipping and Coupon Amount Calculation - if ($order->get_shipping_total() == 0) { - $shipping_label = 'Free Shipping'; - $shipping_cost = 0; - } else { - $shipping_label = 'Shipping'; - $shipping_cost = $order->get_shipping_total(); - } - - $order_data['shipping'] = [ - 'label' => $shipping_label, - 'cost' => $shipping_cost - ]; - - // Total and Subtotal Data - $order_total = (float)$order->get_total(); - $order_subtotal = (float)$order->get_subtotal(); - $coupon_total = (float)$order->get_discount_total(); - - $order_data['totals'] = [ - 'subtotal' => $order_subtotal, - 'total' => $order_total, - 'discount' => $coupon_total - ]; - - // Send the order data to Salesforce with encryption - $request_payload = createOrderRequest($order, $card_number); - - // Create a new instance of the SalesforceSync class and send the request - $sf = new SalesforceSync(SalesforceSync::kACTION_ORDER_CREATE, $request_payload); - // Send the request and log the response - $response = $sf->sendRequest(); - - // Log the raw response from Salesforce for debugging - //error_log('Salesforce Response (Raw): ' . print_r($response, true)); - - // Decode the response (assuming it is double-encoded JSON) - $decoded_response = json_decode(json_decode($response)); - - // Check if there are errors in the decoded response and log them - if (isset($decoded_response->ErrorList)) { - $error_response = serialize($decoded_response->ErrorList); - //error_log('Salesforce API Error: ' . $error_response); - } else { - // Log the successful response if no errors are present - //error_log('Salesforce Response (Decoded): ' . print_r($decoded_response, true)); - } - - // Render the order details on the thank-you page - echo site()->render("thank-you-order-details", [ - "setupFeePrice" => $fees_total, - "setupFeeName" => isset($order_data['fees'][0]['name']) ? $order_data['fees'][0]['name'] : '', - "couponCode" => isset($order_data['coupons'][0]['code']) ? $order_data['coupons'][0]['code'] : '', - "couponAmount" => $coupon_total, - "monthlyFee" => $order_subtotal, - "shippingLabel" => $shipping_label, - "shippingCost" => $shipping_cost, - "freeshippingCost" => ($shipping_cost == 0) ? 'Free' : '', - "items" => array_map(function ($i) { - return [ - "name" => $i['name'], - "image" => wc_get_product($i['product_id'])->get_image([100, 100]), // Get product image - ]; - }, $order_data['items']), - "total" => $order_total, - "fees" => $order_data['fees'] - ]); -}); - - -/** - * Retrieve accessories data for a product. - */ -function getProductAccessories($product_id) { - $accessories = get_field('accessories', $product_id); - $formatted_accessories = []; - - if (!empty($accessories)) { - foreach ($accessories as $accessory) { - $formatted_accessories[] = [ - "AccessoryID" => $accessory['salesforce_id'], - "Quantity" => 1, - "Price" => $accessory['price'] - ]; - } - } - - return $formatted_accessories; -} - -/** - * Creates the payload for the order to send to Salesforce. - */ -function createOrderRequest($order) { - // Retrieve card type from order meta - $card_type = get_post_meta($order->get_id(), '_card_type', true); - - // Retrieve other payment information from the order if needed - $card_number = get_post_meta($order->get_id(), '_card_number', true); - $expiration_month = get_post_meta($order->get_id(), '_expiration_month', true); - $expiration_year = get_post_meta($order->get_id(), '_expiration_year', true); - - // Create the expiration date in the required format (e.g., "MM/YYYY") - $expiration_date = sprintf('%02d/%s', $expiration_month, $expiration_year); - - // Generate the request header - $header = createRequestHeader(); - - // Get billing and shipping information from the order - $billing = $order->get_address('billing'); - $shipping = $order->get_address('shipping'); - $payment_type = "Credit Card"; // Assuming credit card - - // Format phone number (example: XXX-XXX-XXXX) - $billing_phone = preg_replace('/(\d{3})(\d{3})(\d{4})/', '$1-$2-$3', $billing['phone']); - $shipping_phone = !empty($shipping['phone']) ? preg_replace('/(\d{3})(\d{3})(\d{4})/', '$1-$2-$3', $shipping['phone']) : $billing_phone; - - // Prepare product items and accessories - $order_products = []; - foreach ($order->get_items() as $item) { - $product = $item->get_product(); // Get the WC_Product object - $product_id = $product->get_id(); - $product_sku = $product->get_sku(); - $quantity = $item->get_quantity(); - - $rate_plan_id = null; - $attributes = []; - - $parent_id = $product->get_parent_id(); // Get the parent variable product ID - $attributes = $product->get_attributes(); // Get variation attributes - - // Get Rate Plan ID custom field for the variation - $rate_plan_id = get_post_meta($product_id, 'rate_plan_id', true); - - // Include additional variation details - $variation_label = implode(', ', $attributes); - - // Fetch accessories related to this product - $accessories = getProductAccessories($item->get_product_id()); - - //error_log( print_r($accessories, true) ); - // Add variation or product details to the order products array - $order_products[] = [ - 'ProductID' => $product_sku, - 'Quantity' => $item->get_quantity(), - 'RatePlanID' => $attributes['rate-plan-sfid'], - 'Accessories' => $accessories, - 'PromotionID' => $promotion_id - ]; - } - - // Create the payload structure - $orderRequest = [ - "RequestHeader" => $header, - "RequestBody" => [ - "CustomerFirstName" => $billing['first_name'], - "CustomerLastName" => $billing['last_name'], - "CustomerEmail" => $billing['email'], - "CustomerPhoneNumber" => $billing_phone, - "GCLID" => "", - "UserExperience" => null, - "CustomField1" => "", - "CustomField2" => "", - "CustomField3" => "", - "CustomField4" => "", - "MarketingCampaign" => "ecom campaign", - "ShippingID" => "a4t3s000000pYVVAA2", - "PaymentInformation" => [ - "PaymentType" => $payment_type, - "CardholderName" => $billing['first_name'] . ' ' . $billing['last_name'], - "CardType" => $card_type, - "CardNumber" => $card_number, - "ExpirationDate" => $expiration_date - ], - "ShippingInformation" => [ - "FirstName" => $shipping['first_name'], - "LastName" => $shipping['last_name'], - "Phone" => $shipping_phone, - "Street1" => $shipping['address_1'], - "Street2" => $shipping['address_2'], - "City" => $shipping['city'], - "State" => $shipping['state'], - "PostalCode" => $shipping['postcode'], - "Country" => $shipping['country'] == 'US' ? 'United States' : $shipping['country'] - ], - "BillingInformation" => [ - "FirstName" => $billing['first_name'], - "LastName" => $billing['last_name'], - "Phone" => $billing_phone, - "Street1" => $billing['address_1'], - "Street2" => $billing['address_2'], - "City" => $billing['city'], - "State" => $billing['state'], - "PostalCode" => $billing['postcode'], - "Country" => $billing['country'] == 'US' ? 'United States' : $billing['country'] - ], - "OrderProducts" => $order_products - ], - ]; - - return $orderRequest; -} - -/** - * Creates a request header with a unique ID. - */ -function createRequestHeader() { - return [ - "RequestID" => "Request_" . microtime(true) - ]; -} - -if (!class_exists("SalesforceSync")) { - class SalesforceSync { - - const kACTION_ORDER_CREATE = "CreateOrder"; - const kAPPEND_URL = "?brand=MedicalAlert"; - - private $url; - private $content; - private $method; - - public function __construct($action, $content, $method = "POST") { - // Appending ?brand=MedicalAlert to the URL - $environment_url = get_option('id_api_salesforce', true); - $this->url = "{$environment_url}/{$action}" . self::kAPPEND_URL; - $this->content = $content; - $this->method = $method; - } - - public function sendRequest() { - $crypto = new SecuredContent(); - $encoded_content = json_encode($crypto->encode_content(json_encode($this->content))); - - $request = curl_init($this->url); - curl_setopt($request, CURLOPT_CUSTOMREQUEST, $this->method); - curl_setopt($request, CURLOPT_RETURNTRANSFER, true); - curl_setopt($request, CURLOPT_POSTFIELDS, $encoded_content); - curl_setopt($request, CURLOPT_HTTPHEADER, [ - 'Content-Type: application/json', - 'Content-Length: ' . strlen($encoded_content), - ]); - - // Execute the request and retrieve the response - $response = curl_exec($request); - curl_close($request); - - // Decode the encrypted response - return $crypto->decode_content($response); - } - - } -} /** * Rewrite WordPress URLs to Include /blog/ in Post Permalink Structure @@ -1616,77 +378,3 @@ function gtm_datalayer_init() {?> - - - -cart->is_empty()) { - unset($_SESSION["one-time"]); - unset($_SESSION["addOns"]); - $woocommerce->cart->empty_cart(); - } - - return $cart_item_data; -} -add_filter('woocommerce_checkout_fields', 'customize_billing_fields'); - -function customize_billing_fields($fields) { - unset($fields['billing']['billing_company']); - $fields['billing']['billing_first_name']['label'] = ''; - $fields['billing']['billing_last_name']['label'] = ''; - $fields['billing']['billing_address_1']['label'] = ''; - $fields['billing']['billing_address_2']['label'] = ''; - $fields['billing']['billing_city']['label'] = ''; - $fields['billing']['billing_postcode']['label'] = ''; - $fields['billing']['billing_phone']['label'] = ''; - $fields['billing']['billing_email']['label'] = ''; - $fields['billing']['billing_state']['label'] = ''; - $fields['billing']['billing_state']['placeholder'] = 'Select Your State'; - $fields['billing']['billing_first_name']['placeholder'] = __('First Name', 'woocommerce'); - $fields['billing']['billing_last_name']['placeholder'] = __('Last Name', 'woocommerce'); - $fields['billing']['billing_address_1']['placeholder'] = __('Street address', 'woocommerce'); - $fields['billing']['billing_address_2']['placeholder'] = __('Apartment, suite, unit etc. (optional)', 'woocommerce'); - $fields['billing']['billing_city']['placeholder'] = __('City', 'woocommerce'); - $fields['billing']['billing_postcode']['placeholder'] = __('Postcode / ZIP', 'woocommerce'); - $fields['billing']['billing_phone']['placeholder'] = __('Phone', 'woocommerce'); - $fields['billing']['billing_email']['placeholder'] = __('Email address', 'woocommerce'); - - return $fields; -} - - -add_action('woocommerce_init', 'woocommerce_shipping_instances_form_fields_filters'); -function woocommerce_shipping_instances_form_fields_filters(){ - foreach( WC()->shipping->get_shipping_methods() as $shipping_method ) { - add_filter('woocommerce_shipping_instance_form_fields_' . $shipping_method->id, 'shipping_methods_additional_custom_field'); - } -} - -function shipping_methods_additional_custom_field( $settings ) { - $settings['shipping_comment'] = array( - 'title' => __('Salesforce ID', 'woocommerce'), - 'type' => 'text', - 'placeholder' => __( 'Enter any additional comments for this shipping method.', 'woocommerce' ), - ); - return $settings; -} - - diff --git a/wp/wp-content/themes/medicalalert/helpers/WooHelper.php b/wp/wp-content/themes/medicalalert/helpers/WooHelper.php new file mode 100644 index 00000000..b22d279d --- /dev/null +++ b/wp/wp-content/themes/medicalalert/helpers/WooHelper.php @@ -0,0 +1,1289 @@ +cart->is_empty()) { + WC()->cart->empty_cart(); + } + $_SESSION["addOns"] = []; + $_SESSION["one-time"] = []; + return $passed; + }, 20, 3); + + + add_filter('woocommerce_checkout_fields', function ($fields) { + return $fields; + }); +}); + +// WooCommerce Fee Stuff +// first, wordpress doesn't use sessions, so let's enable those +add_action('init', function () { + if (!session_id()) { + 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. + */ +add_filter('woocommerce_apply_individual_use_coupon', 'only_one_coupon_allowed', 10, 2); +function only_one_coupon_allowed($apply, $coupon) { + // Check if a coupon is already applied + if (WC()->cart->has_discount()) { + // Remove other applied coupons except the current one + WC()->cart->empty_discounts(); + WC()->cart->apply_coupon($coupon->get_code()); + return false; // Do not apply the new 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 + if (strpos($error, 'Coupon code already applied!') !== false) { + return ''; // Return an empty string to suppress this specific error message + } + return $error; // Return the original error message if it's not related to coupons +} + + +add_action('woocommerce_cart_calculate_fees', 'add_setup_fees'); + +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 + } + + // Loop through each applied coupon + foreach ($cart->get_applied_coupons() as $coupon_code) { + // Get the coupon object + $coupon = new WC_Coupon($coupon_code); + + // 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')); + + } +} + +/** + * Generates a cart summary based on your current state + * + * @return string + */ +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; + } + $product = site()->getPost($cartItem["product_id"], [ + "title", + "thumbnail", + "acf.activation_fee", + "acf.fee_type", + "meta._regular_price", + "shipCoupon", + "shipCouponName", + "defaultShipping", + "shippingName", + "couponList", + "couponTotal", + "activationFeeName", + "activationFeeAmount", + ]); + + // starting aggrigate costs + $coupon = WC()->cart->applied_coupons; + + $productMonthly = $product["_regular_price"]; + $oneTimeCostsFee = $product["activation_fee"]; // AKA Setup fee + $activationFeeName = $product["fee_type"]; + $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; + } + } + +// Get all coupons +$coupons = get_posts(array( + 'post_type' => 'shop_coupon', + 'posts_per_page' => -1, + 'post_status' => 'publish', +)); + +// 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'; + } + } + + $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'; + } + + $cart = WC()->cart; + $cart_contents = $cart->get_cart(); + + foreach ($cart_contents as $cart_item_key => $cart_item): + endforeach; + + $variable_price = $cart_item['data']->get_regular_price(); + + $fees = WC()->cart->get_fees(); + $attributeRatePlan = $cart_item['variation']['attribute_rate-plan']; + $keylb = $_SESSION["addOns"]["Key Lockbox"]; + + +// Separate add-ons +$fallDetection = array_filter($_SESSION["addOns"], function($item) { + return $item["label"] === "Fall Detection"; +}); + +$protectionPlan = array_filter($_SESSION["addOns"], function($item) { + return $item["label"] === "Protection Plan"; +}); + +$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"])) { + + 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; + + } 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; + } + } + +// 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); +} + +$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'}; +} + +$proinstall_label = $_SESSION["one-time"]["Professional Install"]["label"]; +$fees = WC()->cart->get_fees(); + +$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; + } + + if (in_array(56, $coupon_categories)) { + $is_fiveoff_applied = true; + } +} + +if ($is_sixforsix_applied || $is_fiveoff_applied) { + $coupon_amount = $coupon->amount; +} + +$cart_items = WC()->cart->get_cart(); + + 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); + } + } +} + +add_action('woocommerce_before_calculate_totals', 'update_cart_prices'); + +function get_title_shipping_method_from_method_id( $method_rate_id = '' ){ + if( ! empty( $method_rate_id ) ){ + $method_key_id = str_replace( ':', '_', $method_rate_id ); + $option_name = 'woocommerce_'.$method_key_id.'_settings'; + return get_option( $option_name, true )['title']; + } else { + return false; + } +} +function add_administration_fees() { + WC()->cart->add_fee( 'Processing Fee', 2.5 ); +} + +/** + * custom woocommerce order fields + */ +$additionalWooFields = [ + "subscriber_first_name" => [ + "type" => "text", + "label" => "", + "placeholder" => "First Name", + "required" => true, + ], + "subscriber_last_name" => [ + "type" => "text", + "label" => "", + "placeholder" => "Last Name", + "required" => true, + ], + "subscriber_address_1" => [ + "type" => "text", + "label" => "", + "placeholder" => "Address 1", + "required" => true, + ], + "subscriber_address_2" => [ + "type" => "text", + "label" => "", + "placeholder" => "Address 2 (Apt, Suite, etc.)", + ], + "subscriber_zip" => [ + "type" => "text", + "label" => "", + "placeholder" => "Zip Code", + "required" => true, + ], + "subscriber_city" => [ + "type" => "text", + "label" => "", + "placeholder" => "City", + "required" => true, + ], + "subscriber_state" => [ + "type" => "text", + "label" => "", + "placeholder" => "State", + "required" => true, + ], + "subscriber_email" => [ + "type" => "text", + "label" => "", + "placeholder" => "Email Address", + ], + "subscriber_phone" => [ + "type" => "text", + "label" => "", + "placeholder" => "Phone Number", + ], + "caregiver_relation" => [ + "type" => "select", + "label" => "Relation", + "options" => [ + "Brother" => "Brother", + "Daughter" => "Daughter", + "Father" => "Father", + "Friend" => "Friend", + "Granddaughter" => "Granddaughter", + "Grandson" => "Grandson", + "In-law" => "In-law", + "Mother" => "Mother", + "Neighbor" => "Neighbor", + "Relative" => "Relative", + "Sister" => "Sister", + "Son" => "Son", + "Spouse" => "Spouse", + "Other" => "Other", + ], + "required" => true, + ], + "caregiver_first_name" => [ + "type" => "text", + "label" => "", + "placeholder" => "First Name", + "required" => true, + ], + "caregiver_last_name" => [ + "type" => "text", + "label" => "", + "placeholder" => "Last Name", + "required" => true, + ], + "caregiver_email" => [ + "type" => "text", + "label" => "", + "placeholder" => "Email Address", + ], + "caregiver_phone" => [ + "type" => "text", + "label" => "", + "placeholder" => "Phone Number", + ], + "card_number" => [ + "type" => "number", + "label" => "Credit Card", + "required" => true, + ], + "ccv" => [ + "type" => "number", + "label" => "CCV", + "required" => true, + ], + "expiration_month" => [ + "type" => "number", + "label" => "Expiration Month", + "required" => true, + "attrs" => ["min" => 1, "max" => 12, "step" => 1] + ], + "expiration_year" => [ + "type" => "number", + "label" => "Expiration Year", + "required" => true, + "attrs" => ["min" => 2022, "max" => 2032, "step" => 1] + ], + "SESSpromoid" => [ + "type" => "hidden", + "label" => "Promotion ID", + ], + "SESSpromotion_description" => [ + "type" => "hidden", + "label" => "Promotion Description", + ], + "SESScoupon_code" => [ + "type" => "hidden", + "label" => "Coupon Code", + ], +]; + +add_action('woocommerce_before_checkout_billing_form', function ($checkout) use ($additionalWooFields) { + $dto = []; + foreach ($additionalWooFields as $key => $field) { + ob_start(); + $customAttributes = ["v-model" => $key]; + if ($field["attrs"]) { + $customAttributes = array_merge($customAttributes, $field["attrs"]); + } + woocommerce_form_field($key, [ + 'type' => $field["type"], + 'class' => $field["classes"] ?? ['my-field-class orm-row-wide'], + 'input_class' => $field["input_classes"] ?? [], + 'label_class' => $field["label_classes"] ?? [], + 'label' => $field["label"] ?? $key, + 'required' => $field["placeholder"] ?? false, + 'placeholder' => $field["placeholder"] ?? "", + 'options' => $field["options"] ?? [], + 'custom_attributes' => $customAttributes, + ], $checkout->get_value($key)); + $fieldHTML = ob_get_contents(); + ob_end_clean(); + + $dto[$key] = $fieldHTML; + } + + echo site()->render("checkout-step-1", $dto); +}); + +function showCardFields() +{ + global $additionalWooFields; + $dto = []; + foreach ($additionalWooFields as $key => $field) { + if (!in_array($key, ["card_number", "ccv", "expiration_month", "expiration_year"])) { + continue; + } + ob_start(); + $customAttributes = ["v-model" => $key]; + if ($field["attrs"]) { + $customAttributes = array_merge($customAttributes, $field["attrs"]); + } + woocommerce_form_field($key, [ + 'type' => $field["type"], + 'class' => $field["classes"] ?? ['my-field-class orm-row-wide'], + 'input_class' => $field["input_classes"] ?? [], + 'label_class' => $field["label_classes"] ?? [], + 'label' => $field["label"] ?? $key, + 'required' => $field["placeholder"] ?? false, + 'placeholder' => $field["placeholder"] ?? "", + 'options' => $field["options"] ?? [], + 'custom_attributes' => $customAttributes, + ], null); + $fieldHTML = ob_get_contents(); + ob_end_clean(); + + $dto[$key] = $fieldHTML; + } + echo site()->render("card-fields", $dto); +} + +add_action('woocommerce_checkout_update_order_meta', function ($orderID) use ($additionalWooFields) { + foreach ($additionalWooFields as $key => $field) { + if (isset($_POST[$key])) { + $value = esc_attr($_POST[$key]); + if ($key === "card_number") { + $parts = str_split($value); + $output = ""; + for ($i = 0; $i < count($parts); $i++) { + if ($i < count($parts) - 4) { + $output .= "*"; + } else { + $output .= $parts[$i]; + } + } + $value = $output; + } + update_post_meta($orderID, $key, $value); + } + } +}); + +add_action('woocommerce_admin_order_data_after_shipping_address', function ($order) use ($additionalWooFields) { + $dto = [ + "subscriber-data" => [], + "caregiver-data" => [], + ]; + foreach ($additionalWooFields as $key => $field) { + $meta = get_post_meta($order->get_id(), $key, true); + $dataType = (substr($key, 0, 10) === "subscriber") ? "subscriber-data" : "caregiver-data"; + $dto[$dataType][] = [ + "label" => $field["label"] ? $field["label"] : $field["placeholder"], + "value" => $meta ?: "", + ]; + } + 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' ); + +/** + * Update order emails to include all the extra stuff + */ +add_filter('woocommerce_email_order_meta_fields', function ($fields, $sent_to_admin, $order) use ($additionalWooFields) { + foreach ($additionalWooFields as $key => $value) { + $fields[$key] = [ + 'label' => strlen($value["label"]) ? $value["label"] : $value["placeholder"], + 'value' => get_post_meta($order->get_id(), $key, true), + ]; + } + + if (count($order->get_coupon_codes())) { + $fields["applied_coupons"] = [ + "label" => "Applied Coupons", + "value" => implode(", ", $order->get_coupon_codes()), + ]; + } + return $fields; +}, 10, 3); + +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'])) { + $card_number = sanitize_text_field($_POST['card_number']); + update_post_meta($order_id, '_card_number', $card_number); + + $card_type = detect_card_type($card_number); + if ($card_type) { + update_post_meta($order_id, '_card_type', $card_type); + } + } + + if (isset($_POST['expiration_month']) && !empty($_POST['expiration_month'])) { + $expiration_month = sanitize_text_field($_POST['expiration_month']); + update_post_meta($order_id, '_expiration_month', $expiration_month); + } + + if (isset($_POST['expiration_year']) && !empty($_POST['expiration_year'])) { + $expiration_year = sanitize_text_field($_POST['expiration_year']); + update_post_meta($order_id, '_expiration_year', $expiration_year); + } +} + +/** + * Function to detect card type based on the card number. + */ +function detect_card_type($number) { + $number = preg_replace('/\D/', '', $number); + $patterns = [ + 'Visa' => '/^4[0-9]{12}(?:[0-9]{3})?$/', + 'MasterCard' => '/^5[1-5][0-9]{14}$/', + 'American Express' => '/^3[47][0-9]{13}$/', + 'Discover' => '/^6(?:011|5[0-9]{2})[0-9]{12}$/' + ]; + + foreach ($patterns as $type => $pattern) { + if (preg_match($pattern, $number)) { + return $type; + } + } + + return null; +} + +add_action('woocommerce_thankyou', function ($order_id) { + $card_number = get_post_meta($order_id, '_card_number', true); + //error_log("Card Number: " . $card_number); + $order = wc_get_order($order_id); + + $order_data = []; + foreach ($order->get_items() as $item) { + $item_data = $item->get_data(); + $formatted_meta_data = $item->get_formatted_meta_data('_', true); + $order_data['items'][] = [ + 'name' => $item->get_name(), + 'product_id' => $item->get_product_id(), + 'quantity' => $item->get_quantity(), + 'subtotal' => $item->get_subtotal(), + 'total' => $item->get_total(), + ]; + } + + $order_products = []; + foreach ($order->get_items() as $item) { + $product = $item->get_product(); + $product_id = $product->get_id(); + $product_sku = $product->get_sku(); + $quantity = $item->get_quantity(); + + $rate_plan_id = null; + $attributes = []; + + + 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']); + // Get Rate Plan ID custom field for the variation + $rate_plan_id = get_post_meta($product_id, 'rate_plan_id', true); // Adjust if needed + + $variation_label = implode(', ', $attributes); + } else { + // For non-variation products, still fetch Rate Plan ID if it exists + $rate_plan_id = get_post_meta($product_id, 'rate_plan_id', true); + } + } + + $fees_total = 0; + foreach ($order->get_fees() as $fees) { + $order_data['fees'][] = [ + 'name' => $fees->get_name(), + 'amount' => $fees->get_amount(), + ]; + $fees_total += $fees->get_amount(); + } + + foreach ($order->get_coupon_codes() as $coupon_code) { + $coupon = new WC_Coupon($coupon_code); + $order_data['coupons'][] = [ + 'code' => $coupon_code, + 'discount_amount' => $coupon->get_amount(), + 'remaining_usage' => ($coupon->get_usage_limit_per_user() - $coupon->get_usage_count()) + ]; + } + + // Shipping and Coupon Amount Calculation + if ($order->get_shipping_total() == 0) { + $shipping_label = 'Free Shipping'; + $shipping_cost = 0; + } else { + $shipping_label = 'Shipping'; + $shipping_cost = $order->get_shipping_total(); + } + + $order_data['shipping'] = [ + 'label' => $shipping_label, + 'cost' => $shipping_cost + ]; + + // Total and Subtotal Data + $order_total = (float)$order->get_total(); + $order_subtotal = (float)$order->get_subtotal(); + $coupon_total = (float)$order->get_discount_total(); + + $order_data['totals'] = [ + 'subtotal' => $order_subtotal, + 'total' => $order_total, + 'discount' => $coupon_total + ]; + + // Send the order data to Salesforce with encryption + $request_payload = createOrderRequest($order, $card_number); + + // Create a new instance of the SalesforceSync class and send the request + $sf = new SalesforceSync(SalesforceSync::kACTION_ORDER_CREATE, $request_payload); + // Send the request and log the response + $response = $sf->sendRequest(); + + // Log the raw response from Salesforce for debugging + //error_log('Salesforce Response (Raw): ' . print_r($response, true)); + + // Decode the response (assuming it is double-encoded JSON) + $decoded_response = json_decode(json_decode($response)); + + // Check if there are errors in the decoded response and log them + if (isset($decoded_response->ErrorList)) { + $error_response = serialize($decoded_response->ErrorList); + //error_log('Salesforce API Error: ' . $error_response); + } else { + // Log the successful response if no errors are present + //error_log('Salesforce Response (Decoded): ' . print_r($decoded_response, true)); + } + + // Render the order details on the thank-you page + echo site()->render("thank-you-order-details", [ + "setupFeePrice" => $fees_total, + "setupFeeName" => isset($order_data['fees'][0]['name']) ? $order_data['fees'][0]['name'] : '', + "couponCode" => isset($order_data['coupons'][0]['code']) ? $order_data['coupons'][0]['code'] : '', + "couponAmount" => $coupon_total, + "monthlyFee" => $order_subtotal, + "shippingLabel" => $shipping_label, + "shippingCost" => $shipping_cost, + "freeshippingCost" => ($shipping_cost == 0) ? 'Free' : '', + "items" => array_map(function ($i) { + return [ + "name" => $i['name'], + "image" => wc_get_product($i['product_id'])->get_image([100, 100]), // Get product image + ]; + }, $order_data['items']), + "total" => $order_total, + "fees" => $order_data['fees'] + ]); +}); + + +/** + * Retrieve accessories data for a product. + */ +function getProductAccessories($product_id) { + $accessories = get_field('accessories', $product_id); + $formatted_accessories = []; + + if (!empty($accessories)) { + foreach ($accessories as $accessory) { + $formatted_accessories[] = [ + "AccessoryID" => $accessory['salesforce_id'], + "Quantity" => 1, + "Price" => $accessory['price'] + ]; + } + } + + return $formatted_accessories; +} + +/** + * Creates the payload for the order to send to Salesforce. + */ +function createOrderRequest($order) { + // Retrieve card type from order meta + $card_type = get_post_meta($order->get_id(), '_card_type', true); + + // Retrieve other payment information from the order if needed + $card_number = get_post_meta($order->get_id(), '_card_number', true); + $expiration_month = get_post_meta($order->get_id(), '_expiration_month', true); + $expiration_year = get_post_meta($order->get_id(), '_expiration_year', true); + + // Create the expiration date in the required format (e.g., "MM/YYYY") + $expiration_date = sprintf('%02d/%s', $expiration_month, $expiration_year); + + // Generate the request header + $header = createRequestHeader(); + + // Get billing and shipping information from the order + $billing = $order->get_address('billing'); + $shipping = $order->get_address('shipping'); + $payment_type = "Credit Card"; // Assuming credit card + + // Format phone number (example: XXX-XXX-XXXX) + $billing_phone = preg_replace('/(\d{3})(\d{3})(\d{4})/', '$1-$2-$3', $billing['phone']); + $shipping_phone = !empty($shipping['phone']) ? preg_replace('/(\d{3})(\d{3})(\d{4})/', '$1-$2-$3', $shipping['phone']) : $billing_phone; + + // Prepare product items and accessories + $order_products = []; + foreach ($order->get_items() as $item) { + $product = $item->get_product(); // Get the WC_Product object + $product_id = $product->get_id(); + $product_sku = $product->get_sku(); + $quantity = $item->get_quantity(); + + $rate_plan_id = null; + $attributes = []; + + $parent_id = $product->get_parent_id(); // Get the parent variable product ID + $attributes = $product->get_attributes(); // Get variation attributes + + // Get Rate Plan ID custom field for the variation + $rate_plan_id = get_post_meta($product_id, 'rate_plan_id', true); + + // Include additional variation details + $variation_label = implode(', ', $attributes); + + // Fetch accessories related to this product + $accessories = getProductAccessories($item->get_product_id()); + + //error_log( print_r($accessories, true) ); + // Add variation or product details to the order products array + $order_products[] = [ + 'ProductID' => $product_sku, + 'Quantity' => $item->get_quantity(), + 'RatePlanID' => $attributes['rate-plan-sfid'], + 'Accessories' => $accessories, + 'PromotionID' => $promotion_id + ]; + } + + // Create the payload structure + $orderRequest = [ + "RequestHeader" => $header, + "RequestBody" => [ + "CustomerFirstName" => $billing['first_name'], + "CustomerLastName" => $billing['last_name'], + "CustomerEmail" => $billing['email'], + "CustomerPhoneNumber" => $billing_phone, + "GCLID" => "", + "UserExperience" => null, + "CustomField1" => "", + "CustomField2" => "", + "CustomField3" => "", + "CustomField4" => "", + "MarketingCampaign" => "ecom campaign", + "ShippingID" => "a4t3s000000pYVVAA2", + "PaymentInformation" => [ + "PaymentType" => $payment_type, + "CardholderName" => $billing['first_name'] . ' ' . $billing['last_name'], + "CardType" => $card_type, + "CardNumber" => $card_number, + "ExpirationDate" => $expiration_date + ], + "ShippingInformation" => [ + "FirstName" => $shipping['first_name'], + "LastName" => $shipping['last_name'], + "Phone" => $shipping_phone, + "Street1" => $shipping['address_1'], + "Street2" => $shipping['address_2'], + "City" => $shipping['city'], + "State" => $shipping['state'], + "PostalCode" => $shipping['postcode'], + "Country" => $shipping['country'] == 'US' ? 'United States' : $shipping['country'] + ], + "BillingInformation" => [ + "FirstName" => $billing['first_name'], + "LastName" => $billing['last_name'], + "Phone" => $billing_phone, + "Street1" => $billing['address_1'], + "Street2" => $billing['address_2'], + "City" => $billing['city'], + "State" => $billing['state'], + "PostalCode" => $billing['postcode'], + "Country" => $billing['country'] == 'US' ? 'United States' : $billing['country'] + ], + "OrderProducts" => $order_products + ], + ]; + + return $orderRequest; +} + +/** + * Creates a request header with a unique ID. + */ +function createRequestHeader() { + return [ + "RequestID" => "Request_" . microtime(true) + ]; +} + +if (!class_exists("SalesforceSync")) { + class SalesforceSync { + + const kACTION_ORDER_CREATE = "CreateOrder"; + const kAPPEND_URL = "?brand=MedicalAlert"; + + private $url; + private $content; + private $method; + + public function __construct($action, $content, $method = "POST") { + // Appending ?brand=MedicalAlert to the URL + $environment_url = get_option('id_api_salesforce', true); + $this->url = "{$environment_url}/{$action}" . self::kAPPEND_URL; + $this->content = $content; + $this->method = $method; + } + + public function sendRequest() { + $crypto = new SecuredContent(); + $encoded_content = json_encode($crypto->encode_content(json_encode($this->content))); + + $request = curl_init($this->url); + curl_setopt($request, CURLOPT_CUSTOMREQUEST, $this->method); + curl_setopt($request, CURLOPT_RETURNTRANSFER, true); + curl_setopt($request, CURLOPT_POSTFIELDS, $encoded_content); + curl_setopt($request, CURLOPT_HTTPHEADER, [ + 'Content-Type: application/json', + 'Content-Length: ' . strlen($encoded_content), + ]); + + // Execute the request and retrieve the response + $response = curl_exec($request); + curl_close($request); + + // Decode the encrypted response + return $crypto->decode_content($response); + } + + } +} + +// Ensure only one item in the cart +add_filter('woocommerce_add_cart_item_data', 'restrict_cart_to_one_item', 10, 3); +function restrict_cart_to_one_item($cart_item_data, $product_id, $variation_id) { + global $woocommerce; + if (!$woocommerce->cart->is_empty()) { + unset($_SESSION["one-time"]); + unset($_SESSION["addOns"]); + $woocommerce->cart->empty_cart(); + } + + return $cart_item_data; +} +add_filter('woocommerce_checkout_fields', 'customize_billing_fields'); + +function customize_billing_fields($fields) { + unset($fields['billing']['billing_company']); + $fields['billing']['billing_first_name']['label'] = ''; + $fields['billing']['billing_last_name']['label'] = ''; + $fields['billing']['billing_address_1']['label'] = ''; + $fields['billing']['billing_address_2']['label'] = ''; + $fields['billing']['billing_city']['label'] = ''; + $fields['billing']['billing_postcode']['label'] = ''; + $fields['billing']['billing_phone']['label'] = ''; + $fields['billing']['billing_email']['label'] = ''; + $fields['billing']['billing_state']['label'] = ''; + $fields['billing']['billing_state']['placeholder'] = 'Select Your State'; + $fields['billing']['billing_first_name']['placeholder'] = __('First Name', 'woocommerce'); + $fields['billing']['billing_last_name']['placeholder'] = __('Last Name', 'woocommerce'); + $fields['billing']['billing_address_1']['placeholder'] = __('Street address', 'woocommerce'); + $fields['billing']['billing_address_2']['placeholder'] = __('Apartment, suite, unit etc. (optional)', 'woocommerce'); + $fields['billing']['billing_city']['placeholder'] = __('City', 'woocommerce'); + $fields['billing']['billing_postcode']['placeholder'] = __('Postcode / ZIP', 'woocommerce'); + $fields['billing']['billing_phone']['placeholder'] = __('Phone', 'woocommerce'); + $fields['billing']['billing_email']['placeholder'] = __('Email address', 'woocommerce'); + + return $fields; +} + + +add_action('woocommerce_init', 'woocommerce_shipping_instances_form_fields_filters'); +function woocommerce_shipping_instances_form_fields_filters(){ + foreach( WC()->shipping->get_shipping_methods() as $shipping_method ) { + add_filter('woocommerce_shipping_instance_form_fields_' . $shipping_method->id, 'shipping_methods_additional_custom_field'); + } +} + +function shipping_methods_additional_custom_field( $settings ) { + $settings['shipping_comment'] = array( + 'title' => __('Salesforce ID', 'woocommerce'), + 'type' => 'text', + 'placeholder' => __( 'Enter any additional comments for this shipping method.', 'woocommerce' ), + ); + return $settings; +} + +add_action( 'wp_footer', 'refresh_cart'); + +function refresh_cart() { ?> + + + +cart->get_applied_coupons())) { + return; + } + + WC()->cart->apply_coupon($couponcode); + } +}); \ No newline at end of file