namespace, '/coupons', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_coupons' ), 'permission_callback' => array( $this, 'check_permission' ), ), ) ); // Apply coupon to WooCommerce cart. register_rest_route( $this->namespace, '/coupons/apply', array( array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'apply_coupon' ), 'permission_callback' => array( $this, 'check_permission' ), 'args' => array( 'code' => array( 'required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), ), ), ) ); } /** * Get customer coupons, available deals, and next unlock milestone. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response */ public function get_coupons( $request ) { $customer_id = $this->get_customer_id(); $customer = new WC_Customer( $customer_id ); $user_email = strtolower( $customer->get_email() ); $total_spent = (float) $customer->get_total_spent(); $order_count = (int) $customer->get_order_count(); // Fetch all published coupons. $coupon_posts = get_posts( array( 'post_type' => 'shop_coupon', 'post_status' => 'publish', 'posts_per_page' => 100, 'orderby' => 'date', 'order' => 'DESC', ) ); $available_coupons = array(); $potential_unlocks = array(); $now = current_time( 'timestamp' ); foreach ( $coupon_posts as $post ) { $coupon = new WC_Coupon( $post->ID ); $code = $coupon->get_code(); // Expiry check. $expires = $coupon->get_date_expires(); if ( $expires && $expires->getTimestamp() < $now ) { continue; } // Email restrictions check. $email_restrictions = array_map( 'strtolower', $coupon->get_email_restrictions() ); if ( ! empty( $email_restrictions ) && ! in_array( $user_email, $email_restrictions, true ) ) { continue; } // Overall usage limit check. $usage_limit = $coupon->get_usage_limit(); $usage_count = $coupon->get_usage_count(); if ( $usage_limit > 0 && $usage_count >= $usage_limit ) { continue; } // Per-user usage limit check. $usage_per_user = $coupon->get_usage_limit_per_user(); if ( $usage_per_user > 0 ) { $used_by_user = count( $coupon->get_used_by() ); $user_usage = 0; foreach ( $coupon->get_used_by() as $user ) { if ( (int) $user === $customer_id || strtolower( $user ) === $user_email ) { $user_usage++; } } if ( $user_usage >= $usage_per_user ) { continue; } } // Format discount string. $discount_type = $coupon->get_discount_type(); $amount = (float) $coupon->get_amount(); $min_spend = (float) $coupon->get_minimum_amount(); if ( 'percent' === $discount_type ) { $formatted_discount = $amount . '% ' . __( 'OFF', 'advanced-customer-account' ); } else { $formatted_discount = $this->format_price( $amount ) . ' ' . __( 'OFF', 'advanced-customer-account' ); } $days_remaining = null; $formatted_expiry = __( 'Never expires', 'advanced-customer-account' ); if ( $expires ) { $days_remaining = max( 0, ceil( ( $expires->getTimestamp() - $now ) / DAY_IN_SECONDS ) ); $formatted_expiry = $this->format_date( $expires->date( 'Y-m-d' ) ); } $coupon_data = array( 'id' => $coupon->get_id(), 'code' => strtoupper( $code ), 'description' => $coupon->get_description() ?: __( 'Special customer discount coupon', 'advanced-customer-account' ), 'discount_type' => $discount_type, 'amount' => $amount, 'formatted_discount' => $formatted_discount, 'min_spend' => $min_spend, 'formatted_min_spend'=> $min_spend > 0 ? $this->format_price( $min_spend ) : null, 'expires_at' => $formatted_expiry, 'days_remaining' => $days_remaining, 'free_shipping' => $coupon->get_free_shipping(), ); // Check if this is an unlocked/active coupon or a next unlock milestone. if ( $min_spend > 0 && $total_spent < $min_spend ) { $potential_unlocks[] = $coupon_data; } else { $available_coupons[] = $coupon_data; } } // Calculate "Next Coupon to Unlock" (Gamification milestone). $settings = get_option( 'aca_settings', array() ); $rewards_enabled = isset( $settings['rewards_enabled'] ) ? (bool) $settings['rewards_enabled'] : true; $next_coupon = null; if ( $rewards_enabled ) { $rewards_type = isset( $settings['rewards_type'] ) ? $settings['rewards_type'] : 'auto'; $target_orders = isset( $settings['rewards_target_orders'] ) ? max( 1, absint( $settings['rewards_target_orders'] ) ) : 10; $target_spend = isset( $settings['rewards_target_spend'] ) ? max( 1, floatval( $settings['rewards_target_spend'] ) ) : 250; $discount_label = ! empty( $settings['rewards_discount_label'] ) ? sanitize_text_field( $settings['rewards_discount_label'] ) : '15% OFF'; $coupon_code = ! empty( $settings['rewards_coupon_code'] ) ? strtoupper( sanitize_text_field( $settings['rewards_coupon_code'] ) ) : 'VIP15'; $custom_desc = ! empty( $settings['rewards_description'] ) ? sanitize_text_field( $settings['rewards_description'] ) : __( 'Unlock our exclusive VIP Club discount with your orders!', 'advanced-customer-account' ); if ( 'spend' === $rewards_type ) { // Based on configured total spend. $needed = max( 0, $target_spend - $total_spent ); $pct = min( 100, round( ( $total_spent / $target_spend ) * 100 ) ); $next_coupon = array( 'code' => $coupon_code, 'formatted_discount' => $discount_label, 'target_spend' => $this->format_price( $target_spend ), 'current_spend' => $this->format_price( $total_spent ), 'needed_amount' => $this->format_price( $needed ), 'progress_pct' => $pct, 'title' => $needed > 0 ? sprintf( __( 'Spend %s more to unlock %s!', 'advanced-customer-account' ), $this->format_price( $needed ), $discount_label ) : sprintf( __( 'Congratulations! You unlocked %s!', 'advanced-customer-account' ), $discount_label ), 'description' => $custom_desc, ); } elseif ( 'orders' === $rewards_type ) { // Based on configured fixed order count. $orders_needed = max( 0, $target_orders - $order_count ); $pct = min( 100, round( ( $order_count / $target_orders ) * 100 ) ); $next_coupon = array( 'code' => $coupon_code, 'formatted_discount' => $discount_label, 'target_spend' => sprintf( _n( '%d Order', '%d Orders', $target_orders, 'advanced-customer-account' ), $target_orders ), 'current_spend' => sprintf( _n( '%d Order placed', '%d Orders placed', $order_count, 'advanced-customer-account' ), $order_count ), 'needed_amount' => sprintf( _n( '%d more order', '%d more orders', $orders_needed, 'advanced-customer-account' ), $orders_needed ), 'progress_pct' => $pct, 'title' => $orders_needed > 0 ? sprintf( _n( 'Complete %1$d more order to unlock VIP %2$s!', 'Complete %1$d more orders to unlock VIP %2$s!', $orders_needed, 'advanced-customer-account' ), $orders_needed, $discount_label ) : sprintf( __( 'Congratulations! You completed %d orders and unlocked VIP %s!', 'advanced-customer-account' ), $target_orders, $discount_label ), 'description' => $custom_desc, ); } else { // 'auto': First prioritize WooCommerce coupons with minimum spend. if ( ! empty( $potential_unlocks ) ) { usort( $potential_unlocks, function ( $a, $b ) { return ( $a['min_spend'] - $b['min_spend'] ); } ); $target = $potential_unlocks[0]; $needed = max( 0, $target['min_spend'] - $total_spent ); $pct = $target['min_spend'] > 0 ? min( 100, round( ( $total_spent / $target['min_spend'] ) * 100 ) ) : 100; $next_coupon = array( 'code' => $target['code'], 'formatted_discount' => $target['formatted_discount'], 'target_spend' => $this->format_price( $target['min_spend'] ), 'current_spend' => $this->format_price( $total_spent ), 'needed_amount' => $this->format_price( $needed ), 'progress_pct' => $pct, 'title' => sprintf( __( 'Spend %s more to unlock %s!', 'advanced-customer-account' ), $this->format_price( $needed ), $target['formatted_discount'] ), 'description' => $target['description'], ); } else { // Fallback to configured target orders if no higher min-spend coupon exists. $effective_target = $target_orders; if ( $order_count >= $effective_target ) { // Customer already reached the target orders, adjust to next round tier. $effective_target = ( (int) ceil( ( $order_count + 1 ) / 5 ) ) * 5; } $orders_needed = max( 0, $effective_target - $order_count ); $pct = min( 100, round( ( $order_count / $effective_target ) * 100 ) ); $next_coupon = array( 'code' => $coupon_code, 'formatted_discount' => $discount_label, 'target_spend' => sprintf( _n( '%d Order', '%d Orders', $effective_target, 'advanced-customer-account' ), $effective_target ), 'current_spend' => sprintf( _n( '%d Order placed', '%d Orders placed', $order_count, 'advanced-customer-account' ), $order_count ), 'needed_amount' => sprintf( _n( '%d more order', '%d more orders', $orders_needed, 'advanced-customer-account' ), $orders_needed ), 'progress_pct' => $pct, 'title' => sprintf( _n( 'Complete %1$d more order to unlock VIP %2$s!', 'Complete %1$d more orders to unlock VIP %2$s!', $orders_needed, 'advanced-customer-account' ), $orders_needed, $discount_label ), 'description' => $custom_desc, ); } } } // Get past coupon usage history from customer's orders. $history = $this->get_customer_coupon_history( $customer_id ); return rest_ensure_response( array( 'available' => $available_coupons, 'next_coupon' => $next_coupon, 'history' => $history, 'total_spent' => $this->format_price( $total_spent ), 'order_count' => $order_count, ) ); } /** * Apply coupon directly to WooCommerce cart. * * If cart has items, applies coupon immediately. * If cart is empty, stores coupon in customer session for automatic application upon adding items. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function apply_coupon( $request ) { $code = sanitize_text_field( $request->get_param( 'code' ) ); if ( empty( $code ) ) { return new WP_Error( 'rest_missing_code', __( 'Please provide a coupon code.', 'advanced-customer-account' ), array( 'status' => 400 ) ); } // Ensure WooCommerce session & cart are initialized. if ( null === WC()->session ) { $session_class = apply_filters( 'woocommerce_session_handler', 'WC_Session_Handler' ); WC()->session = new $session_class(); WC()->session->init(); } if ( null === WC()->cart ) { wc_load_cart(); } $coupon = new WC_Coupon( $code ); if ( ! $coupon->get_id() ) { return new WP_Error( 'rest_invalid_coupon', __( 'Coupon code does not exist.', 'advanced-customer-account' ), array( 'status' => 404 ) ); } // 1. Check if already applied to cart. if ( WC()->cart && WC()->cart->has_discount( $code ) ) { return rest_ensure_response( array( 'success' => true, 'message' => sprintf( __( 'Coupon "%s" is already applied to your cart!', 'advanced-customer-account' ), strtoupper( $code ) ), 'cart_url' => wc_get_cart_url(), ) ); } // 2. If Cart is EMPTY: // In WooCommerce, applying a coupon to an empty cart is not allowed directly. // We save the coupon in the session so it auto-applies as soon as any product is added to the cart! if ( ! WC()->cart || WC()->cart->is_empty() ) { if ( WC()->session ) { WC()->session->set( 'aca_pending_coupon', strtoupper( $code ) ); } return rest_ensure_response( array( 'success' => true, 'is_saved' => true, 'message' => sprintf( __( 'Coupon "%s" saved! It will be automatically applied when you add products to your cart.', 'advanced-customer-account' ), strtoupper( $code ) ), 'shop_url' => wc_get_page_permalink( 'shop' ), ) ); } // 3. Cart has items, apply coupon. $applied = WC()->cart->apply_coupon( $code ); if ( false === $applied ) { // Extract WC notice error. $notices = wc_get_notices( 'error' ); wc_clear_notices(); $raw_msg = ! empty( $notices ) ? wp_strip_all_tags( $notices[0]['notice'] ) : __( 'Coupon could not be applied.', 'advanced-customer-account' ); $error_msg = html_entity_decode( $raw_msg, ENT_QUOTES, 'UTF-8' ); // If notice indicates already applied, return as success rather than error! if ( stripos( $error_msg, 'already applied' ) !== false ) { return rest_ensure_response( array( 'success' => true, 'message' => sprintf( __( 'Coupon "%s" is already applied to your cart!', 'advanced-customer-account' ), strtoupper( $code ) ), 'cart_url' => wc_get_cart_url(), ) ); } return new WP_Error( 'rest_coupon_error', $error_msg, array( 'status' => 400 ) ); } return rest_ensure_response( array( 'success' => true, 'message' => sprintf( __( 'Coupon "%s" applied successfully to your cart!', 'advanced-customer-account' ), strtoupper( $code ) ), 'cart_url' => wc_get_cart_url(), ) ); } /** * Retrieve coupons previously used in customer orders. * * @param int $customer_id Customer ID. * @return array */ private function get_customer_coupon_history( $customer_id ) { $orders = wc_get_orders( array( 'customer_id' => $customer_id, 'limit' => 20, 'status' => array( 'completed', 'processing' ), ) ); $history = array(); foreach ( $orders as $order ) { $coupons = $order->get_coupon_codes(); if ( empty( $coupons ) ) { continue; } $order_date = $order->get_date_created() ? $this->format_date( $order->get_date_created()->date( 'Y-m-d' ) ) : ''; foreach ( $coupons as $code ) { $discount = (float) $order->get_discount_total(); $history[] = array( 'code' => strtoupper( $code ), 'order_id' => $order->get_id(), 'order_number' => $order->get_order_number(), 'discount' => $discount > 0 ? $this->format_price( $discount ) : __( 'Discount applied', 'advanced-customer-account' ), 'date' => $order_date, ); } } return $history; } }