'Forbidden',
'code' => $code,
),
403
);
}
add_action('wp_ajax_bloyal_front_nonce', 'bloyal_send_front_nonce');
add_action('wp_ajax_nopriv_bloyal_front_nonce', 'bloyal_send_front_nonce');
/**
* Hands the storefront its AJAX nonce. Kept out of the page HTML so that a
* full-page cache can never serve one visitor's nonce to another, and answered
* over POST so no intermediary cache stores it either.
*
* @return void
*/
function bloyal_send_front_nonce()
{
$nonce = wp_create_nonce('bloyal_front');
bloyal_set_front_nonce_cookie($nonce);
nocache_headers();
header('Vary: Cookie', false);
wp_send_json_success(array('nonce' => $nonce));
}
/**
* Store the storefront AJAX nonce in a JS-readable cookie, so the common case
* costs no extra request. Only sent when the browser has no usable nonce yet:
* an unconditional Set-Cookie stops some reverse proxies from caching the page.
*
* @param string|null $nonce Nonce value, or null to create one.
* @return void
*/
function bloyal_set_front_nonce_cookie($nonce = null)
{
if (headers_sent()) {
return;
}
// Only 1 means "issued in the current tick". A nonce from the previous tick
// still verifies but is on its way out, so it gets replaced here rather than
// left to expire on the visitor.
if (isset($_COOKIE['bloyal_front_n']) && 1 === wp_verify_nonce($_COOKIE['bloyal_front_n'], 'bloyal_front')) {
return;
}
if (null === $nonce) {
$nonce = wp_create_nonce('bloyal_front');
}
$path = (defined('COOKIEPATH') && COOKIEPATH) ? COOKIEPATH : '/';
$domain = (defined('COOKIE_DOMAIN') && COOKIE_DOMAIN) ? COOKIE_DOMAIN : '';
setcookie('bloyal_front_n', $nonce, time() + (10 * HOUR_IN_SECONDS), $path, $domain, is_ssl(), false);
}
add_action('send_headers', 'bloyal_send_front_nonce_cookie');
function bloyal_send_front_nonce_cookie()
{
if (is_admin()) {
return;
}
bloyal_set_front_nonce_cookie();
}
$bloyal_obj = new BloyalController();
$payment_alert_obj = new BLOYAL_PaymentAlertController();
register_activation_hook(__FILE__, 'bloyal_activation');
function bloyal_activation()
{
try {
if (! is_plugin_active('woocommerce/woocommerce.php') && current_user_can('activate_plugins')) {
wp_die(esc_html('This plugin requires the WooCommerce Plugin to be installed and active.
« Return to Plugins'));
}
update_option('loyalty_block', 'true');
update_option('bloyal_click_and_collect_status', '2');
update_option('bloyal_apply_full_balance_loyalty', 'false');
update_option('bloyal_apply_full_balance_giftcard', 'false');
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
register_deactivation_hook(__FILE__, 'bloyal_deactivation');
function bloyal_deactivation() {}
register_uninstall_hook(__FILE__, 'bloyal_uninstall');
function bloyal_uninstall()
{
try {
// CON-111: preserve the device connection (credentials + service URLs + device id)
// and the tender mapping on uninstall. A delete+reinstall is a common way to "update"
// the hand-distributed ZIP, and it must not force a reconnect or wipe tender mappings.
// The following options are intentionally NOT deleted:
// bloyal_access_key, bloyal_access_key_verification, bloyal_domain_url,
// bloyal_custom_grid_api_url, bloyal_custom_loyaltyengine_api_url,
// bloyal_custom_orderengine_api_url, bloyal_custompayment_api_url,
// bloyal_custom_logging_api_url, is_bloyal_custom_api_url, Device_Code,
// bloyal_tender_payments_mapping
// Caches and non-essential settings below are still cleaned up on uninstall.
delete_option('loyalty_block');
delete_option('bloyal_click_and_collect_status');
delete_option('bloyal_apply_full_balance_loyalty');
delete_option('bloyal_apply_full_balance_giftcard');
delete_option('bloyal_Tenders');
delete_option('bloyal_ShippingCarriers');
delete_option('bloyal_apply_in_increment_of_giftcard');
delete_option('bloyal_apply_in_increment_of_loyalty');
delete_option('bloyal_log_enable_disable');
delete_option('bloyal_snippet_code');
delete_option('bloyal_snippet_informational_code');
delete_option('bloyal_snippet_confirmation_code');
delete_option('bloyal_snippet_problem_code');
delete_option('bloyal_on_account_tender_code');
delete_option('bloyal_snippets_codes');
delete_option('bloyal_saved_device_snippets_lists');
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
add_filter('woocommerce_default_address_fields', 'bloyal_wdm_override_default_address_fields');
function bloyal_wdm_override_default_address_fields($address_fields)
{
try {
$query_string = null;
if (isset($_SERVER['QUERY_STRING'])) {
$query_string = sanitize_text_field(wp_unslash($_SERVER['QUERY_STRING']));
}
if (! (is_checkout() && ! $query_string)) {
return $address_fields;
} else {
$isDisplayDOB = get_option('bloyal_display_DOB');
$isRequiredDOB = get_option('bloyal_required_DOB');
if (empty($isDisplayDOB) || false == $isDisplayDOB) {
bLoyalLoggerService::write_custom_log("\r\n ========== bloyal_display_DOB ============\r\n" . $isDisplayDOB);
}
if ('true' == $isDisplayDOB) {
$address_fields = bloyal_add_birth_date_address_field($address_fields, $isRequiredDOB);
}
return $address_fields;
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
function bloyal_add_birth_date_address_field($address_fields, $isRequiredDOB)
{
try {
if (empty($isRequiredDOB) || false == $isRequiredDOB) {
bLoyalLoggerService::write_custom_log("\r\n ========== bloyal_required_DOB ============\r\n" . $isRequiredDOB);
}
$user_id = get_current_user_id();
if (! empty($user_id)) {
$user_birth_date = get_user_meta($user_id, 'birth_date', true);
} else {
$user_birth_date = WC()->session->get('guest_user_birth_date');
}
$address_fields['birth_date'] = array(
'label' => __('Birth Date', 'woocommerce'),
'required' => 'true' == $isRequiredDOB ? true : false,
'class' => array('form-row-wide'),
'type' => 'date',
'placeholder' => 'MM/DD/YYYY',
'priority' => 100,
'default' => $user_birth_date,
);
return $address_fields;
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_action('show_user_profile', 'bloyal_extra_user_profile_fields');
add_action('edit_user_profile', 'bloyal_extra_user_profile_fields');
function bloyal_extra_user_profile_fields($user)
{
?>
|
|
";
// print_r(WC()->session);
WC()->session->set(
'bloyal_uid',
array(
'u_id' => $u_id,
'session_id' => $woo_session_id,
)
);
}
// Also save cart_uid early for persistence (even if bloyal_uid session is lost later)
if (!empty($u_id) && WC()->session) {
WC()->session->set('bloyal_early_cart_uid', $u_id);
bLoyalLoggerService::write_custom_log("\r\n ==========Saved cart_uid early from CalculateCart response============\r\n" . "Cart UID: " . bloyal_mask_cart_uid_for_log($u_id) . "\r\n---------------\r\n", 1);
}
$obj_alert = new BLOYAL_AlertPopUpController();
$bloyalAlerts = $bloyal_cart_object->data->LoyaltySummary->Alerts;
WC()->session->set('bloyal_cart_alerts_data', $bloyalAlerts);
$obj_alert->process_alert_data($bloyalAlerts, 'true');
$objectPromotionController->add_promotions($cart_object, $bloyal_cart_object);
$discount = $bloyal_cart_object->data->Cart->Shipments[0]->Discount;
$cost = $bloyal_cart_object->data->Cart->Shipments[0]->Charge;
if ($discount && $external) {
WC()->session->set('bloyal_shipping_cart_data', $bloyal_cart_object->data->Cart->Shipments);
} else {
WC()->session->set('bloyal_shipping_cart_data', null);
}
if ($activeMethod) {
$woo_session_id = WC()->session->get_customer_id();
$final_price = $cost - $discount;
if ($final_price < 0) {
$final_price = 0;
}
WC()->session->set(
'bloyal_shipping_rate_cost',
array(
'rate_id' => $activeMethod,
'cost' => $cost,
'final_price' => $final_price,
'session_id' => $woo_session_id,
'discount' => $discount,
'external' => $external,
)
);
if ('false' == $is_bloyal_applied_taxes) {
$objectShippingController->change_wooc_shipping_tax_amount(
array(
'shipping_discount' => $discount,
'shipping_original_cost' => $cost,
)
);
}
add_filter('woocommerce_shipping_rate_cost', 'bloyal_change_shiping_rate_cost', 10, 2);
add_filter('woocommerce_shipping_rate_label', 'bloyal_change_shiping_rate_label', 10, 2);
} else {
WC()->session->set('bloyal_shipping_rate_cost', null);
}
if ('false' != $is_bloyal_applied_taxes) {
$objectCustomTaxController = new CustomTaxClassController();
$objectCustomTaxController->calculate_and_apply_custom_tax($cart_object, $bloyal_cart_object);
}
bLoyal_add_to_cart_custom_line_item($bloyal_cart_object->data->Cart->Lines, $cart_object);
}
if (isset($bloyal_cart_object->status) && ('error' == $bloyal_cart_object->status)) {
$msg = $bloyal_cart_object->message;
wc_clear_notices();
if (! wc_has_notice($msg, 'error') && 'wc-ajax=checkout' == $_SERVER['QUERY_STRING']) {
wc_add_notice($msg, 'error');
}
}
WC()->session->set('bloyal_calculated', true);
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
function bloyal_change_shiping_rate_cost($cost, $rate)
{
try {
$bloyal_obj = new BloyalController();
$bloyalSession = $bloyal_obj->getSessionData();
if (! empty($bloyalSession)) {
$rate_id = isset($bloyalSession['rate_id']) ? $bloyalSession['rate_id'] : '';
$final_price = isset($bloyalSession['final_price']) ? $bloyalSession['final_price'] : '0';
$discount = isset($bloyalSession['discount']) ? $bloyalSession['discount'] : '0';
if (($rate_id == $rate->id)) {
$external = isset($bloyalSession['external']) ? $bloyalSession['external'] : '';
if ($external) {
$bloyalSession['cost'] = $cost;
WC()->session->set('bloyal_shipping_rate_cost', $bloyalSession);
$final_price = $cost - $discount;
if ($final_price < 0) {
$final_price = 0;
}
} elseif ( ! $final_price && $cost > 0 && empty( $discount ) ) {
// CON-78: Charge:0 is a timing artefact (cart cleared by prior order), not free shipping.
bLoyalLoggerService::write_custom_log(
"\r\n [CON-78] Shipping guard: bLoyal Charge=0, no discount, WC rate cost={$cost} — keeping WC cost.",
2
);
return $cost;
}
return $final_price > 0 ? $final_price : 0;
}
}
return $cost;
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
function bloyal_change_shiping_rate_label($label, $rate)
{
try {
$bloyal_obj = new BloyalController();
$cost = $rate->cost;
$bloyalSession = $bloyal_obj->getSessionData();
if (! empty($bloyalSession)) {
$label = bloyal_set_rate_label($bloyalSession, $label, $rate, $cost);
}
return $label;
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
add_filter('woocommerce_cart_shipping_method_full_label', 'bloyal_add_free_shipping_label', 10, 2);
function bloyal_add_free_shipping_label($label, $method)
{
if (0 == $method->cost && ! (strpos($label, ': $0.00'))) {
$label .= ': $0.00';
}
return $label;
}
function bloyal_set_rate_label($bloyalSession, $label, $rate, $cost)
{
$rate_id = isset($bloyalSession['rate_id']) ? $bloyalSession['rate_id'] : '';
$charge = isset($bloyalSession['cost']) ? $bloyalSession['cost'] : '';
$discount = isset($bloyalSession['discount']) ? $bloyalSession['discount'] : '';
$final_price = isset($bloyalSession['final_price']) ? $bloyalSession['final_price'] : '';
if (($rate_id == $rate->id)) {
$label = bloyal_update_label_price($label, $cost, $charge, $final_price);
}
return $label;
}
add_action('woocommerce_cart_calculate_fees', 'bloyal_apply_split_tenders_to_cart');
function bloyal_apply_split_tenders_to_cart()
{
global $woocommerce;
if (is_admin() && ! defined('DOING_AJAX')) {
return;
}
$gift_card_amount = WC()->session->get('partial_gift_amount');
if ((is_float($gift_card_amount)) && ($gift_card_amount > 0) && (! is_null($gift_card_amount))) {
$woocommerce->cart->add_fee('Gift Card', -$gift_card_amount, false);
add_filter('woocommerce_cart_totals_get_fees_from_cart_taxes', 'bloyal_exlude_cart_fees_taxes', 10, 3);
add_filter('woocommerce_available_payment_gateways', 'bloyal_unset_gift_card_method', 1);
}
$loyalty_dollar_amount = WC()->session->get('partial_loyalty_amount');
if ((is_float($loyalty_dollar_amount)) && ($loyalty_dollar_amount > 0) && (! is_null($loyalty_dollar_amount))) {
$woocommerce->cart->add_fee('Loyalty Dollars', -$loyalty_dollar_amount, false);
add_filter('woocommerce_cart_totals_get_fees_from_cart_taxes', 'bloyal_exlude_cart_fees_taxes', 10, 3);
add_filter('woocommerce_available_payment_gateways', 'bloyal_unset_loyalty_method', 1);
}
}
function bloyal_unset_gift_card_method($gateways)
{
unset($gateways['bloyal_gift_card']);
return $gateways;
}
function bloyal_unset_loyalty_method($gateways)
{
unset($gateways['bloyal_loyalty_dollar']);
return $gateways;
}
function bloyal_exlude_cart_fees_taxes($taxes, $fee, $cart)
{
return array();
}
function bloyal_update_label_price($label, $cost, $charge, $final_price)
{
if ($cost != $charge) {
if ($final_price) {
$label .= ' $' . $charge . '';
} else {
// $label .= ' $' . $charge . ': $0.00';
}
} elseif (! $cost) {
$is_free = strcasecmp($label, 'Free Shipping');
if ($is_free) {
// $label .= ' $' . $charge . ': $0.00';
$label .= '';
}
}
return $label;
}
add_filter('woocommerce_product_needs_shipping', 'bloyal_wvp_no_shipping', 10, 2);
function bloyal_wvp_no_shipping($needs_shipping, $product)
{
try {
if ($product->is_virtual()) {
$needs_shipping = false;
} else {
add_filter('woocommerce_cart_needs_shipping', '__return_true');
}
return $needs_shipping;
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
add_action('init', 'bloyal_stop_heartbeat', 1);
function bloyal_stop_heartbeat()
{
wp_deregister_script('heartbeat');
}
add_action('woocommerce_order_item_add_action_buttons', 'bloyal_resubmit_order_button', 10, 1);
function bloyal_resubmit_order_button($order)
{
try {
if (is_plugin_active('woocommerce/woocommerce.php') && $order->get_status() != 'auto-draft' && get_option('bloyal_use_order_engine') == 'true') {
echo '';
echo '';
echo '';
}
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
add_action('woocommerce_before_cart', 'bloyal_custom_checkout_message', 10, 1);
add_action('woocommerce_cart_is_empty', 'bloyal_custom_checkout_message', 10, 1);
function bloyal_custom_checkout_message()
{
$bloyal_unexisted_woo_products = WC()->session->get('bloyal_unexisted_woo_products');
if (isset($bloyal_unexisted_woo_products) && ! empty($bloyal_unexisted_woo_products)) {
echo 'Following Cart Products are not present in woocommerce database.';
foreach ($bloyal_unexisted_woo_products as $product) {
$product_name = $product['product_name'];
echo '';
echo esc_attr($product['product_name']);
echo ' ';
}
echo '';
WC()->session->set('bloyal_unexisted_woo_products', null);
}
}
add_action(
'rest_api_init',
function ($server) {
$server->register_route(
'cart',
'/cart',
array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'bloyal_view_cart_in_woocommerce',
'permission_callback' => 'bloyal_cart_handoff_permission_check',
'args' => array(
'CartId' => array(
'required' => false,
'sanitize_callback' => 'sanitize_text_field',
'validate_callback' => 'bloyal_is_cart_uid',
),
'cart_uid' => array(
'required' => false,
'sanitize_callback' => 'sanitize_text_field',
'validate_callback' => 'bloyal_is_cart_uid',
),
),
)
);
}
);
/**
* Whether a value is shaped like a bLoyal CartUid (a GUID).
*
* @param mixed $value Value received on the request.
* @return bool
*/
function bloyal_is_cart_uid($value)
{
if ('' === $value || null === $value) {
return true;
}
return (bool) preg_match(
'/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/',
(string) $value
);
}
/**
* Permission check for the bLoyal cart-handoff route.
*
* The route stays reachable without authentication on purpose: it exists so a shopper can open a
* cart link minted on bLoyal's side and land on this store's checkout. What it is allowed to do is
* bounded instead - it authenticates nobody, creates no WordPress user, and changes only the
* calling visitor's own WooCommerce session. It is refused when WooCommerce has not set up a cart
* and session for this request, which is the case on /wp-json/ requests: the handler calls
* WC()->cart->empty_cart() first and would otherwise fatal on a null cart.
*
* @return true|WP_Error
*/
function bloyal_cart_handoff_permission_check()
{
if (! function_exists('WC') || ! WC()->cart || ! WC()->session) {
return new WP_Error(
'bloyal_cart_unavailable',
__('The cart is not available for this request.', 'bloyal'),
array('status' => 503)
);
}
return true;
}
function bloyal_fetch_orders_after_modified_date(WP_REST_Request $request)
{
try {
$bloyal_obj = new BloyalController();
return $bloyal_obj->bloyal_fetch_orders_after_modified_date($request);
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
function bloyal_fetch_customers_after_modified_date(WP_REST_Request $request)
{
try {
$bloyal_obj = new BloyalController();
return $bloyal_obj->bloyal_fetch_customers_after_modified_date($request);
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
function bloyal_fetch_products_by_sku(WP_REST_Request $request)
{
try {
$bloyal_obj = new BloyalController();
$param = $request['modified_date'];
$param1 = $request['sku'];
if (strlen($param)) {
return $bloyal_obj->bloyal_fetch_products_after_modified_date($request);
} else {
return $bloyal_obj->bloyal_fetch_product_by_sku($request);
}
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
function bloyal_update_products(WP_REST_Request $request)
{
try {
$bloyal_obj = new BloyalController();
return $bloyal_obj->bloyal_update_products($request);
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
function bloyal_view_cart_in_woocommerce(WP_REST_Request $request)
{
try {
$param = $request['CartId'];
if (empty($param)) {
$param = $request['cart_uid'];
}
$bloyal_obj = new BloyalController();
$bloyal_obj->bloyal_view_cart_in_woocommerce($param);
wp_redirect(wc_get_checkout_url());
exit;
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
add_action('woocommerce_order_refunded', 'bloyal_order_refunded', 10, 2);
function bloyal_order_refunded($order_id, $refund_id)
{
try {
$bloyal_obj = new BloyalController();
$result = $bloyal_obj->bloyal_order_refunded($order_id, $refund_id);
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
/**
* This function is used to apply custom coupons
*
* @param array $coupons_enabled
*
* @return array
*/
add_filter('woocommerce_coupons_enabled', 'bloyal_apply_custom_coupon_before_coupon_table', 1);
function bloyal_apply_custom_coupon_before_coupon_table($coupons_enabled)
{
try {
if (isset($_POST['coupon_code'])) {
$coupon_code = sanitize_text_field(wp_unslash($_POST['coupon_code']));
$bloyal_obj = new BloyalController();
$res = $bloyal_obj->bloyal_validate_coupon($coupon_code);
}
return $coupons_enabled;
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
// Pass the original value through: returning nothing here makes this filter
// resolve to null, which disables coupons store-wide and hides both coupon forms.
return $coupons_enabled;
}
}
/**
* This function is used to handle coupon errors
*
* @param string $err
* @param string $error_code
* @param string $coupon
*
* @return coupon message
*/
add_filter('woocommerce_coupon_error', 'bloyal_woocommerce_get_coupon_error', 10, 3);
function bloyal_woocommerce_get_coupon_error($err, $error_code, $coupon)
{
try {
// Check if this is a bLoyal coupon - suppress WooCommerce validation errors
if ( $coupon && is_object( $coupon ) && method_exists( $coupon, 'get_code' ) ) {
$coupon_code = $coupon->get_code();
$session_bloyal_coupons = WC()->session->get('bloyal_coupon');
if (!empty($session_bloyal_coupons)) {
foreach ($session_bloyal_coupons as $bloyal_coupon) {
if (isset($bloyal_coupon['coupon_code']) && strcasecmp($bloyal_coupon['coupon_code'], $coupon_code) == 0) {
// Suppress WooCommerce errors for bLoyal coupons
return false;
}
}
}
}
return 105 == $error_code ? false : $err;
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
return $err;
}
}
add_action('admin_enqueue_scripts', 'bloyal_enqueue_scripts');
/**
* Function to enqueue bloyal script.
*
* @param null
*
* @return void
*/
function bloyal_enqueue_scripts()
{
try {
wp_enqueue_script('bloyal_scripts', BLOYAL_URL . 'assets/js/bloyal.js', array('jquery'), BLOYAL_VERSION, true);
wp_localize_script(
'bloyal_scripts',
'bloyalAuth',
array(
'nonce' => wp_create_nonce('bloyal_admin'),
'actions' => bloyal_admin_ajax_actions(),
)
);
wp_register_style('bloyal_style_sheet', BLOYAL_URL . 'assets/css/bloyal.css', array(), '1.0');
wp_enqueue_style('bloyal_style_sheet');
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
/**
* Function to include bloyal script(frontend).
*
* @param null
*
* @return void
*/
add_action('wp_enqueue_scripts', 'bloyal_include_scripts');
function bloyal_include_scripts()
{
$bloyal_sk = WC()->session ? WC()->session->get('bloyal_sk') : null;
$bloyal_session_key = null;
if (!empty($bloyal_sk)) {
$bloyal_session_key = isset($bloyal_sk['bloyal_session_key']) ? sanitize_text_field($bloyal_sk['bloyal_session_key']) : null;
}
$snippets_src = 'https://snippets.bloyal.io/bLoyalSnippetLoader.js?ver=' . BLOYAL_VERSION;
wp_enqueue_script('bLoyalSnippetLoader', $snippets_src, array(), null, true);
$plugin_slug = 'woocommerce-multiple-addresses';
wp_enqueue_script($plugin_slug . '-plugin-script', plugins_url('assets/js/shipping_details.js', __FILE__), array('jquery'), BLOYAL_VERSION, true);
wp_register_style('bloyal_checkout_style_sheet', BLOYAL_URL . '/assets/css/bloyal_checkout.css', array(), '1.0');
wp_enqueue_style('bloyal_checkout_style_sheet');
wp_localize_script(
$plugin_slug . '-plugin-script',
'WCMA_Ajax',
array(
'ajaxurl' => admin_url('admin-ajax.php'),
'id' => 0,
'wc_multiple_addresses' => wp_create_nonce('wc-multiple-addresses-ajax-nonce'),
'isLoggedIn' => is_user_logged_in(),
'bL_sk' => $bloyal_session_key,
)
);
}
add_action('wp_head', 'bloyal_myplugin_ajaxurl', 8);
function bloyal_myplugin_ajaxurl()
{
echo '';
}
/**
* This function is used to add meta box to configuartion page
*
* @return void
*/
add_action('add_meta_boxes', 'bloyal_add_meta_box');
function bloyal_add_meta_box()
{
try {
add_meta_box('bloyalmeta', 'bLoyal Configuration', 'show_meta', 'bLoyal', 'normal', 'high', null);
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
add_action('admin_menu', 'bloyal_add_dashboard_menu');
function bloyal_add_dashboard_menu()
{
try {
$access_key_snippets = get_option('bloyal_access_key');
add_menu_page('', 'bLoyal', '', __FILE__, '', plugins_url('assets/images/bloyal_logo_16x16.png', __FILE__), 24);
add_submenu_page(__FILE__, 'configuration', 'Loyalty Configuration', 'manage_options', 'bconfig', 'bloyal_add_config_submenu', 7, plugins_url() . '/bloyal/view/Logo.jpg');
if (! empty($access_key_snippets)) {
add_submenu_page(__FILE__, 'configuration', 'Order Processing Configuration', 'manage_options', 'bconfig_order_processing', 'bloyal_add_config_submenu_orders', 7, plugins_url() . '/bloyal/view/Logo.jpg');
add_submenu_page(__FILE__, 'bloyal snippets', 'Web Snippets', 'manage_options', 'bloyal_snippets', 'bloyal_snippets_add_snippets_detail_submenu', plugins_url() . '/bloyal/view/Logo.jpg');
add_submenu_page(__FILE__, 'bloyal click and collect', 'Click & Collect', 'manage_options', 'bloyal_click_and_collect', 'bloyal_click_and_collect_config_submenu', plugins_url() . '/bloyal/view/Logo.jpg');
}
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
function bloyal_add_config_submenu()
{
try {
$bloyal_view_obj = new BloyalView();
$bloyal_view_obj->bloyal_render_config_submenu_page();
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
function bloyal_add_config_submenu_orders()
{
try {
$bloyal_view_obj = new BloyalView();
$bloyal_view_obj->bloyal_render_config_submenu_page_order_processing();
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
function bloyal_click_and_collect_config_submenu()
{
try {
$bloyal_view_obj = new BloyalView();
$bloyal_view_obj->bloyal_click_and_collect_config_submenu_page();
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
add_action('wp_ajax_get_bloyal_access_key_by_apikey', 'bloyal_get_access_key');
function bloyal_get_access_key()
{
try {
function get_access_key_by_apikey()
{
try {
$bloyal_obj = new BloyalController();
$domain_name = sanitize_text_field(wp_unslash($_POST['post_domain_name']));
$api_key = sanitize_text_field(wp_unslash($_POST['post_api_key']));
$domain_url = sanitize_text_field(wp_unslash($_POST['post_domain_url']));
$is_bloyal_custom_url_used = sanitize_text_field(wp_unslash($_POST['post_custom_api_url_used']));
$custom_grid_api_url = sanitize_text_field(wp_unslash($_POST['post_custom_grid_api_url']));
return $bloyal_obj->bloyal_get_access_key_curl($domain_name, $api_key, $domain_url, $is_bloyal_custom_url_used, $custom_grid_api_url);
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
wp_send_json(
wp_json_encode(
array(
'status' => 'error',
'error_msg_api' => $ex->getMessage(),
'code' => 500,
)
)
);
die();
}
}
wp_send_json(get_access_key_by_apikey());
wp_deregister_script('autosave');
die();
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
wp_send_json(
wp_json_encode(
array(
'status' => 'error',
'error_msg_api' => $ex->getMessage(),
'code' => 500,
)
)
);
die();
}
}
add_action('wp_ajax_resubmit_bloyal_order_data', 'bloyal_order_details_to_resubmit');
function bloyal_order_details_to_resubmit()
{
try {
function order_details_to_resubmit()
{
try {
$resubmit_obj = new BLOYAL_ResubmitOrderController();
$order_id = sanitize_text_field(wp_unslash($_POST['post_order_id']));
return $resubmit_obj->make_resubmit_request($order_id);
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
return $ex->getMessage();
}
}
wp_send_json(order_details_to_resubmit());
wp_deregister_script('autosave');
die();
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
return $ex->getMessage();
}
}
add_action('wp_ajax_test_bloyal_access_key_by_apikey', 'bloyal_test_access_key');
function bloyal_test_access_key()
{
try {
function test_access_key_by_apikey()
{
try {
$bloyal_obj = new BloyalController();
$domain_name = sanitize_text_field(wp_unslash($_POST['post_domain_name']));
$api_key = sanitize_text_field(wp_unslash($_POST['post_api_key']));
$domain_url = sanitize_text_field(wp_unslash($_POST['post_domain_url']));
$access_key = sanitize_text_field(wp_unslash($_POST['post_access_key']));
$custom_api_url_used = sanitize_text_field(wp_unslash($_POST['post_custom_api_url_used']));
$custom_grid_api_url = sanitize_text_field(wp_unslash($_POST['post_custom_grid_api_url']));
$custom_payment_api_url = sanitize_text_field(wp_unslash($_POST['post_custompayment_api_url']));
return $bloyal_obj->bloyal_test_access_key_curl($domain_name, $api_key, $domain_url, $access_key, $custom_api_url_used, $custom_grid_api_url, $custom_payment_api_url);
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
wp_send_json(
wp_json_encode(
array(
'status' => 'error',
'error_msg_api' => $ex->getMessage(),
'code' => 500,
)
)
);
die();
}
}
wp_send_json(test_access_key_by_apikey());
wp_deregister_script('autosave');
die();
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
echo wp_json_encode(
array(
'status' => 'error',
'error_msg_api' => $ex->getMessage(),
'code' => 500,
)
);
die();
}
}
add_action('wp_ajax_check_access_key_before_save', 'bloyal_check_bloyal_access_key_before_save');
function bloyal_check_bloyal_access_key_before_save()
{
try {
function check_bloyal_access_key()
{
try {
$bloyal_obj = new BloyalController();
$domain_name = sanitize_text_field(wp_unslash($_POST['post_domain_name']));
$api_key = sanitize_text_field(wp_unslash($_POST['post_api_key']));
$domain_url = sanitize_text_field(wp_unslash($_POST['post_domain_url']));
$access_key = sanitize_text_field(wp_unslash($_POST['post_access_key']));
$custom_api_url_used = sanitize_text_field(wp_unslash($_POST['post_custom_api_url_used']));
$custom_grid_api_url = sanitize_text_field(wp_unslash($_POST['post_custom_grid_api_url']));
$custom_payment_api_url = sanitize_text_field(wp_unslash($_POST['post_custompayment_api_url']));
return $bloyal_obj->bloyal_test_access_key_curl($domain_name, $api_key, $domain_url, $access_key, $custom_api_url_used, $custom_grid_api_url, $custom_payment_api_url);
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
wp_send_json(check_bloyal_access_key());
wp_deregister_script('autosave');
die();
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
add_action('wp_ajax_save_bloyal_configuration_data', 'bloyal_save_configuration_data');
function bloyal_save_configuration_data()
{
try {
function save_configuration_data()
{
try {
$bloyal_obj = new BloyalController();
return $bloyal_obj->bloyal_save_configuration_data_wpdb();
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
echo save_configuration_data();
wp_deregister_script('autosave');
die();
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
add_action('wp_ajax_save_bloyal_configuration_data_order_processing', 'bloyal_save_configuration_data_order_processing');
function bloyal_save_configuration_data_order_processing()
{
try {
function save_configuration_data()
{
try {
$bloyal_obj = new BloyalController();
return $bloyal_obj->bloyal_save_configuration_data_wpdb_order_processing();
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
wp_send_json(save_configuration_data());
wp_deregister_script('autosave');
die();
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
add_action('wp_ajax_save_bloyal_accesskeyverification_data', 'bloyal_save_accesskeyverification_data');
function bloyal_save_accesskeyverification_data()
{
try {
function save_accesskeyverification_data()
{
try {
$bloyal_obj = new BloyalController();
$access_key_verification = sanitize_text_field(wp_unslash($_POST['post_access_key_verification']));
$is_custom_bloyal_url = sanitize_text_field(wp_unslash($_POST['post_bloyal_custom_url']));
return $bloyal_obj->bloyal_save_accesskeyverification_data_wpdb($access_key_verification, $is_custom_bloyal_url);
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
wp_send_json(save_accesskeyverification_data());
wp_deregister_script('autosave');
die();
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
add_action('wp_ajax_get_bloyal_configuration_details', 'bloyal_get_configuration_details');
function bloyal_get_configuration_details()
{
try {
function get_configuration_details()
{
try {
$bloyal_obj = new BloyalController();
return $bloyal_obj->bloyal_get_configuration_details_from_wpdb();
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
wp_send_json(get_configuration_details());
wp_deregister_script('autosave');
die();
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
add_action('wp_ajax_get_bloyal_accesskeyverification_details', 'bloyal_get_accesskeyverification_details');
function bloyal_get_accesskeyverification_details()
{
try {
function get_accesskeyverification_details()
{
try {
$bloyal_obj = new BloyalController();
return $bloyal_obj->bloyal_get_accesskeyverification_details_from_wpdb();
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
wp_send_json(get_accesskeyverification_details());
wp_deregister_script('autosave');
die();
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
add_action('woocommerce_proceed_to_checkout', 'bloyal_cart_coupon_remove');
function bloyal_cart_coupon_remove()
{
$loyalty_block_setting = get_option('loyalty_block');
if (empty($loyalty_block_setting) || false == $loyalty_block_setting) {
bLoyalLoggerService::write_custom_log("\r\n ========== loyalty_block ============\r\n" . $loyalty_block_setting);
}
?>
[View Loyalty And Discounts]
bloyal_fetch_discount_summary();
$loyalty_block_html = json_decode($loyalty_block_html);
$loyalty_block_html = $loyalty_block_html->msg;
echo '' . wp_kses_post($loyalty_block_html) . '';
$session_bloyal_coupons = WC()->session->get('bloyal_coupon');
if (isset($session_bloyal_coupons)) {
if ($session_bloyal_coupons) {
echo '[Remove Coupons]';
}
}
echo '
';
$time_post = microtime(true);
$exec_time = $time_post - $time_pre;
}
add_filter('woocommerce_payment_gateways', 'bloyal_custom_payment_gateways');
function bloyal_custom_payment_gateways($gateways)
{
try {
$access_key = get_option('bloyal_access_key');
if (! empty($access_key)) {
$gateways[] = 'Bloyal_Gift_Card_Gateway';
$gateways[] = 'Bloyal_Loyalty_Dollar_Gateway';
$gateways[] = 'Bloyal_Stored_Payment_Gateway';
}
return $gateways;
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_action('wp_ajax_check_loyalty_dollar_balance', 'bloyal_check_loyalty_dollar_balance'); // Loyalty dollar balance check
add_action('wp_ajax_nopriv_check_loyalty_dollar_balance', 'bloyal_check_loyalty_dollar_balance'); // Loyalty dollar balance check
function bloyal_check_loyalty_dollar_balance()
{
try {
$balance = (new LoyaltyDollarPaymentController())->getLoyaltyDollarBalance();
$message = '';
$applyFullBalance = get_option('bloyal_apply_full_balance_loyalty');
$applyIncrementOf = get_option('bloyal_apply_in_increment_of_loyalty');
// for guest user(Loyalty dollar)
if (! is_user_logged_in()) {
$message = 'Unable to check balance for guest user...';
} elseif (is_int($balance)) {
$message = 'Unable to check your balance.';
} else {
$balance = $balance->GetCardBalanceResult->AvailableBalance;
$cart_total = WC()->cart->total;
if ($applyFullBalance == 'false') {
if (($cart_total <= $balance) && ($balance != 0)) {
$message = 'Current balance is : $' . $balance . ', choose an amount to redeem.';
}
if (($cart_total > $balance) && ($balance != 0)) {
$message = 'Current balance is : $' . $balance . ', choose an amount to redeem.';
}
if ($balance == 0) {
$message = 'Current balance is $' . $balance . ', place order with another tender.';
}
} else {
if (($cart_total <= $balance) && ($balance != 0)) {
$message = 'Current balance is : $' . $balance . ' , $' . $cart_total . ' will be redeemed on order completion.';
WC()->session->set('loyalty_balance_check', floatval($balance));
}
if (($cart_total > $balance) && ($balance != 0)) {
$message = "Click 'Apply Balance' to pay $" . $balance . ', then place order with another tender.';
WC()->session->set('loyalty_balance_check', floatval($balance));
}
if ($balance == 0) {
$message = 'Current balance is $' . $balance . ', place order with another tender.';
}
}
$cartTotal = $cart_total;
}
wp_send_json(
wp_json_encode(
array(
'status' => 'success',
'message' => $message,
'balance' => $balance,
'apply_fullbalance' => $applyFullBalance,
'apply_incrementof' => $applyIncrementOf,
'cart_total' => $cart_total,
)
)
);
die();
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_action('wp_ajax_apply_loyalty_dollar_balance', 'bloyal_apply_loyalty_dollar_balance');
add_action('wp_ajax_nopriv_apply_loyalty_dollar_balance', 'bloyal_apply_loyalty_dollar_balance');
function bloyal_apply_loyalty_dollar_balance()
{
try {
$loyaltyBalance = (new LoyaltyDollarPaymentController())->getLoyaltyDollarBalance();
$message = '';
$applyFullBalance = get_option('bloyal_apply_full_balance_loyalty');
// if ( is_int( $balance ) ) {
if (is_int($loyaltyBalance)) {
$message = 'Unable to check balance, use another method or try again later.';
} else {
$cart_total = WC()->cart->total;
if ($applyFullBalance == 'false') {
$balance = sanitize_text_field(wp_unslash($_POST['post_redeem_amount']));
$availableBalance = $loyaltyBalance->GetCardBalanceResult->AvailableBalance;
if ($cart_total <= $balance) {
$message = 'Current balance is : $' . $availableBalance . ' , $' . $balance . ' will be redeemed on order completion.';
WC()->session->set('partial_loyalty_amount_redeem', floatval($balance));
} else {
$message = 'Current balance is : $' . $availableBalance . ' , Applied Balance is $' . $balance . ', then place order with another tender.';
WC()->session->set('partial_loyalty_amount', floatval($balance));
}
} else {
$balance = $loyaltyBalance->GetCardBalanceResult->AvailableBalance;
if ($cart_total <= $balance) {
$message = 'Current balance is : $' . $balance . ' , $' . $cart_total . ' will be redeemed on order completion.';
} else {
WC()->session->set('partial_loyalty_amount', floatval($balance));
}
}
}
$response = array(
'status' => 'success',
'message' => $message,
'balance' => $balance,
);
$response_json = wp_json_encode($response);
wp_send_json($response_json);
die();
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_action('wp_ajax_check_gift_card_balance', 'bloyal_check_gift_card_balance'); // Gift card balance check
add_action('wp_ajax_nopriv_check_gift_card_balance', 'bloyal_check_gift_card_balance'); // Gift card balance check
function bloyal_check_gift_card_balance()
{
try {
$gift_card_number = sanitize_text_field(wp_unslash($_POST['gift_card_number']));
$balance = (new PaymentController())->getGiftcardBalance($gift_card_number);
$message = '';
$applyFullBalance = get_option('bloyal_apply_full_balance_giftcard');
$applyIncrementOf = get_option('bloyal_apply_in_increment_of_giftcard');
if (is_int($balance)) {
$message = 'Invalid gift card number.';
} else {
$balance = $balance->GetCardBalanceResult->AvailableBalance;
$cart_total = WC()->cart->total;
if ($applyFullBalance == 'false') {
if (($cart_total <= $balance) && ($balance != 0)) {
$message = 'Current balance is : $' . number_format($balance, 2) . ' , choose an amount to redeem.';
}
if (($cart_total > $balance) && ($balance != 0)) {
$message = 'Current balance is $' . number_format($balance, 2) . ', choose an amount to redeem.';
}
if ($balance == 0) {
$message = 'Current balance is $' . number_format($balance, 2) . ', place order with another tender.';
}
WC()->session->set('partial_gift_number_increment_of', $gift_card_number);
} else {
if (($cart_total <= $balance) && ($balance != 0)) {
$message = 'Current balance is : $' . number_format($balance, 2) . ' , $' . number_format($cart_total, 2) . ' will be redeemed on order completion.';
}
if (($cart_total > $balance) && ($balance != 0)) {
$message = "Click 'Apply Balance' to pay $" . number_format($balance, 2) . ', then place order with another tender.';
}
if ($balance == 0) {
$message = 'Current balance is $' . number_format($balance, 2) . ', place order with another tender.';
}
}
}
$response = array(
'status' => 'success',
'message' => $message,
'balance' => $balance,
'apply_fullbalance' => $applyFullBalance,
'apply_incrementof' => $applyIncrementOf,
'cart_total' => $cart_total,
);
$response_json = wp_json_encode($response);
wp_send_json($response_json);
die();
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_action('wp_ajax_apply_gift_card_balance', 'bloyal_apply_gift_card_balance');
add_action('wp_ajax_nopriv_apply_gift_card_balance', 'bloyal_apply_gift_card_balance');
function bloyal_apply_gift_card_balance()
{
try {
$gift_card_number = sanitize_text_field(wp_unslash($_POST['gift_card_number']));
$giftBalance = (new PaymentController())->getGiftcardBalance($gift_card_number);
$message = '';
$applyFullBalance = get_option('bloyal_apply_full_balance_giftcard');
if (is_int($giftBalance)) {
$message = 'Invalid gift card number.';
} else {
$cart_total = WC()->cart->total;
if ($applyFullBalance === 'false') {
$redeemBalance = sanitize_text_field(wp_unslash($_POST['post_redeem_amount']));
$balance = $giftBalance->GetCardBalanceResult->AvailableBalance;
if ($cart_total <= $redeemBalance) {
$message = 'Current balance is : $' . number_format($balance, 2) . ' , $' . number_format($redeemBalance, 2) . ' will be redeemed on order completion.';
WC()->session->set('partial_gift_amount_redeem', floatval($balance));
} else {
$message = 'Current balance is : $' . number_format($balance, 2) . ' , Applied Balance is $' . number_format($redeemBalance, 2) . ', then place order with another tender.';
$balance = $redeemBalance;
WC()->session->set('partial_gift_amount', floatval($redeemBalance));
WC()->session->set('partial_gift_number', $gift_card_number);
}
} else {
$balance = $giftBalance->GetCardBalanceResult->AvailableBalance;
if ($cart_total <= $balance) {
$message = 'Current balance is : $' . number_format($balance, 2) . ' , $' . number_format($cart_total, 2) . ' will be redeemed on order completion.';
} elseif ($balance == 0) {
$message = 'Current balance is : $' . number_format($balance, 2) . ' , then place order with another tender';
} else {
WC()->session->set('partial_gift_amount', floatval($balance));
WC()->session->set('partial_gift_number', $gift_card_number);
}
}
}
$response = array(
'status' => 'success',
'message' => $message,
'balance' => $balance,
);
$response_json = wp_json_encode($response);
wp_send_json($response_json);
wp_die();
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_action('woocommerce_review_order_after_order_total', 'bloyal_add_remove_link_after_total');
function bloyal_add_remove_link_after_total()
{
try {
$bloyal_session_coupons = WC()->session->get('bloyal_coupon');
if (isset($bloyal_session_coupons)) {
if ($bloyal_session_coupons) {
?>
[Remove Coupons]'; ?>
getMessage(), 3);
}
}
add_action('woocommerce_after_cart_item_quantity_update', 'bloyal_after_cart_item_quantity_update', 10, 3);
function bloyal_after_cart_item_quantity_update($cart_item_key, $quantity, $old_quantity)
{
try {
$bloyal_obj = new BloyalController();
$bloyal_obj->bloyal_after_cart_item_quantity_update();
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
add_action('wp_ajax_refresh_cached_data', 'bloyal_refresh_cached_data');
function bloyal_refresh_cached_data()
{
try {
$bloyal_obj = new BloyalController();
$action = 'Connectors/ContextInfo';
$isFailed = false;
bLoyalLoggerService::write_custom_log("Get Devices Request URL \r\n" . $action . "\r\n ======================\r\n", 1);
$result = $bloyal_obj->send_curl_request('', $action, 'grid', 0);
bLoyalLoggerService::write_custom_log("Get Devices Response \r\n" . wp_json_encode($result) . "\r\n ======================\r\n", 1);
update_option('Device_Code', $result->data->DeviceCode);
$device_code = $result->data->DeviceCode;
$action = $device_code . '/SnippetProfiles';
bLoyalLoggerService::write_custom_log("Get Snippets Request URL \r\n" . $action . "\r\n ======================\r\n", 1);
$snippet_code = array(
'all' => array(),
'informational' => array(),
'confirmation' => array(),
'problem' => array(),
);
$result = $bloyal_obj->send_curl_request('', $action, 'web_snippets_api_url', 0);
bLoyalLoggerService::write_custom_log("Get Snippets Response \r\n" . wp_json_encode($result) . "\r\n ======================\r\n", 1);
$payment_snippet_code = '';
if ('success' == $result->status) {
if (! empty($result->data)) {
foreach ($result->data as $key => $snippet) {
if ('Alert' == $snippet->SnippetType) {
$SnippetSettings = json_decode($snippet->SnippetSettings);
$snippet_code[strtolower($SnippetSettings->AlertType)][] = $snippet->Code;
}
if ('PaymentMethod' == $snippet->SnippetType) {
$payment_snippet_code = $snippet->Code;
update_option('payment_snippets_codes', $payment_snippet_code);
}
}
}
$snippet_code['informational'] = array_merge($snippet_code['informational'], $snippet_code['all']);
$snippet_code['confirmation'] = array_merge($snippet_code['confirmation'], $snippet_code['all']);
$snippet_code['problem'] = array_merge($snippet_code['problem'], $snippet_code['all']);
update_option('bloyal_snippets_codes', wp_json_encode($snippet_code));
} else {
$errorMessage = 'Could not refresh at the moment, please try again later';
$isFailed = true;
}
$result_tenders = $bloyal_obj->send_curl_request('', 'Tenders', 'grid', 0);
if ('success' == $result_tenders->status) {
update_option('bloyal_Tenders', wp_json_encode($result_tenders));
} else {
$errorMessage = 'Could not refresh at the moment, please try again later';
$isFailed = true;
}
$result_ShippingCarriers = $bloyal_obj->send_curl_request('', 'ShippingCarriers', 'grid', 0);
if ('success' == $result_ShippingCarriers->status) {
update_option('bloyal_ShippingCarriers', wp_json_encode($result_ShippingCarriers));
} else {
$errorMessage = 'Could not refresh at the moment, please try again later';
$isFailed = true;
}
wp_send_json(
wp_json_encode(
array(
'status' => $isFailed ? 'failed' : 'success',
'errorMessage' => $errorMessage,
)
)
);
die;
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
echo wp_json_encode(
array(
'status' => 'failed',
'errorMessage' => $ex->getMessage(),
)
);
die;
}
}
add_action('woocommerce_admin_order_data_after_billing_address', 'bloyal_custom_date_of_birth_field_billing', 10, 1);
function bloyal_custom_date_of_birth_field_billing($order)
{
echo '' . esc_html(__('Date of Birth')) . ':
' . esc_attr(get_post_meta($order->get_id(), '_bloyal_billing_date_of_birth', true)) . '
';
}
add_action('woocommerce_admin_order_data_after_shipping_address', 'bloyal_custom_date_of_birth_field_shipping', 10, 1);
function bloyal_custom_date_of_birth_field_shipping($order)
{
$method = $order->get_shipping_methods();
echo '' . esc_html(__('Gift message')) . ':
' . esc_attr(get_post_meta($order->get_id(), '_bloyal_shipping_gift_message', true)) . '
';
echo '' . esc_html(__('Email address')) . ':
' . esc_attr(get_post_meta($order->get_id(), '_bloyal_shipping_email', true)) . '
';
echo '' . esc_html(__('Phone')) . ':
' . esc_attr(get_post_meta($order->get_id(), '_bloyal_shipping_phone', true)) . '
';
echo '' . esc_html(__('Date of Birth')) . ':
' . esc_attr(get_post_meta($order->get_id(), '_bloyal_shipping_date_of_birth', true)) . '
';
}
add_filter('woocommerce_checkout_fields', 'bloyal_custom_shipping_checkout_fields');
function bloyal_custom_shipping_checkout_fields($fields)
{
try {
// Ensure $fields is always an array to prevent fatal errors with other plugins (e.g., ShipStation)
if (!is_array($fields)) {
$fields = array();
}
if (is_checkout() || (is_cart())) {
global $current_user;
$otherAddrs = array();
$objectMultipleShippingController = new BLOYAL_MultipleShippingAddressController();
$current_user = wp_get_current_user();
if (! empty($current_user)) {
$loggedin_customer_id = isset($current_user->ID) && ($current_user->ID) ? $current_user->ID : '';
$loggedin_customer_email = isset($current_user->user_email) && ($current_user->user_email) ? $current_user->user_email : '';
}
$addrs_count = 0;
$formatted_cust_bill_birth_date = ''; // define this variable to avoid the warnings (03-04-2024)
$isDisplayPhone = get_option('bloyal_display_Phone');
$isRequiredPhone = get_option('bloyal_required_Phone');
$isDisplayEmail = get_option('bloyal_display_Email');
$isRequiredEmail = get_option('bloyal_required_Email');
$isDisplayOrderComments = get_option('bloyal_display_order_comments');
$isDisplayAddressBook = get_option('bloyal_display_address_Book');
// resolved warnings for undefined varriable
$customer_Fname = '';
$customer_Lname = '';
$customer_Address1 = '';
$customer_Address2 = '';
$customer_City = '';
$customer_StateName = '';
$customer_EmailAddress = '';
$customer_MobilePhone = '';
$customer_PostalCode = '';
$customer_Comp_name = '';
$customer_CountryName = '';
if ('true' == $isDisplayAddressBook) {
$cart_data = WC()->session->get('bloyal_cart_data');
$customer_uid = '';
$customer_code = '';
$customer_Fname = '';
$customer_Lname = '';
$customer_Comp_name = '';
$customer_Address1 = '';
$customer_Address2 = '';
$customer_City = '';
$customer_State = '';
$customer_PostalCode = '';
$customer_Country = '';
$customer_StateCode = '';
$customer_StateName = '';
$customer_CountryCode = '';
$customer_CountryName = '';
$customer_MobilePhone = '';
$customer_EmailAddress = '';
$customer_BirthDate = '';
if (! empty($cart_data)) {
$customer_uid = $cart_data->Cart->Customer->Uid;
$customer_code = $cart_data->Cart->Customer->Code;
// code to get calculatecart customer information (Start)
$customer_Fname = $cart_data->Cart->Customer->FirstName;
$customer_Lname = $cart_data->Cart->Customer->LastName;
$customer_Comp_name = $cart_data->Cart->Customer->CompanyName;
$customer_Address1 = $cart_data->Cart->Customer->Address->Address1;
$customer_Address2 = $cart_data->Cart->Customer->Address->Address2;
$customer_City = $cart_data->Cart->Customer->Address->City;
$customer_State = $cart_data->Cart->Customer->Address->State;
$customer_PostalCode = $cart_data->Cart->Customer->Address->PostalCode;
$customer_Country = $cart_data->Cart->Customer->Address->Country;
$customer_StateCode = $cart_data->Cart->Customer->Address->StateCode;
$customer_StateName = $cart_data->Cart->Customer->Address->StateName;
$customer_CountryCode = $cart_data->Cart->Customer->Address->CountryCode;
$customer_CountryName = $cart_data->Cart->Customer->Address->CountryName;
$customer_MobilePhone = $cart_data->Cart->Customer->MobilePhone;
$customer_EmailAddress = $cart_data->Cart->Customer->EmailAddress;
$customer_BirthDate = $cart_data->Cart->Customer->BirthDate;
}
if (null != $customer_BirthDate && '' != $customer_BirthDate) {
$dateTime = new DateTime($customer_BirthDate);
$formatted_cust_bill_birth_date = $dateTime->format('Y-m-d');
}
// code to get calculatecart customer information (end)
$saved_addrs = $objectMultipleShippingController->get_multiple_shipping_addresses($customer_uid, $customer_code);
$saved_addresses = wp_json_encode($saved_addrs);
$saved_addresses = json_decode($saved_addresses, true);
$total_saved_addrs = 0; // define variable to avoid warnings
if ($saved_addresses['status'] == 'success') {
$total_saved_addrs = count($saved_addresses['data']);
}
$addresses = array();
$addresses[0] = __('Please Configure shipping address..', 'woocommerce');
if (! empty($saved_addrs)) {
$addresses[0] = __('Select an address...', 'woocommerce');
for ($addrs_count = 0; $addrs_count < $total_saved_addrs; $addrs_count++) {
$addresses[$addrs_count + 1] = $saved_addresses['data'][$addrs_count]['Title'];
}
}
$alt_field = array(
'label' => __('Saved addresses', 'woocommerce'),
'required' => false,
'class' => array('form-row'),
'clear' => true,
'type' => 'select',
'priority' => 1,
'options' => $addresses,
);
$alt_save_address = array(
'label' => __('Save this Address', 'woocommerce'),
'id' => 'save_address_checkbox',
'name' => 'save_address_checkbox',
'type' => 'checkbox',
'priority' => 2,
'class' => array('form-row'),
);
$fields['shipping'] = bloyal_array_unshift_assoc($fields['shipping'], 'alt_save_address', $alt_save_address);
$fields['shipping'] = bloyal_array_unshift_assoc($fields['shipping'], 'shipping_alt', $alt_field);
}
if ('true' == $isDisplayPhone) {
$fields['shipping']['shipping_phone'] = array(
'type' => 'text',
'label' => __('Phone', 'woocommerce'),
'clear' => false,
'validate' => array('phone'),
'required' => 'true' == $isRequiredPhone ? true : false,
'priority' => 110,
);
}
if ('true' == $isDisplayEmail) {
$fields['shipping']['shipping_email'] = array(
'type' => 'email',
'label' => __('Email address', 'woocommerce'),
'clear' => false,
'validate' => array('email'),
'required' => 'true' == $isRequiredEmail ? true : false,
'priority' => 120,
);
}
if ('true' == $isDisplayOrderComments) {
$fields['billing']['order_comments2'] = array(
'type' => 'text',
'label' => __('Order Instructions', 'woocommerce'),
'clear' => false,
'required' => false,
'priority' => 130,
);
add_filter('woocommerce_enable_order_notes_field', '__return_false');
}
// code to set bLoyal calculatecart customer information on checkout page (start)
$fields['billing']['billing_first_name']['default'] = $customer_Fname;
$fields['billing']['billing_last_name']['default'] = $customer_Lname;
$fields['billing']['billing_address_1']['default'] = $customer_Address1;
$fields['billing']['billing_address_2']['default'] = $customer_Address2;
$fields['billing']['billing_city']['default'] = $customer_City;
$fields['billing']['billing_state']['default'] = $customer_StateName;
$fields['billing']['billing_email']['default'] = $customer_EmailAddress;
$fields['billing']['billing_phone']['default'] = $customer_MobilePhone;
$fields['billing']['billing_postcode']['default'] = $customer_PostalCode;
$fields['billing']['billing_company']['default'] = $customer_Comp_name;
$fields['billing']['billing_country']['default'] = $customer_CountryName;
$fields['billing']['billing_birth_date']['default'] = $formatted_cust_bill_birth_date;
// code to set bLoyal calculatecart customer information on checkout page (end)
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
// Ensure we always return an array even if there's an error
if (!is_array($fields)) {
$fields = array();
}
}
// Always return $fields to prevent null being passed to other plugins (e.g., ShipStation)
return is_array($fields) ? $fields : array();
}
function bloyal_array_unshift_assoc(&$arr, $key, $val)
{
try {
$arr = array_reverse($arr, true);
$arr[$key] = $val;
return array_reverse($arr, true);
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_action('wp_ajax_shipping_address_change', 'bloyal_ajax_checkout_change_shipping_address');
add_action('wp_ajax_nopriv_shipping_address_change', 'bloyal_ajax_checkout_change_shipping_address');
function bloyal_ajax_checkout_change_shipping_address()
{
try {
global $current_user;
$objectMultipleShippingController = new BLOYAL_MultipleShippingAddressController();
$current_user = wp_get_current_user();
if (! empty($current_user)) {
$loggedin_customer_id = isset($current_user->ID) && ($current_user->ID) ? $current_user->ID : '';
$loggedin_customer_email = isset($current_user->user_email) && ($current_user->user_email) ? $current_user->user_email : '';
$cart_data = WC()->session->get('bloyal_cart_data');
$customer_uid = $cart_data->Cart->Customer->Uid;
$customer_code = $cart_data->Cart->Customer->Code;
$saved_addrs = $objectMultipleShippingController->get_multiple_shipping_addresses($customer_uid, $customer_code);
$saved_addresses = wp_json_encode($saved_addrs);
$saved_addresses = json_decode($saved_addresses, true);
}
$selected = sanitize_text_field(wp_unslash($_REQUEST['id']));
$selected = $selected - 1;
header('Content-Type: application/json');
$saved_birth_date = null;
$saved_birth_date = $saved_addresses['data'][$selected]['BirthDate'];
if (null != $saved_birth_date && '' != $saved_birth_date) {
$saved_birth_date = explode('-', $saved_birth_date);
$saved_date = explode('T', $saved_birth_date[2]);
$formatted_shipping_date = $saved_birth_date[1] . '/' . $saved_date[0] . '/' . $saved_birth_date[0];
}
$current_shipping_addrs = array(
'shipping_first_name' => $saved_addresses['data'][$selected]['FirstName'],
'shipping_last_name' => $saved_addresses['data'][$selected]['LastName'],
'shipping_company' => $saved_addresses['data'][$selected]['Company'],
'shipping_country' => $saved_addresses['data'][$selected]['Address']['CountryName'],
'shipping_country_code' => $saved_addresses['data'][$selected]['Address']['CountryCode'],
'shipping_address_1' => $saved_addresses['data'][$selected]['Address']['Address1'],
'shipping_address_2' => $saved_addresses['data'][$selected]['Address']['Address2'],
'shipping_city' => $saved_addresses['data'][$selected]['Address']['City'],
'shipping_state' => $saved_addresses['data'][$selected]['Address']['StateName'],
'shipping_state_code' => $saved_addresses['data'][$selected]['Address']['StateCode'],
'shipping_postcode' => $saved_addresses['data'][$selected]['Address']['PostalCode'],
'shipping_birth_date' => $formatted_shipping_date,
'shipping_phone' => $saved_addresses['data'][$selected]['Phone1'],
'shipping_email' => $saved_addresses['data'][$selected]['EmailAddress'],
'uid' => $saved_addresses['data'][$selected]['Uid'],
);
WC()->session->set('current_shipping_address_uid', $saved_addresses['data'][$selected]['Uid']);
$current_shipping_addrs = wp_send_json($current_shipping_addrs);
exit;
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_action('woocommerce_before_order_notes', 'bloyal_gift_order_field');
function bloyal_gift_order_field($checkout)
{
try {
echo '';
woocommerce_form_field(
'gift_order_checkbox',
array(
'type' => 'checkbox',
'label' => __('Gift Order'),
'id' => 'gift_order_id',
'name' => 'gift_order_id',
'required' => false,
),
$checkout->get_value('gift_order_checkbox')
);
echo '';
echo '';
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_action('wp_ajax_save_shipping_address', 'bloyal_ajax_save_shipping_address');
function bloyal_ajax_save_shipping_address()
{
try {
$save_shipping_address = sanitize_text_field(wp_unslash($_POST['save_shipping_addrs']));
bLoyalLoggerService::write_custom_log("\r\n ========== saved value ============\r\n" . $save_shipping_address);
WC()->session->set('check_save_shipping_address', $save_shipping_address);
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
function bloyal_add_payment_methods_to_checkout()
{
try {
$objectAddPaymentMethods = new AddPaymentMethods();
$current_user = wp_get_current_user();
if (! empty($current_user)) {
$payment_methods = $objectAddPaymentMethods->save_payment_methods($current_user->ID, $current_user->user_email);
}
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
function bloyal_custom_cron_schedule($schedules)
{
try {
$schedules['every_one_day'] = array(
'interval' => 86400,
'display' => esc_html__('Every One day'),
);
return $schedules;
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_filter('cron_schedules', 'bloyal_custom_cron_schedule');
if (! wp_next_scheduled('bloyal_cron_hook')) {
wp_schedule_event(time(), 'every_one_day', 'bloyal_cron_hook');
}
// add_action( 'bloyal_cron_hook', 'bloyal_cron_function' );
function bloyal_cron_function()
{
try {
$bloyal_obj = new BloyalController();
$domain_name = get_option('bloyal_domain_name');
$domain_url = get_option('bloyal_domain_url');
$is_bloyal_custom_url_used = get_option('is_bloyal_custom_api_url');
$bloyal_urls = $bloyal_obj->bloyal_get_service_urls($domain_name, $domain_url, $is_bloyal_custom_url_used);
bLoyalLoggerService::write_custom_log("\r\n ========== Get Service URLs updated by CRON Job ============\r\n");
if (empty($domain_name) || false == $domain_name) {
bLoyalLoggerService::write_custom_log("\r\n ========== bloyal_domain_name ============\r\n" . $domain_name);
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_filter('woocommerce_order_shipping_to_display', 'bloyal_filter_woocommerce_order_shipping_to_display', 10, 2);
function bloyal_filter_woocommerce_order_shipping_to_display($shipping, $instance)
{
try {
if ($instance->get_shipping_method() == 'Local pickup $0.00') {
return $shipping;
}
if ($instance->get_shipping_method() == 'Free shipping') {
return $shipping;
}
if ($instance->get_total_shipping() == 0.00) {
$shipping = '$0 ' . $instance->get_shipping_method();
return $shipping;
}
return $shipping;
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_filter('woocommerce_package_rates', 'bloyal_sort_shipping_services_by_priority', 10, 2);
function bloyal_sort_shipping_services_by_priority($rates, $package)
{
try {
// OPTIMIZE and sort by priority
$bloyal_rates = WC()->session->get('custom_bloyal_shipping_rates');
$bloyal_rate_uids = array();
if (! empty($bloyal_rates)) {
foreach ($bloyal_rates as $rate) {
array_push($bloyal_rate_uids, $rate['id']);
}
}
if (isset($rates) && (! $rates)) {
return;
}
$rate_priorities = array();
$woocommerce_native = array();
foreach ($rates as $rate) {
$bloyal_id = $rate->id;
$rate_priority = array_search($bloyal_id, $bloyal_rate_uids);
if ($rate_priority != false) {
array_push($rate_priorities, $rate_priority);
} elseif ($rate_priority === 0) {
array_push($rate_priorities, 0);
} else {
array_push($rate_priorities, 1000);
}
}
array_multisort($rate_priorities, SORT_NUMERIC, SORT_ASC, $rates);
return $rates;
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
function bloyal_log_cron_schedule($schedules)
{
$schedules['every_ten_seconds'] = array(
'interval' => 10,
'display' => esc_html__('Every Ten Seconds'),
);
return $schedules;
}
add_filter('cron_schedules', 'bloyal_log_cron_schedule');
if (! wp_next_scheduled('bloyal_cron_log_hook')) {
wp_schedule_event(time(), 'every_ten_seconds', 'bloyal_cron_log_hook');
}
add_action('bloyal_cron_log_hook', 'bloyal_upload_bloyal_log');
function bloyal_upload_bloyal_log()
{
try {
$bLoyal_logger_service_obj = new bLoyalLoggerService();
$bLoyal_logger_service_obj->uploadLog();
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
add_filter('woocommerce_ship_to_different_address_checked', '__return_false');
// End of WooCommerce Cart Ops -----------------------------------------------------------------------------------------------
// Start bLoyal Snippets -----------------------------------------------------------------------------------------------------
function bloyal_snippets_add_snippets_detail_submenu()
{
$bloyal_snippets_view_obj = new BloyalSnippetsView();
$bloyal_snippets_view_obj->bloyal_snippets_render_snippets_detail_submenu_page();
}
add_action('admin_enqueue_scripts', 'bloyal_snippets_enqueue_scripts');
/**
* Initialize bloyal_snippets_enqueue_scripts.
*
* @return void
*/
function bloyal_snippets_enqueue_scripts()
{
// Depends on bloyal_scripts for the admin-ajax nonce prefilter and bloyalAuth data.
wp_enqueue_script('bloyal_snippets_scripts', BLOYAL_URL . '/assets/js/bloyal_snippets.js', array('jquery', 'bloyal_scripts'), BLOYAL_VERSION, true);
wp_register_style('bloyal_snippets_style_sheet', BLOYAL_URL . '/assets/css/bloyal_snippets.css', array(), '1.0');
wp_enqueue_style('bloyal_snippets_style_sheet');
}
add_action('wp_ajax_get_access_key_by_apikey_snippets', 'bloyal_snippets_get_access_key');
function bloyal_snippets_get_access_key()
{
try {
$master_settings_obj = new BloyalSnippetsSettingsController();
$obj = new stdClass();
$obj->domain_name_snippets = sanitize_text_field(wp_unslash($_POST['post_domain_name_snippets']));
$obj->api_key_snippets = sanitize_text_field(wp_unslash($_POST['post_api_key_snippets']));
$obj->domain_url_snippets = sanitize_text_field(wp_unslash($_POST['post_domain_url_snippets']));
$obj->is_custom_web_snippet_url_used = sanitize_text_field(wp_unslash($_POST['post_is_custom_web_snippet_url_used']));
$obj->snippets_custom_gridapi_url = sanitize_text_field(wp_unslash($_POST['post_snippetscustomgridapiurl']));
wp_send_json($master_settings_obj->bloyal_snippets_get_access_key_curl($obj));
die();
} catch (Exception $ex) {
wp_send_json(
wp_json_encode(
array(
'status' => 'error',
'error_msg_api' => $ex->getMessage(),
'code' => 500,
)
)
);
die();
}
}
add_action('wp_ajax_test_access_key_by_apikey_snippets', 'bloyal_snippets_test_access_key');
function bloyal_snippets_test_access_key()
{
try {
$master_settings_obj = new BloyalSnippetsSettingsController();
$obj = new stdClass();
$obj->domain_name_snippets = sanitize_text_field(wp_unslash($_POST['post_domain_name_snippets']));
$obj->api_key_snippets = sanitize_text_field(wp_unslash($_POST['post_api_key_snippets']));
$obj->domain_url_snippets = sanitize_text_field(wp_unslash($_POST['post_domain_url_snippets']));
$obj->access_key_snippets = sanitize_text_field(wp_unslash($_POST['post_access_key_snippets']));
$obj->is_custom_web_snippet_url_used = sanitize_text_field(wp_unslash($_POST['post_is_custom_web_snippet_url_used']));
$obj->snippets_custom_gridapi_url = sanitize_text_field(wp_unslash($_POST['post_snippetscustomgridapiurl']));
wp_send_json($master_settings_obj->bloyal_snippets_test_access_key($obj));
die();
} catch (Exception $ex) {
wp_send_json(
wp_json_encode(
array(
'status' => 'error',
'error_msg_api' => $ex->getMessage(),
'code' => 500,
)
)
);
die();
}
}
add_action('wp_ajax_check_snippets_access_key_before_save', 'bloyal_check_bloyal_snippets_access_key_before_save');
function bloyal_check_bloyal_snippets_access_key_before_save()
{
function check_bloyal_snippets_access_key()
{
$master_settings_obj = new BloyalSnippetsSettingsController();
$obj = new stdClass();
$obj->domain_name_snippets = sanitize_text_field(wp_unslash($_POST['post_domain_name_snippets']));
$obj->api_key_snippets = sanitize_text_field(wp_unslash($_POST['post_api_key_snippets']));
$obj->domain_url_snippets = sanitize_text_field(wp_unslash($_POST['post_domain_url_snippets']));
$obj->access_key_snippets = sanitize_text_field(wp_unslash($_POST['post_access_key_snippets']));
$obj->is_custom_web_snippet_url_used = sanitize_text_field(wp_unslash($_POST['post_is_custom_web_snippet_url_used']));
$obj->snippets_custom_gridapi_url = sanitize_text_field(wp_unslash($_POST['post_snippetscustomgridapiurl']));
return $master_settings_obj->bloyal_snippets_test_access_key($obj);
}
wp_send_json(check_bloyal_snippets_access_key());
wp_deregister_script('autosave');
die();
}
add_action('wp_ajax_save_configuration_data', 'bloyal_snippets_save_configuration_data');
function bloyal_snippets_save_configuration_data()
{
try {
$master_settings_obj = new BloyalSnippetsSettingsController();
$oblBloyalSnippetController = new BloyalSnippetsController();
$obj_save_conf = new stdClass();
$obj_save_conf->domain_name_snippets = sanitize_text_field(wp_unslash($_POST['post_domain_name_snippets']));
$obj_save_conf->api_key_snippets = sanitize_text_field(wp_unslash($_POST['post_api_key_snippets']));
$obj_save_conf->domain_url_snippets = sanitize_text_field(wp_unslash($_POST['post_domain_url_snippets']));
$obj_save_conf->access_key_snippets = sanitize_text_field(wp_unslash($_POST['post_access_key_snippets']));
$obj_save_conf->radio_web_snippet = sanitize_text_field(wp_unslash($_POST['post_radio_web_snippet_url']));
$obj_save_conf->custom_web_snippet_url = sanitize_text_field(wp_unslash($_POST['post_custom_web_snippet_url']));
$obj_save_conf->default_device = sanitize_text_field(wp_unslash($_POST['post_default_device']));
$obj_save_conf->post_use_wordpress_login = sanitize_text_field(wp_unslash($_POST['post_use_wordpress_login']));
$obj_save_conf->post_use_bloyal_login = sanitize_text_field(wp_unslash($_POST['post_use_bloyal_login']));
$obj_save_conf->snippetscustomgridapiurl = sanitize_text_field(wp_unslash($_POST['post_snippetscustomgridapiurl']));
$obj_save_conf->snippetscustomloyaltyengineapiurl = sanitize_text_field(wp_unslash($_POST['post_snippetscustomloyaltyengineapiurl']));
$obj_save_conf->snippetcustomwebsnippetapiurl = sanitize_text_field(wp_unslash($_POST['post_snippetcustomwebsnippetapiurl']));
$obj_save_conf->snippetcustomwebsnippethtmlapiurl = sanitize_text_field(wp_unslash($_POST['post_snippetcustomwebsnippethtmlapiurl']));
$obj_save_conf->page_id = sanitize_text_field(wp_unslash($_POST['post_page']));
bLoyalSnipetsLoggerService::write_custom_log("Save bLoyal Snippets Configuration data \n\r" . wp_json_encode($obj_save_conf) . "\r\n ======================\r\n", 1);
wp_send_json($master_settings_obj->bloyal_snippets_save_configuration_data_wpdb($obj_save_conf));
die();
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_action('wp_ajax_save_snippets_accesskeyverification_data', 'bloyal_snippets_save_accesskeyverification_data');
function bloyal_snippets_save_accesskeyverification_data()
{
try {
$master_settings_obj = new BloyalSnippetsSettingsController();
$access_key_verification_snippets = sanitize_text_field(wp_unslash($_POST['post_access_key_verification_snippets']));
$custom_web_snippet_url_used = sanitize_text_field(wp_unslash($_POST['post_custom_web_snippet_url_used']));
wp_send_json($master_settings_obj->bloyal_snippets_save_accesskeyverification_data_wpdb($access_key_verification_snippets, $custom_web_snippet_url_used));
die();
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_action('wp_ajax_get_configuration_details', 'bloyal_snippets_get_configuration_details');
function bloyal_snippets_get_configuration_details()
{
$master_settings_obj = new BloyalSnippetsSettingsController();
wp_send_json($master_settings_obj->bloyal_snippets_get_configuration_details_from_wpdb());
die();
}
add_action('wp_ajax_get_accesskeyverification_details', 'bloyal_snippets_get_accesskeyverification_details');
function bloyal_snippets_get_accesskeyverification_details()
{
try {
$master_settings_obj = new BloyalSnippetsSettingsController();
wp_send_json($master_settings_obj->bloyal_snippets_get_accesskeyverification_details_from_wpdb());
die();
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_action('wp_ajax_fetch_snippets_associated_with_device', 'bloyal_fetch_snippets_wrt_device');
function bloyal_fetch_snippets_wrt_device()
{
try {
$bloyal_snippets_obj = new BloyalSnippetsController();
$device_context = $bloyal_snippets_obj->send_curl_request('', 'contextdevices', 'loyaltyengine', 0);
$selected_device = $device_context->data->Code;
wp_send_json($bloyal_snippets_obj->bloyal_fetch_snippets_wrt_device($selected_device));
die();
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_action('wp_loaded', 'bloyal_add_shortcodes_for_all_devices');
function bloyal_add_shortcodes_for_all_devices()
{
try {
$arrSelectedSnippetShortCodes = get_option('bloyal_saved_device_snippets_lists');
if (! empty($arrSelectedSnippetShortCodes)) {
bloyal_addSnippetData($arrSelectedSnippetShortCodes);
} else {
$bloyal_snippets_obj = new BloyalSnippetsController();
$device_context = $bloyal_snippets_obj->send_curl_request('', 'contextdevices', 'loyaltyengine', 0);
if (! empty($device_context)) {
$savedSnippetDevice = $device_context->data->Code;
}
$snippetsData = $bloyal_snippets_obj->bloyal_fetch_snippets_wrt_device($savedSnippetDevice);
$snippetsData = json_decode($snippetsData, true);
if (! empty($snippetsData)) {
$arrSavedDeviceSnippetsList = array();
foreach ($snippetsData['snippets_list'] as $key => $snippet) {
$arrSavedDeviceSnippetsList[] = array(
'snippet_shortcode' => str_replace(array('[', ']'), '', $snippet['snippet_shortcode']),
'snippet_type' => $snippet['snippet_type'],
);
}
update_option('bloyal_saved_device_snippets_lists', $arrSavedDeviceSnippetsList);
bloyal_addSnippetData($arrSavedDeviceSnippetsList);
}
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
function bloyal_addSnippetData($arrSelectedSnippetShortCodes)
{
try {
global $wp_session;
if (! empty($arrSelectedSnippetShortCodes)) {
foreach ($arrSelectedSnippetShortCodes as $key => $strShortCode) {
add_shortcode($strShortCode['snippet_shortcode'], 'bloyal_shortcode_callback');
$wp_session[$strShortCode['snippet_shortcode']] = $strShortCode['snippet_type'];
}
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
function bloyal_shortcode_callback($atts, $content, $tag)
{
try {
ob_start();
global $wp_session;
$shortcode_name_content = explode('_', $tag);
$snipppet_code = $shortcode_name_content[1];
$device_code = $shortcode_name_content[2];
$club_code = isset($shortcode_name_content[3]) ? $shortcode_name_content[3] : '';
$snippet_type = '';
if (isset($wp_session[$tag])) {
$snippet_type = $wp_session[$tag];
}
$bloyal_snippets_obj = new BloyalSnippetsController();
echo $bloyal_snippets_obj->bloyal_fetch_snippet_html($atts, $snipppet_code, $device_code, $snippet_type, $club_code);
return ob_get_clean();
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_action('wp_ajax_save_snippets_uss_css_status', 'bloyal_save_snippets_uss_css_status');
function bloyal_save_snippets_uss_css_status()
{
try {
$bloyal_snippets_obj = new BloyalSnippetsController();
$checked_snippets = sanitize_text_field(wp_unslash($_POST['post_checked_snippets']));
$unchecked_snippets = sanitize_text_field(wp_unslash($_POST['post_unchecked_snippets']));
wp_send_json($bloyal_snippets_obj->bloyal_save_snippets_uss_css_status($checked_snippets, $unchecked_snippets));
die();
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_filter('woocommerce_login_redirect', 'bloyal_redirect_woocommerce_loggedin_user_to_snippet');
function bloyal_redirect_woocommerce_loggedin_user_to_snippet()
{
try {
bLoyalLoggerService::write_custom_log("\r\n ========== REQUEST ReturnUrl data 2586 ============\r\n" . $_REQUEST['ReturnUrl']);
if (isset($_REQUEST['ReturnUrl'])) {
$return_url = sanitize_url(wp_unslash($_REQUEST['ReturnUrl']));
bLoyalLoggerService::write_custom_log("\r\n ========== return url data 2588 ============\r\n" . $return_url);
wp_redirect($return_url);
exit;
} else {
wp_redirect(home_url());
exit;
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_filter('woocommerce_registration_redirect', 'bloyal_redirect_woocommerce_registered_user_to_snippet');
function bloyal_redirect_woocommerce_registered_user_to_snippet($user_id)
{
try {
$user = get_user_by('id', $user_id);
$user_email = $user->user_email;
if (isset($_REQUEST['ReturnUrl'])) {
// code to add bL_sk session key after register via web snippet page
//bloyal_customer_session_api($user_id, $user_email);
// $return_url = sanitize_url( wp_unslash( $_REQUEST['ReturnUrl'].'?bL_sk='.$_SESSION['bloyal_session_key'] ) );
$return_url = sanitize_url(wp_unslash($_REQUEST['ReturnUrl']));
wp_redirect($return_url);
exit;
} else {
$_wp_http_referer = sanitize_url(wp_unslash($_REQUEST['_wp_http_referer']));
wp_redirect($_wp_http_referer);
wp_redirect(home_url());
exit;
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_action('wp_logout', 'clear_session_storage_key');
// // Hook the function to wp_logout
function clear_session_storage_key()
{
// Since we can't use JavaScript here, we'll use PHP to delete the session storage key
// However, PHP can't directly access the browser's session storage
// We'll use a workaround by setting a cookie that will be read by JavaScript on the next page load
setcookie('clear_session_storage_key', 'true', 0, '/');
}
add_filter('wp_login', 'bloyal_redirect_wordpress_loggedin_user_to_snippet');
function bloyal_redirect_wordpress_loggedin_user_to_snippet($user_login)
{
try {
$user = get_user_by('login', $user_login);
$user_id = $user->ID;
$user_email = $user->user_email;
//bloyal_customer_session_api($user_id, $user_email);
$page_id = get_option('page_id');
if (0 == $page_id) {
if (isset($_REQUEST['ReturnUrl'])) {
$return_url = sanitize_url(wp_unslash($_REQUEST['ReturnUrl']));
wp_redirect($return_url);
exit;
} elseif (isset($_REQUEST['_wp_http_referer'])) {
$_wp_http_referer = sanitize_url(wp_unslash($_REQUEST['_wp_http_referer']));
wp_redirect($_wp_http_referer);
exit;
}
} elseif (isset($_REQUEST['ReturnUrl'])) {
// code to add bL_sk session key after login via web snippet page
// bloyal_customer_session_api($user_id, $user_email);
// $bloyal_sk = WC()->session->get( 'bloyal_sk' );
// $bloyal_session_key = null;
// if (!empty($bloyal_sk)) {
// $bloyal_session_key = isset( $bloyal_sk['bloyal_session_key'] ) ? sanitize_text_field( $bloyal_sk['bloyal_session_key'] ) : null;
// }
// $return_url = sanitize_url( wp_unslash( $_REQUEST['ReturnUrl'].'?bL_sk='.$bloyal_session_key ) );
$return_url = sanitize_url(wp_unslash($_REQUEST['ReturnUrl']));
if (strpos($return_url, '?ReturnUrl=')) {
$redirect_url = explode('ReturnUrl=', $return_url);
wp_redirect($redirect_url[1]);
exit;
}
wp_redirect($return_url);
exit;
} elseif (isset($_REQUEST['_wp_http_referer'])) {
$_wp_http_referer = sanitize_url(wp_unslash($_REQUEST['_wp_http_referer']));
wp_redirect($_wp_http_referer);
exit;
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_filter('user_register', 'bloyal_redirect_wordpress_registered_user_to_snippet');
function bloyal_redirect_wordpress_registered_user_to_snippet($user_id)
{
try {
if (empty($_REQUEST['ReturnUrl'])) {
$current_user = wp_get_current_user();
wp_set_current_user($current_user->data->ID ?? null);
wp_set_auth_cookie($current_user->data->ID ?? null, false, is_ssl());
} else {
wp_set_current_user($user_id);
wp_set_auth_cookie($user_id, false, is_ssl());
if (! empty($_REQUEST['ReturnUrl'])) {
$return_url = sanitize_url(wp_unslash($_REQUEST['ReturnUrl']));
wp_redirect($return_url);
}
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_action('wp_ajax_refresh_saved_data', 'bloyal_snippets_refresh_data');
function bloyal_snippets_refresh_data()
{
update_option('bloyal_saved_device_snippets_lists', '');
update_option('bLoyal_snippets_devices', '');
update_option('bLoyal_web_snippets_storeUid', '');
wp_send_json(
wp_json_encode(
array(
'status' => 'success',
)
)
);
die;
}
add_action('wp_ajax_refresh_device_codes', 'bloyal_refresh_device_codes');
function bloyal_refresh_device_codes()
{
$bloyal_snippets_obj = new BloyalSnippetsController();
$bloyal_snippets_obj->bloyal_fetch_all_devices();
wp_send_json(
wp_json_encode(
array(
'status' => 'success',
)
)
);
die;
}
add_filter('cron_schedules', 'bloyal_snippet_custom_cron_schedule');
function bloyal_snippet_custom_cron_schedule($schedules)
{
$schedules['every_twenty_four_hours'] = array(
'interval' => 86400,
'display' => __('Every 24 hours'),
);
return $schedules;
}
if (! wp_next_scheduled('bloyal_snippet_cron_hook')) {
wp_schedule_event(time(), 'every_twenty_four_hours', 'bloyal_snippet_cron_hook');
}
add_action('bloyal_snippet_cron_hook', 'bloyal_snippet_cron_function');
function bloyal_snippet_cron_function()
{
try {
$bloyal_snippets_obj = new BloyalSnippetsController();
$obj = new stdClass();
$obj->domain_name_snippets = get_option('bloyal_domain_name');
$obj->api_key_snippets = get_option('bloyal_api_key');
$obj->domain_url_snippets = get_option('bloyal_domain_url');
$obj->is_custom_web_snippet_url_used = get_option('bloyal_snippets_radio_web_snippet_api');
$bloyal_urls = $bloyal_snippets_obj->bloyal_snippets_get_service_urls($obj);
bLoyalSnipetsLoggerService::write_custom_log("\r\n ========== Get Service URLs updated by CRON Job ============\r\n");
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// REACT functionality ------------------------------------------------------------------------------------------------------
add_action('wp_loaded', 'bloyal_add_react_shortcodes');
function bloyal_add_react_shortcodes()
{
try {
$snippet_list = get_option('bloyal_saved_device_snippets_lists');
$react_shortcodes = array();
$react_shortcode = array(); // made this code on 1-04-2024 to remove $react_shortcode warnings
foreach ($snippet_list as $snippet) {
$snippet_components = explode('_', $snippet['snippet_shortcode']);
$react_shortcode1 = $snippet['snippet_shortcode'] . '_react';
$react_shortcode2 = $snippet['snippet_shortcode'] . '_React';
$react_shortcode3 = $snippet['snippet_shortcode'] . '_REACT';
add_shortcode($react_shortcode1, 'bloyal_react_club_shortcode_callback', false);
add_shortcode($react_shortcode2, 'bloyal_react_club_shortcode_callback', false);
add_shortcode($react_shortcode3, 'bloyal_react_club_shortcode_callback', false);
array_push($react_shortcodes, $react_shortcode);
}
// update_option( 'bloyal_saved_snippets_react', $react_shortcodes );
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// add_action('init', 'register_session');
function bloyal_register_session()
{
if (! session_id()) {
session_start();
}
}
add_filter('query_vars', 'bloyal_add_session_to_url');
function bloyal_add_session_to_url($aVars)
{
$aVars[] = 'bL_sk';
return $aVars;
}
add_filter('rewrite_rules_array', 'bloyal_add_rewrite_rules');
function bloyal_add_rewrite_rules($aRules)
{
$aNewRules = array('msds-pif/([^/]+)/?$' => 'index.php?pagename=msds-pif&msds_pif_cat=$matches[1]');
$aRules = $aNewRules + $aRules;
return $aRules;
}
function bloyal_react_club_shortcode_callback($atts, $content, $tag)
{
try {
ob_start();
global $wp_session;
$shortcode_name_content = explode('_', $tag);
$snipppet_code = $shortcode_name_content[1];
$device_code = $shortcode_name_content[2];
$club_code = isset($shortcode_name_content[3]) ? $shortcode_name_content[3] : '';
$snippet_type = '';
if (isset($wp_session[$tag])) {
$snippet_type = $wp_session[$tag];
}
$bloyal_snippets_obj = new BloyalSnippetsController();
echo esc_attr($bloyal_snippets_obj->bloyal_fetch_snippet_html($atts, $snipppet_code, $device_code, $snippet_type, $club_code));
return ob_get_clean();
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_action('wp_ajax_bloyal_activate_provisioning_snippets_url', 'bloyal_activate_provisioning_snippets_url');
function bloyal_activate_provisioning_snippets_url()
{
$provisioningStatus = WC()->session->get('provisioning_status');
bLoyalLoggerService::write_custom_log('activate_provisioning_snippets_url' . $provisioningStatus);
if ($provisioningStatus == 'Pending') {
$provisioningResponse = WC()->session->get('provisioning_response');
wp_send_json($provisioningResponse);
} else {
try {
// this api use for create bLoyal service provisioning session after the plugin activated in bLoyal loyalty configuration page click on activate device by bLoyal
$bloyal_provisioning_api_url = 'https://domain.bloyal.io/api/v4/ServiceProvisioning/Sessions/Devices';
$stor_name = get_option('blogname');
$stor_code = get_option('woocommerce_version');
$apiRequestData = array(
'ConnectorKey' => '94EC0683-BCA6-42EF-B172-86D11D4B1E56',
'StoreCode' => str_replace(' ', '', $stor_name) . str_replace('.', '', $stor_code),
'StoreName' => $stor_name,
'DeviceCode' => str_replace(' ', '', $stor_name) . str_replace('.', '', $stor_code),
'DeviceName' => 'wp_' . str_replace(' ', '', $stor_name),
'CustomSettings' => array(),
'Uid' => '',
'Status' => 'Pending',
'StatusMessage' => '',
'RetryCount' => 0,
);
$args = array(
'headers' => array(
'Content-Type' => 'application/json',
),
'body' => wp_json_encode($apiRequestData),
'method' => 'POST',
'timeout' => 45,
);
bLoyalLoggerService::write_custom_log('provisioning_api apiRequestData' . $args);
$response = wp_remote_post($bloyal_provisioning_api_url, $args);
bLoyalLoggerService::write_custom_log('provisioning_api apiRequest' . $response);
$response_status = wp_remote_retrieve_response_code($response);
bLoyalLoggerService::write_custom_log('provisioning_api apiResponse' . $response_status);
$response = wp_remote_retrieve_body($response);
if (! empty(json_decode($response, true))) {
$results = json_decode($response, true);
$data_status = $results['data']['Status'];
$provision_session_key = $results['data']['ProvisionSessionKey'];
WC()->session->set('provisioning_status', $data_status);
WC()->session->set('provisioning_key', $provision_session_key);
WC()->session->set('provisioning_response', $response);
}
wp_send_json($response);
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
wp_die();
}
add_action('wp_ajax_bloyal_activate_provisioning_device', 'bloyal_activate_provisioning_device');
function bloyal_activate_provisioning_device()
{
try {
if (! empty(WC()->session->get('provisioning_key'))) {
$provision_session_key = WC()->session->get('provisioning_key');
// this api use for get bLoyal service provisioning Sessions after the device success fully provisioned by bLoyal
$provisioning_session_key_api_url = 'https://domain.bloyal.io/api/v4/ServiceProvisioning/Sessions/' . $provision_session_key;
$args = array(
'headers' => array(
'Content-Type' => 'application/json',
),
'method' => 'GET',
'timeout' => 45,
);
$response = wp_remote_get($provisioning_session_key_api_url, $args);
$response_status = wp_remote_retrieve_response_code($response);
$response = wp_remote_retrieve_body($response);
$results = json_decode($response, true);
if ($results['status'] == 'success') {
$data_status = $results['data']['Status'];
$data_msg = $results['data']['StatusMessage'];
if ($data_status == 'Succeeded') {
WC()->session->__unset('provisioning_status');
WC()->session->__unset('provisioning_response');
WC()->session->__unset('provisioning_key');
} elseif ($data_status == 'Failed') {
WC()->session->__unset('provisioning_status');
WC()->session->__unset('provisioning_response');
WC()->session->__unset('provisioning_key');
}
if ($results['data']['AccessKey'] != '') {
bloyal_update_bLoyal_provisioning_activated_data_wpdb($results['data']);
} else {
wp_send_json(
wp_json_encode(
array(
'save_success' => false,
'Status' => $data_status,
'Message' => 'Device not activated, ' . $data_msg,
)
)
);
}
}
} else {
wp_send_json(
wp_json_encode(
array(
'save_success' => false,
'Status' => 'Pending',
)
)
);
}
wp_die();
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
function bloyal_update_bLoyal_provisioning_activated_data_wpdb($results)
{
try {
$access_key_verification = sanitize_text_field(wp_unslash($_POST['post_access_key_verification']));
$is_custom_bloyal_url = sanitize_url(wp_unslash($_POST['post_bloyal_custom_url']));
update_option('bloyal_access_key_verification', $access_key_verification);
update_option('is_bloyal_custom_api_url', $is_custom_bloyal_url);
update_option('bloyal_domain_name', isset($results['LoginDomain']) ? $results['LoginDomain'] : '');
update_option('bloyal_api_key', isset($results['ApiKey']) ? $results['ApiKey'] : '');
update_option('bloyal_domain_url', isset($results['ServiceUrls']['DirectorUrl']) ? $results['ServiceUrls']['DirectorUrl'] : '');
update_option('bloyal_access_key', isset($results['AccessKey']) ? $results['AccessKey'] : '');
// update_option('bloyal_on_account_tender_code', isset($results['post_on_account_tender']) ? $results['post_on_account_tender']: '');
update_option('bloyal_custom_grid_api_url', isset($results['ServiceUrls']['GridApiUrl']) ? $results['ServiceUrls']['GridApiUrl'] : '');
update_option('bloyal_custom_loyaltyengine_api_url', isset($results['ServiceUrls']['LoyaltyEngineApiUrl']) ? $results['ServiceUrls']['LoyaltyEngineApiUrl'] : '');
update_option('bloyal_custom_orderengine_api_url', isset($results['ServiceUrls']['OrderEngineApiUrl']) ? $results['ServiceUrls']['OrderEngineApiUrl'] : '');
update_option('bloyal_custompayment_api_url', isset($results['ServiceUrls']['PaymentApiUrl']) ? $results['ServiceUrls']['PaymentApiUrl'] : '');
update_option('bloyal_custom_logging_api_url', isset($results['ServiceUrls']['LoggingApiUrl']) ? $results['ServiceUrls']['LoggingApiUrl'] : '');
update_option('is_bloyal_custom_api_url', isset($results['ServiceUrls']['DirectorApiUrl']) ? $results['ServiceUrls']['DirectorApiUrl'] : '');
update_option('bloyal_click_and_collect_status', '2');
update_option('bloyal_click_collect_label', 'Pickup at Store');
update_option('click_collect_error', 'No store available for active cart.');
wp_send_json(wp_json_encode($results));
} catch (Exception $exception) {
bLoyalLoggerService::write_custom_log($exception->getMessage(), 3);
return $exception->getMessage();
}
wp_die();
}
add_action('wp_ajax_bloyal_save_bloyal_click_collect_configuration_data', 'bloyal_save_bloyal_click_collect_configuration_data');
function bloyal_save_bloyal_click_collect_configuration_data()
{
try {
function save_click_collect_configuration_data()
{
try {
$bloyal_obj = new BloyalController();
return $bloyal_obj->bloyal_save_click_collect_configuration_data_wpdb();
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
wp_send_json(save_click_collect_configuration_data());
wp_deregister_script('autosave');
die();
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
function bloyal_shipping_store_pickup_method()
{
try {
if (! class_exists('bloyal_Shipping_Store_Pickup_Method')) {
class bloyal_Shipping_Store_Pickup_Method extends WC_Shipping_Method
{
/**
* Constructor for your shipping class
*
* @access public
* @return void
*/
public function __construct($instance_id = 0)
{
$this->id = 'bloyal_pickup_store';
$this->instance_id = absint($instance_id);
$this->method_title = __('bloyal Shipping Pickup at Store');
$this->method_description = __('Custom Shipping Pickup at Store Method for bloyal');
$this->supports = array(
'shipping-zones',
'instance-settings',
);
$this->instance_form_fields = array(
'enabled' => array(
'title' => __('Enable/Disable'),
'type' => 'checkbox',
'label' => __('Enable this shipping method'),
'default' => 'no',
),
'title' => array(
'title' => __('bloyal Shipping Pickup at Store'),
'type' => 'text',
'description' => __('This controls the title which the user sees during checkout.'),
'default' => __('Pickup at Store'),
'desc_tip' => true,
),
);
$this->enabled = $this->get_option('enabled');
$this->title = $this->get_option('title');
add_action('woocommerce_update_options_shipping_' . $this->id, array($this, 'process_admin_options'));
}
/**
* calculate_shipping function.
*
* @param array $package (default: array())
*/
public function calculate_shipping($package = array())
{
$this->add_rate(
array(
'id' => $this->id . ':' . $this->instance_id,
'label' => $this->title,
'cost' => 0,
)
);
}
}
}
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
add_action('woocommerce_shipping_init', 'bloyal_shipping_store_pickup_method');
function bloyal_add_bloyal_shipping_store_pickup_method($methods)
{
try {
$methods['bloyal_pickup_store'] = 'bloyal_Shipping_Store_Pickup_Method';
return $methods;
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_filter('woocommerce_shipping_methods', 'bloyal_add_bloyal_shipping_store_pickup_method');
}
add_filter('script_loader_tag', 'bloyal_add_attributes_to_script', 10, 3);
/**
* Initialize add_attributes_to_script.
*
* @param mixed $tag string.
* @param mixed $handle string.
* @param mixed $src string.
* @return string
*/
function bloyal_add_attributes_to_script($tag, $handle, $src)
{
try {
if ('bLoyalSnippetLoader' === $handle) {
$snippet_domain = get_option('bloyal_domain_name');
$tag = '';
}
return $tag;
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_action('wp_ajax_bloyal_remove_bloyal_accesskey', 'bloyal_remove_bloyal_access_key');
function bloyal_remove_bloyal_access_key()
{
try {
$adv_access_key = isset($_POST['post_adv_access_key']) ? sanitize_text_field(wp_unslash($_POST['post_adv_access_key'])) : '';
update_option('bloyal_access_key', $adv_access_key);
$result = array(
'message' => 'Access Key succefully removed!',
'status' => 'success',
);
wp_send_json($result);
wp_die();
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
// store payment method developed by Chetu Developer Saurabh Gupta
add_action('wp_ajax_bloyal_stored_payment_method', 'bloyal_stored_payment_method');
function bloyal_stored_payment_method()
{
try {
if (isset($_POST['method_uid'])) {
$stored_payment_uid = sanitize_text_field(wp_unslash($_POST['method_uid']));
WC()->session->set('stored_payment_uid', $stored_payment_uid);
$current_user_id = get_current_user_id();
if ($current_user_id > 0) {
update_user_meta($current_user_id, '_bloyal_stored_payment_uid', $stored_payment_uid);
}
}
wp_die();
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// Pickup at Store locations carrier // Date :- 07/12/2022 Developed by Chetu Developer Saurabh Gupta
function bloyal_store_pickup_locations_data()
{
try {
if (is_cart() || (is_checkout())) {
$stores_data = array();
$click_and_collect_label = get_option('bloyal_click_collect_label');
$bloyal_click_and_collect_status = get_option('bloyal_click_and_collect_status');
$bloyal_click_and_collect_error = get_option('click_collect_error');
$bloyal_obj = new BloyalController();
$bLoyalcartUid = $bloyal_obj->get_uid();
if (! empty($bLoyalcartUid)) {
if (empty($bloyal_click_and_collect_status) || 1 == $bloyal_click_and_collect_status) {
// $bloyal_obj = new BloyalController();
// $bLoyalcartUid = $bloyal_obj->get_uid();
$loyalty_engine_api_url = get_option('loyalty_engine_api_url');
$access_key = get_option('bloyal_access_key');
$action = 'carts/pickuplocations?cartUid=' . $bLoyalcartUid;
// this API use for get the all bLoyal store pickup locations in cart and checkout page bLoyal pickup store shipping method by bLoyal.
$pickup_location_api_url = $loyalty_engine_api_url . '/api/v4/' . $access_key . '/' . $action;
bLoyalLoggerService::write_custom_log("\r\n ========== pickup_location_api_url ============\r\n" . $pickup_location_api_url);
$args = array(
'headers' => array(
'Content-Type' => 'application/json',
),
'method' => 'GET',
'timeout' => 45,
);
$response = wp_remote_get($pickup_location_api_url, $args);
$response_status = wp_remote_retrieve_response_code($response);
$response = wp_remote_retrieve_body($response);
$pickuplocations_data = json_decode($response, true);
$location_error_data = array();
if (isset($pickuplocations_data['status']) && ($pickuplocations_data['status'] == 'success') && (! empty($pickuplocations_data['data']))) {
$stores_data['no'] = 'Select Options';
foreach ($pickuplocations_data['data'] as $key => $value) {
$stores_address = $value['Name'] . ' ' . $value['Address']['Address1'] . ' ' . $value['Address']['City'] . ' ' . $value['Address']['StateName'] . ' ' . $value['Address']['PostalCode'] . ' ' . $value['Address']['CountryName'];
update_option($value['Code'], $stores_address);
$stores_data[$value['Code']] = $value['Name'];
}
}
bLoyalLoggerService::write_custom_log("\r\n ========== pickuplocations_results ============\r\n" . $response);
}
}
}
return $stores_data;
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// Custom function that handle your settings
function bloyal_carrier_settings()
{
try {
$bloyal_shipping_method = '';
$click_and_collect_label = '';
$store_pickup_options = '';
if (is_cart() || (is_checkout())) {
$chosen_shipping_methods = WC()->session->get('chosen_shipping_methods');
$shipping_method = sanitize_key((isset($chosen_shipping_methods[0]) ? $chosen_shipping_methods[0] : ''));
if (strpos($shipping_method, 'bloyal_pickup_store') !== false) {
$click_and_collect_label = get_option('bloyal_click_collect_label');
$store_pickup_options = bloyal_store_pickup_locations_data();
$bloyal_shipping_method = $chosen_shipping_methods[0];
}
}
return array(
'targeted_methods' => array($bloyal_shipping_method), // Your targeted shipping method(s) in this array
'field_id' => 'carrier_name', // Field Id
'field_type' => 'select', // Field type
'field_label' => $click_and_collect_label, // Leave empty value if the first option has a text (see below).
'label' => __('Carrier company', 'woocommerce'), // for validation and as meta key for orders
'field_options' => $store_pickup_options,
);
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// Display the custom checkout field
add_action('woocommerce_after_shipping_rate', 'bloyal_carrier_company_custom_select_field', 20, 2);
function bloyal_carrier_company_custom_select_field($method, $index)
{
try {
// bloyal_store_pickup_locations();
extract(bloyal_carrier_settings()); // Load settings and convert them in variables
$chosen = WC()->session->get('chosen_shipping_methods'); // The chosen methods
$value = WC()->session->get($field_id);
$value = WC()->session->__isset($field_id) ? $value : WC()->checkout->get_value('_' . $field_id);
$options = array(); // Initializing
if (! empty($chosen) && $method->id === $chosen[$index] && in_array($method->id, $targeted_methods)) {
// Start
// modify code to display error message. if store is not available.
if (! empty($field_options)) {
echo '';
// Loop through field otions to add the correct keys
foreach ($field_options as $key => $option_value) {
$option_key = $key == '0' ? '' : $key;
$options[$option_key] = $option_value;
}
woocommerce_form_field(
$field_id,
array(
'type' => $field_type,
'label' => $field_label, // Not required if the first option has a text.
'class' => array('form-row-wide ' . $field_id . '-' . $field_type),
'required' => true,
'options' => $options,
),
$value
);
echo '';
} else {
$bloyal_click_and_collect_error = get_option('click_collect_error');
echo ' ' . $bloyal_click_and_collect_error . '';
}
// End
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// jQuery code (client side) - Ajax sender
add_action('wp_footer', 'bloyal_carrier_company_script_js');
function bloyal_carrier_company_script_js()
{
// Only cart & checkout pages
if (is_cart() || (is_checkout() && ! is_wc_endpoint_url())) :
// Load settings and convert them in variables
extract(bloyal_carrier_settings());
$js_variable = is_cart() ? 'wc_cart_params' : 'wc_checkout_params';
// jQuery Ajax code
?>
session->set($field_id, $value);
WC()->session->set('session_store_code', $storeCode);
WC()->session->set('session_store_address', $storeAddress);
// Send back the data to javascript (json encoded)
if ($field_options != '') {
echo esc_attr($field_label) . ' | ' . esc_attr($field_options[$value]);
}
die();
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// Conditional function for validation
function bloyal_has_carrier_field()
{
try {
$settings = bloyal_carrier_settings();
if (! empty($settings['targeted_methods'][0])) {
return array_intersect(WC()->session->get('chosen_shipping_methods'), $settings['targeted_methods']);
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// Validate the custom selection field
add_action('woocommerce_checkout_process', 'bloyal_carrier_company_checkout_validation');
function bloyal_carrier_company_checkout_validation()
{
try {
// Load settings and convert them in variables
extract(bloyal_carrier_settings());
$click_and_collect_label = 'Please select a ' . get_option('bloyal_click_collect_label') . '.';
if (bloyal_has_carrier_field() && isset($_POST[$field_id]) && empty($_POST[$field_id])) {
wc_add_notice(
sprintf(
__($click_and_collect_label, 'woocommerce'),
'' . $field_label . ''
),
'error'
);
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// Helper function to mask sensitive data in logs for security
function bloyal_mask_cart_uid_for_log($cart_uid)
{
if (empty($cart_uid)) {
return '[EMPTY]';
}
// If it's too short, just mask it entirely
if (strlen($cart_uid) < 8) {
return '[MASKED]';
}
// Show first 8 characters and mask the rest for security
// This allows debugging while protecting sensitive data
return substr($cart_uid, 0, 8) . '...***';
}
// Helper function to get cart_uid from multiple sources (with fallbacks)
function bloyal_get_cart_uid_with_fallbacks()
{
try {
// Priority 1: third_party_cardId (from external integrations)
$third_party_cart_uid = WC()->session ? WC()->session->get('third_party_cardId') : null;
if (!empty($third_party_cart_uid)) {
return $third_party_cart_uid;
}
// Priority 2: bloyal_uid session (standard bLoyal session)
if (WC()->session) {
$bloyal_obj = new BloyalController();
$cart_uid = $bloyal_obj->get_uid();
if (!empty($cart_uid)) {
return $cart_uid;
}
}
// Priority 3: bloyal_cart_data session (fallback when bloyal_uid is lost)
// This is critical when plugin is deactivated or session is cleared
if (WC()->session) {
$bloyal_cart_data = WC()->session->get('bloyal_cart_data');
if (!empty($bloyal_cart_data) && isset($bloyal_cart_data->Cart->Uid)) {
$cart_uid_from_data = $bloyal_cart_data->Cart->Uid;
if (!empty($cart_uid_from_data)) {
bLoyalLoggerService::write_custom_log("\r\n ==========Retrieved cart_uid from bloyal_cart_data session (fallback)============\r\n" . "Cart UID: " . bloyal_mask_cart_uid_for_log($cart_uid_from_data) . "\r\n---------------\r\n", 1);
return $cart_uid_from_data;
}
}
}
return '';
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log("Error in bloyal_get_cart_uid_with_fallbacks: " . $e->getMessage(), 3);
return '';
}
}
// Save cart_uid early when CalculateCart returns (before checkout)
// This ensures cart_uid is captured as early as possible
add_action('woocommerce_before_calculate_totals', 'bloyal_save_cart_uid_early', 10, 1);
function bloyal_save_cart_uid_early($cart)
{
try {
if (!WC()->session) {
return;
}
// Get cart_uid from bloyal_cart_data if available
$bloyal_cart_data = WC()->session->get('bloyal_cart_data');
if (!empty($bloyal_cart_data) && isset($bloyal_cart_data->Cart->Uid)) {
$cart_uid = $bloyal_cart_data->Cart->Uid;
if (!empty($cart_uid)) {
// Store in a persistent session key for later recovery
WC()->session->set('bloyal_early_cart_uid', $cart_uid);
bLoyalLoggerService::write_custom_log("\r\n ==========Saved cart_uid early (before_calculate_totals)============\r\n" . "Cart UID: " . bloyal_mask_cart_uid_for_log($cart_uid) . "\r\n---------------\r\n", 1);
}
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// Save cart_uid to order metadata early (before session might be lost when user creates account)
add_action('woocommerce_checkout_create_order', 'bloyal_save_cart_uid_to_order_meta', 20, 1);
function bloyal_save_cart_uid_to_order_meta($order)
{
try {
// Use helper function with multiple fallbacks
$cart_uid = bloyal_get_cart_uid_with_fallbacks();
// Additional fallback: Check early saved cart_uid
if (empty($cart_uid) && WC()->session) {
$cart_uid = WC()->session->get('bloyal_early_cart_uid');
}
if (!empty($cart_uid)) {
// Save cart_uid to order metadata for later retrieval (especially when session is lost)
$order->update_meta_data('_cart_uid', $cart_uid);
$order_id = $order->get_id();
// If order ID exists, also save directly to postmeta table for backoffice connector compatibility
// This ensures cart_uid is always persisted even if CommitCart fails
if ($order_id > 0) {
bloyal_save_cart_uid_to_postmeta($order_id, $cart_uid);
} else {
// Order ID not yet available, will be saved via woocommerce_new_order hook
// Store cart_uid in session temporarily to retrieve it later
if (WC()->session) {
WC()->session->set('bloyal_pending_cart_uid', $cart_uid);
}
}
bLoyalLoggerService::write_custom_log("\r\n ==========Saved cart_uid to order metadata during checkout_create_order============\r\n" . "Order ID: " . $order_id . ", Cart UID: " . bloyal_mask_cart_uid_for_log($cart_uid) . "\r\n---------------\r\n", 1);
// CON-182: the CartUID session keys are deliberately NOT cleared here.
// Clearing them at checkout_create_order (i.e. before payment) meant that a second
// Place Order submission on the same session started a brand-new bLoyal cart, which
// never went through shipping calculation and committed with $0 shipping (see FCW
// orders 442609/442610). They are cleared after a successful commit in
// PromotionClassController::bloyal_commit_cart() and again on woocommerce_thankyou,
// plus on woocommerce_cart_emptied below, which ties their lifetime to the cart.
} else {
bLoyalLoggerService::write_custom_log("\r\n ==========WARNING: cart_uid is empty during checkout_create_order============\r\n" . "Order ID: " . $order->get_id() . "\r\n---------------\r\n", 2);
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// CON-182: tie the CartUID session lifetime to the cart itself. This covers the concern
// CON-27 was addressing (a stale CartUID surviving when the order-received page never
// loads) without destroying the CartUID for a retry of the same cart. WooCommerce empties
// the cart on the order-received page (wc_clear_cart_after_payment) and when the shopper
// clears it. CommitCart falls back to the _cart_uid order meta when the session is empty.
add_action('woocommerce_cart_emptied', 'bloyal_clear_cart_uid_on_cart_emptied');
function bloyal_clear_cart_uid_on_cart_emptied()
{
try {
if (! WC()->session) {
return;
}
WC()->session->__unset('bloyal_uid');
WC()->session->__unset('bloyal_early_cart_uid');
bLoyalLoggerService::write_custom_log("\r\n ========== Cleared CartUID session keys on cart_emptied ============\r\n", 1);
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// Save cart_uid to postmeta table when order is created (after order ID is available)
add_action('woocommerce_new_order', 'bloyal_save_cart_uid_on_order_created', 10, 1);
function bloyal_save_cart_uid_on_order_created($order_id)
{
try {
$cart_uid = '';
// Priority 1: Check if we have a pending cart_uid from checkout_create_order hook
$pending_cart_uid = WC()->session ? WC()->session->get('bloyal_pending_cart_uid') : null;
if (!empty($pending_cart_uid)) {
$cart_uid = $pending_cart_uid;
if (WC()->session) {
WC()->session->__unset('bloyal_pending_cart_uid');
}
bLoyalLoggerService::write_custom_log("\r\n ==========Retrieved pending cart_uid from session after order creation============\r\n" . "Order ID: " . $order_id . ", Cart UID: " . bloyal_mask_cart_uid_for_log($cart_uid) . "\r\n---------------\r\n", 1);
}
// Priority 2: Try to get cart_uid from order metadata
if (empty($cart_uid)) {
$order = new WC_Order($order_id);
$cart_uid = $order->get_meta('_cart_uid', true);
if (!empty($cart_uid)) {
bLoyalLoggerService::write_custom_log("\r\n ==========Retrieved cart_uid from order metadata after order creation============\r\n" . "Order ID: " . $order_id . ", Cart UID: " . bloyal_mask_cart_uid_for_log($cart_uid) . "\r\n---------------\r\n", 1);
}
}
// Priority 3: Fallback to session sources (bloyal_cart_data, bloyal_uid, etc.)
if (empty($cart_uid)) {
$cart_uid = bloyal_get_cart_uid_with_fallbacks();
if (!empty($cart_uid)) {
bLoyalLoggerService::write_custom_log("\r\n ==========Retrieved cart_uid from session fallbacks after order creation============\r\n" . "Order ID: " . $order_id . ", Cart UID: " . bloyal_mask_cart_uid_for_log($cart_uid) . "\r\n---------------\r\n", 1);
}
}
// Save to postmeta if we found a cart_uid
if (!empty($cart_uid)) {
bloyal_save_cart_uid_to_postmeta($order_id, $cart_uid);
bLoyalLoggerService::write_custom_log("\r\n ==========Saved cart_uid to postmeta after order creation============\r\n" . "Order ID: " . $order_id . ", Cart UID: " . bloyal_mask_cart_uid_for_log($cart_uid) . "\r\n---------------\r\n", 1);
} else {
bLoyalLoggerService::write_custom_log("\r\n ==========WARNING: cart_uid is empty after order creation============\r\n" . "Order ID: " . $order_id . "\r\n---------------\r\n", 2);
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// Final verification hook - last resort to save cart_uid
add_action('woocommerce_checkout_order_processed', 'bloyal_final_cart_uid_save', 99, 1);
function bloyal_final_cart_uid_save($order_id)
{
try {
// First, verify if cart_uid already exists
$order = new WC_Order($order_id);
$existing_cart_uid = $order->get_meta('_cart_uid', true);
if (!empty($existing_cart_uid)) {
// Verify it's in postmeta table
global $wpdb;
$db_table_name = $wpdb->prefix . 'postmeta';
$existing_meta = $wpdb->get_var($wpdb->prepare(
"SELECT meta_id FROM $db_table_name WHERE post_id = %d AND meta_key = '_cart_uid'",
$order_id
));
if ($existing_meta) {
// Already saved, nothing to do
bLoyalLoggerService::write_custom_log("\r\n ==========Final verification: cart_uid already saved============\r\n" . "Order ID: " . $order_id . ", Cart UID: " . bloyal_mask_cart_uid_for_log($existing_cart_uid) . "\r\n---------------\r\n", 1);
return;
} else {
// In metadata but not in postmeta - save it
bloyal_save_cart_uid_to_postmeta($order_id, $existing_cart_uid);
bLoyalLoggerService::write_custom_log("\r\n ==========Final save: cart_uid was in metadata but not in postmeta, saved now============\r\n" . "Order ID: " . $order_id . ", Cart UID: " . bloyal_mask_cart_uid_for_log($existing_cart_uid) . "\r\n---------------\r\n", 1);
return;
}
}
// cart_uid missing - try to recover from all sources
$cart_uid = bloyal_get_cart_uid_with_fallbacks();
// Additional fallback: Check early saved cart_uid
if (empty($cart_uid) && WC()->session) {
$cart_uid = WC()->session->get('bloyal_early_cart_uid');
}
if (!empty($cart_uid)) {
// Save to both metadata and postmeta
$order->update_meta_data('_cart_uid', $cart_uid);
$order->save();
bloyal_save_cart_uid_to_postmeta($order_id, $cart_uid);
bLoyalLoggerService::write_custom_log("\r\n ==========Final save: Recovered and saved cart_uid (last resort)============\r\n" . "Order ID: " . $order_id . ", Cart UID: " . bloyal_mask_cart_uid_for_log($cart_uid) . "\r\n---------------\r\n", 1);
} else {
bLoyalLoggerService::write_custom_log("\r\n ==========ERROR: cart_uid could not be recovered in final hook============\r\n" . "Order ID: " . $order_id . "\r\n---------------\r\n", 3);
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log("Error in bloyal_final_cart_uid_save: " . $e->getMessage(), 3);
}
}
// Helper function to save cart_uid to postmeta table (consistent with bloyal_commit_cart logic)
function bloyal_save_cart_uid_to_postmeta($order_id, $cart_uid)
{
try {
global $wpdb;
// Validate and sanitize inputs
$order_id = absint($order_id); // Ensure integer and positive
$cart_uid = sanitize_text_field($cart_uid); // Sanitize cart_uid string
if (empty($order_id) || empty($cart_uid)) {
return;
}
// Use esc_sql for table name (though $wpdb->prefix is trusted, this is best practice)
$db_table_name = $wpdb->prefix . 'postmeta';
// Check if cart_uid already exists for this order
$existing_cart_uid_query = $wpdb->prepare(
"SELECT meta_id FROM `{$db_table_name}` WHERE post_id = %d AND meta_key = %s",
$order_id,
'_cart_uid'
);
$existing_meta = $wpdb->get_var($existing_cart_uid_query);
if ($existing_meta) {
// Update existing cart_uid entry
$update_query = $wpdb->prepare(
"UPDATE `{$db_table_name}` SET meta_value = %s WHERE post_id = %d AND meta_key = %s",
$cart_uid,
$order_id,
'_cart_uid'
);
$wpdb->query($update_query);
bLoyalLoggerService::write_custom_log("\r\n ==========Updated cart_uid in postmeta table============\r\n" . "Order ID: " . $order_id . ", Cart UID: " . bloyal_mask_cart_uid_for_log($cart_uid) . "\r\n---------------\r\n", 1);
} else {
// Insert new cart_uid entry
$wpdb->insert(
$db_table_name,
array(
'post_id' => $order_id,
'meta_key' => '_cart_uid',
'meta_value' => $cart_uid,
),
array('%d', '%s', '%s')
);
bLoyalLoggerService::write_custom_log("\r\n ==========Inserted cart_uid into postmeta table============\r\n" . "Order ID: " . $order_id . ", Cart UID: " . bloyal_mask_cart_uid_for_log($cart_uid) . "\r\n---------------\r\n", 1);
}
// Also update any orphaned cart_uid entries (from before order was created)
$orphan_update_query = $wpdb->prepare(
"UPDATE `{$db_table_name}` SET post_id = %d WHERE meta_value = %s AND meta_key = %s AND (post_id = 0 OR post_id IS NULL)",
$order_id,
$cart_uid,
'_cart_uid'
);
$wpdb->query($orphan_update_query);
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log("Error saving cart_uid to postmeta: " . $e->getMessage(), 3);
}
}
// Save custom field as order meta data
add_action('woocommerce_checkout_create_order', 'bloyal_save_carrier_company_as_order_meta', 30, 1);
function bloyal_save_carrier_company_as_order_meta($order)
{
try {
// Load settings and convert them in variables
extract(bloyal_carrier_settings());
if (isset($_POST[$field_id]) && $_POST[$field_id] != null) {
$store_pickup_address = sanitize_text_field($field_options[sanitize_key($_POST[$field_id])] ?? '') . ', ' . esc_html(WC()->session->get('session_store_address'));
if (bloyal_has_carrier_field() && isset($_POST[$field_id]) && ! empty($_POST[$field_id])) {
$order->update_meta_data('_' . $field_id, $store_pickup_address);
WC()->session->__unset($field_id); // remove session variable
}
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// Display custom field in admin order pages
add_action('woocommerce_admin_order_data_after_shipping_address', 'bloyal_admin_order_display_carrier_company', 30, 1);
function bloyal_admin_order_display_carrier_company($order)
{
try {
// Load settings and convert them in variables
extract(bloyal_carrier_settings());
$carrier = $order->get_meta('_' . $field_id); // Get carrier company
if (! empty($carrier)) {
// Display
$field_label = get_option('bloyal_click_collect_label');
echo '' . esc_attr($field_label) . ': ' . esc_attr($carrier) . '
';
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// Display carrier company after shipping line everywhere (orders and emails)
add_filter('woocommerce_get_order_item_totals', 'bloyal_display_carrier_company_on_order_item_totals', 1000, 3);
function bloyal_display_carrier_company_on_order_item_totals($total_rows, $order, $tax_display)
{
try {
// Load settings and convert them in variables
extract(bloyal_carrier_settings());
$carrier = $order->get_meta('_' . $field_id); // Get carrier company
if (! empty($carrier)) {
$new_total_rows = array();
// Loop through order total rows
foreach ($total_rows as $key => $values) {
$new_total_rows[$key] = $values;
// Inserting the carrier company under shipping method
if ($key === 'shipping') {
$new_total_rows[$field_id] = array(
'label' => $field_label,
'value' => $carrier,
);
}
}
return $new_total_rows;
}
return $total_rows;
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// end Pickup at Store functionality
// bLoyal log download function
add_action('wp_ajax_bloyal_log_download', 'bloyal_log_download'); // Log download on bLoyal admin
function bloyal_log_download()
{
try {
$filename = BLOYAL_UPLOAD_DIR_BASEPATH . '/bLoyal_log_file.txt';
if (file_exists($filename)) {
// Define header information
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Cache-Control: no-cache, must-revalidate');
header('Expires: 0');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header('Content-Length: ' . filesize($filename));
header('Pragma: public');
// Clear system output buffer
flush();
// Read the size of the file
readfile($filename);
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// End bLoyal log download function
// bLoyal snippets log download function
add_action('wp_ajax_bloyal_snippets_log_download', 'bloyal_snippets_log_download'); // Log download on bLoyal admin
function bloyal_snippets_log_download()
{
try {
$filename = BLOYAL_UPLOAD_DIR_BASEPATH . '/bLoyal_snippets_log_file.txt';
if (file_exists($filename)) {
// Define header information
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Cache-Control: no-cache, must-revalidate');
header('Expires: 0');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header('Content-Length: ' . filesize($filename));
header('Pragma: public');
// Clear system output buffer
flush();
// Read the size of the file
readfile($filename);
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// End bLoyal snippets log download function
// bLoyal log delete function
add_action('wp_ajax_bloyal_log_delete', 'bloyal_log_delete');
function bloyal_log_delete()
{
try {
$filename = BLOYAL_UPLOAD_DIR_BASEPATH . '/bLoyal_log_file.txt';
if (file_exists($filename)) {
$delete_log = wp_delete_file($filename);
$response = wp_send_json(
array(
'log_status' => true,
'message' => 'Log file has been deleted.',
)
);
} else {
$response = wp_send_json(
array(
'log_status' => false,
'message' => 'Log file not available..',
)
);
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// bLoyal snippets log delete function
add_action('wp_ajax_bloyal_snippets_log_delete', 'bloyal_snippets_log_delete');
function bloyal_snippets_log_delete()
{
try {
$filename = BLOYAL_UPLOAD_DIR_BASEPATH . '/bLoyal_snippets_log_file.txt';
if (file_exists($filename)) {
$delete_log = wp_delete_file($filename);
$response = wp_send_json(
array(
'log_status' => true,
'message' => 'Log file has been deleted.',
)
);
} else {
$response = wp_send_json(
array(
'log_status' => false,
'message' => 'Log file not available..',
)
);
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// register the ajax action for authenticated users
add_action('wp_ajax_bloyal_remove_custom_coupon', 'bloyal_remove_custom_coupon');
// register the ajax action for unauthenticated users
add_action('wp_ajax_nopriv_bloyal_remove_custom_coupon', 'bloyal_remove_custom_coupon');
// handle the ajax request
function bloyal_remove_custom_coupon()
{
try {
$bloyal_obj = new BloyalController();
$bloyal_obj->bloyal_remove_all_bloyal_coupons();
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// code to disable store payment method on checkout page if user is not logged
function rp_filter_gateways($args)
{
try {
if (! is_user_logged_in() && isset($args['bloyal_stored_payment_method'])) {
unset($args['bloyal_stored_payment_method']);
}
return $args;
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
add_action('woocommerce_available_payment_gateways', 'rp_filter_gateways');
// add custom line item in to the cart
function bLoyal_add_to_cart_custom_line_item($line_data, $cart_object)
{
try {
foreach ($line_data as $index => $line) {
if (isset($line->ProductCode) && $line->ExternalId == null) {
// code to update price of egiftcard web snippet as per the getCart API response start
WC()->session->set('gift_item_price', $line->Price);
WC()->session->set('gift_item_sku', $line->ProductCode);
// code to update price of egiftcard web snippet as per the getCart API response end
$bLoyalCustomProduct = get_product_by_sku($line->ProductCode);
if (! empty($bLoyalCustomProduct)) {
$product_id = $bLoyalCustomProduct->get_id();
$product_cart_id = WC()->cart->generate_cart_id($product_id);
if (! WC()->cart->find_product_in_cart($product_cart_id)) {
WC()->cart->add_to_cart($product_id);
}
}
}
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
function get_product_by_sku($sku)
{
try {
global $wpdb;
$product_id = $wpdb->get_var($wpdb->prepare("SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $sku));
if ($product_id) {
return new WC_Product($product_id);
}
return null;
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// set COD payment method by default
add_action('template_redirect', 'define_default_payment_gateway');
function define_default_payment_gateway()
{
try {
if (is_checkout() && ! is_wc_endpoint_url()) {
// HERE define the default payment gateway ID
$default_payment_id = 'payment_method_cod';
WC()->session->set('chosen_payment_method', $default_payment_id);
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// we added this code to hide store pickup after ship_to_different_address selection on checkout page
function unset_bloyal_pickup_store_shipping_method($rates)
{
try {
// Specify the shipping method ID you want to unset
foreach ($rates as $rate_id => $rate_val) {
if ('bloyal_pickup_store' === $rate_val->get_method_id()) {
unset($rates[$rate_id]);
}
}
return $rates;
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// code to update cart page on shipping method change
// AJAX handler for updating shipping method in cart page
add_action('wp_ajax_update_shipping_method_cart', 'update_shipping_method_cart_callback');
add_action('wp_ajax_nopriv_update_shipping_method_cart', 'update_shipping_method_cart_callback');
function update_shipping_method_cart_callback()
{
try {
if (isset($_POST['shipping_method'])) {
$chosen_shipping_methods = WC()->session->get('chosen_shipping_methods');
$chosen_shipping_methods[0] = wc_clean($_POST['shipping_method']);
WC()->session->set('chosen_shipping_methods', $chosen_shipping_methods);
// Calculate shipping cost and update totals
WC()->cart->calculate_shipping();
WC()->cart->calculate_totals();
// Get updated cart fragments
$fragments = WC_AJAX::get_refreshed_fragments();
// Return fragments as JSON response
wp_send_json_success(
array(
'fragments' => apply_filters('woocommerce_update_cart_fragments', $fragments),
)
);
} else {
wp_send_json_error('No shipping method provided');
}
exit;
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
}
}
// Override mini-cart item price display
function custom_mini_cart_item_price($product_price, $cart_item, $cart_item_key)
{
// Check if current page is neither cart nor checkout
if (! (is_cart() || is_checkout())) {
$product_id = $cart_item['product_id'];
$product = wc_get_product($product_id);
$product_sku = strtolower($product->get_sku());
$bloyal_cart_object = WC()->session->get('bloyal_cart_data');
if (isset($bloyal_cart_object->Cart->Lines)) {
$custom_price = array();
foreach ($bloyal_cart_object->Cart->Lines as $line) {
$sku = strtolower($line->ProductCode);
$custom_price[$sku] = $line->NetPrice ?? $line->Price;
}
// $customProductPrice = $custom_price[ $product_sku ] ?? null;
return wc_price($custom_price[$product_sku]) ?? $product_price;
}
} else {
try {
return $product_price;
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
}
add_filter('woocommerce_cart_item_price', 'custom_mini_cart_item_price', 20, 10);
// web snippets for egiftcard complete developed by Chetu Developer
add_action('wp_ajax_nopriv_bloyal_web_snippets_complete', 'bloyal_web_snippets_complete');
add_action('wp_ajax_bloyal_web_snippets_complete', 'bloyal_web_snippets_complete');
function bloyal_web_snippets_complete()
{
try {
if (isset($_POST['cart_uid']) && ! empty($_POST['cart_uid'])) {
$access_key = get_option('bloyal_access_key');
$cartUid = $_POST['cart_uid'];
$bloyal_snippet_obj = new BloyalSnippetsController();
$new_snippets_action_url = 'carts?cartUid=' . $cartUid;
$bloyal_web_snippet_getcart_object = $bloyal_snippet_obj->send_curl_request('', $new_snippets_action_url, 'loyaltyengine', 0);
bLoyalLoggerService::write_custom_log("\r\n ==========Response Cart API call============\r\n" . json_encode($bloyal_web_snippet_getcart_object) . "\r\n---------------\r\n");
// code to pass UID from getCart response to calculateCart request start
$cart_uid = isset($bloyal_web_snippet_getcart_object->data->Cart->Uid) ? $bloyal_web_snippet_getcart_object->data->Cart->Uid : '';
if ($cart_uid) {
$woo_session_id = WC()->session->get_customer_id();
WC()->session->set(
'bloyal_uid',
array(
'u_id' => $cart_uid,
'session_id' => $woo_session_id,
)
);
// code to pass UID from getCart response to calculateCart request end
$blwebsnippetLineData = $bloyal_web_snippet_getcart_object->data->Cart->Lines;
if (isset($blwebsnippetLineData) && !empty($blwebsnippetLineData)) {
bLoyal_add_to_cart_custom_line_item($blwebsnippetLineData, $cart_object);
$cart_url = wc_get_cart_url();
$bloyal_cartUid = array('bL_cartUid' => $cart_uid, 'redirect' => $cart_url);
}
wp_send_json($bloyal_cartUid);
}
}
wp_die();
} catch (Exception $ex) {
bLoyalLoggerService::write_custom_log($ex->getMessage(), 3);
}
}
add_action('wp_ajax_generate_bloyal_session_key', 'generate_bloyal_session_key');
add_action('wp_ajax_nopriv_generate_bloyal_session_key', 'generate_bloyal_session_key');
function generate_bloyal_session_key()
{
try {
if (isset($_POST['is_logged_in']) && ! empty($_POST['is_logged_in'])) {
$user = wp_get_current_user();
$user_id = $user->ID;
$user_email = $user->user_email;
$bloyal_snippets_obj = new BloyalSnippetsController();
$user_details = $bloyal_snippets_obj->get_new_customer_details_from_wbdb();
$woo_session_id = WC()->session->get_customer_id();
$action = 'resolvedcustomersession?EmailAddress=' . $user_email . '&ExternalId=' . $user_id;
$response_resolve_customer = $bloyal_snippets_obj->send_curl_request('', $action, 'loyaltyengine', 0);
if ('success' === $response_resolve_customer->status && (isset($response_resolve_customer->data->SessionKey))) {
$bloyal_sk = array(
'bloyal_session_key' => $response_resolve_customer->data->SessionKey,
'session_id' => $woo_session_id,
);
if ($user_details['Customer']['FirstName'] == '' || $user_details['Customer']['FirstName'] == null && $response_resolve_customer->data->Customer->FirstName != '' && $response_resolve_customer->data->Customer->FirstName != null) {
update_user_meta($user_details['Customer']['ExternalId'], 'first_name', $response_resolve_customer->data->Customer->FirstName);
update_user_meta($user_details['Customer']['ExternalId'], 'last_name', $response_resolve_customer->data->Customer->LastName);
}
if ($user_details['Customer']['Address1'] == '' || $user_details['Customer']['Address1'] == null && $response_resolve_customer->data->Customer->Address->Address1 != '' && $response_resolve_customer->data->Customer->Address->Address1 != null) {
update_user_meta($user_details['Customer']['ExternalId'], 'billing_address_1', $response_resolve_customer->data->Customer->Address->Address1);
update_user_meta($user_details['Customer']['ExternalId'], 'billing_address_2', $response_resolve_customer->data->Customer->Address->Address2);
update_user_meta($user_details['Customer']['ExternalId'], 'billing_city', $response_resolve_customer->data->Customer->Address->City);
update_user_meta($user_details['Customer']['ExternalId'], 'billing_state', $response_resolve_customer->data->Customer->Address->State);
update_user_meta($user_details['Customer']['ExternalId'], 'billing_postcode', $response_resolve_customer->data->Customer->Address->PostalCode);
update_user_meta($user_details['Customer']['ExternalId'], 'billing_country', $response_resolve_customer->data->Customer->Address->Country);
}
if (empty($response_resolve_customer->data->Customer->ExternalId)) {
$update_customer_request = $bloyal_snippets_obj->get_customer_update_request($response_resolve_customer->data->Customer);
$device_context = $bloyal_snippets_obj->send_curl_request('', 'contextdevices', 'loyaltyengine', 0);
$device_code = !empty($device_context) && isset($device_context->data->Code) ? $device_context->data->Code : '';
if (!empty($device_code)) {
$action = $device_code . '/Customers?sessionKey=' . $response_resolve_customer->data->SessionKey;
$response_update_customer = $bloyal_snippets_obj->send_curl_request($update_customer_request, $action, 'websnippet', 1);
}
}
wp_send_json($bloyal_sk);
} elseif (!isset($response_resolve_customer->data->SessionKey)) {
$action = 'customers/commands/saves';
$response = $bloyal_snippets_obj->send_curl_request($user_details, $action, 'loyaltyengine', 1);
$action = 'resolvedcustomersession?EmailAddress=' . urlencode($user_details['Customer']['EmailAddress']) . '&ExternalId=' . $user_details['Customer']['ExternalId'];
$response_resolve_customer = $bloyal_snippets_obj->send_curl_request('', $action, 'loyaltyengine', 0);
if ('success' === $response_resolve_customer->status && isset($response_resolve_customer->data->SessionKey)) {
$bloyal_sk = array(
'bloyal_session_key' => $response_resolve_customer->data->SessionKey,
'session_id' => $woo_session_id,
);
wp_send_json($bloyal_sk);
} else {
// Handle error case
$bloyal_sk = array(
'bloyal_session_key' => null,
'session_id' => $woo_session_id,
);
wp_send_json($bloyal_sk);
}
} else {
// Handle error case when status is not success
$bloyal_sk = array(
'bloyal_session_key' => null,
'session_id' => $woo_session_id,
);
wp_send_json($bloyal_sk);
}
} else {
// User not logged in
$bloyal_sk = array(
'bloyal_session_key' => null,
'session_id' => WC()->session->get_customer_id(),
);
wp_send_json($bloyal_sk);
}
} catch (Exception $e) {
bLoyalLoggerService::write_custom_log($e->getMessage(), 3);
$bloyal_sk = array(
'bloyal_session_key' => null,
'session_id' => WC()->session ? WC()->session->get_customer_id() : '',
);
wp_send_json($bloyal_sk);
}
wp_die();
}
?>