<?php
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
/**
 * RestroPress RP_AJAX. AJAX Event Handlers.
 *
 * @class   RP_AJAX
 * @package RestroPress/Classes
 * @since  2.0
 */
defined( 'ABSPATH' ) || exit;
/**
 * RP_Ajax class.
 */
class RP_AJAX {
  /**
   * Hook in ajax handlers.
   */
  public static function init() {
    add_action( 'init', array( __CLASS__, 'define_ajax' ), 0 );
    add_action( 'template_redirect', array( __CLASS__, 'do_rp_ajax' ), 0 );
    self::add_ajax_events();
  }
  /**
   * Get RP Ajax Endpoint.
   *
   * @param string $request Optional.
   *
   * @return string
   */
  public static function get_endpoint( $request = '' ) {
    return esc_url_raw( apply_filters( 'rp_ajax_get_endpoint', add_query_arg( 'rp-ajax', $request, home_url( '/', 'relative' ) ), $request ) );
  }
  /**
   * Set RP AJAX constant and headers.
   */
  public static function define_ajax() {
    // phpcs:disable
    if ( ! empty( $_GET['rp-ajax'] ) ) {
      rp_maybe_define_constant( 'DOING_AJAX', true );
      rp_maybe_define_constant( 'RP_DOING_AJAX', true );
      if ( ! WP_DEBUG || ( WP_DEBUG && ! WP_DEBUG_DISPLAY ) ) {
        @ini_set( 'display_errors', 0 ); // Turn off display_errors during AJAX events to prevent malformed JSON.
      }
      $GLOBALS['wpdb']->hide_errors();
    }
  }
  /**
   * Send headers for RP Ajax Requests.
   *
   */
  private static function rp_ajax_headers() {
    if ( ! headers_sent() ) {
      send_origin_headers();
      send_nosniff_header();
      rp_nocache_headers();
      header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
      header( 'X-Robots-Tag: noindex' );
      status_header( 200 );
    } elseif ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
      headers_sent( $file, $line );
      trigger_error( "rp_ajax_headers cannot set headers - headers already sent by {$file} on line {$line}", E_USER_NOTICE ); // @codingStandardsIgnoreLine
    }
  }
  /**
   * Check for RP Ajax request and fire action.
   */
  public static function do_rp_ajax() {
    global $wp_query;
    if ( ! empty( $_GET['rp-ajax'] ) ) {
      $wp_query->set( 'rp-ajax', sanitize_text_field( wp_unslash( $_GET['rp-ajax'] ) ) );
    }
    $action = $wp_query->get( 'rp-ajax' );
    if ( $action ) {
      self::rp_ajax_headers();
      $action = sanitize_text_field( $action );
      do_action( 'rp_ajax_' . $action );
      wp_die();
    } // phpcs:enable
  }
  /**
   * Hook in methods - uses WordPress ajax handlers (admin-ajax).
   */
  public static function add_ajax_events() {
    $ajax_events_nopriv = array(
      'show_products',
      'add_to_cart',
      'show_delivery_options',
      'check_service_slot',
      'edit_cart_fooditem',
      'update_cart_items',
      'remove_from_cart',
      'clear_cart',
      'proceed_checkout',
      'get_subtotal',
      'apply_discount',
      'remove_discount',
      'checkout_login',
      'checkout_register',
      'recalculate_taxes',
      'get_states',
      'fooditem_search',
      'checkout_update_service_option',
      'remove_fees_after_empty_cart',
      'reorder',
      "update_modal_on_service_switch",
      'receipt_order_status',
    );
    foreach ( $ajax_events_nopriv as $ajax_event ) {
      add_action( 'wp_ajax_rpress_' . $ajax_event, array( __CLASS__, $ajax_event ) );
      add_action( 'wp_ajax_nopriv_rpress_' . $ajax_event, array( __CLASS__, $ajax_event ) );
      // RP AJAX can be used for frontend ajax requests.
      add_action( 'rp_ajax_' . $ajax_event, array( __CLASS__, $ajax_event ) );
    }
    $ajax_events = array(
      'add_addon',
      'load_addon_child',
      'add_price',
      'add_category',
      'get_order_details',
      'update_order_status',
      'check_for_fooditem_price_variations',
      'admin_order_addon_items',
      'customer_search',
      'user_search',
      'search_users',
      'check_new_orders',
      'activate_addon_license',
      'deactivate_addon_license',
      'show_order_details',
      'more_order_history',
      'delete_user_address',
      'default_user_address'
    );
    foreach ( $ajax_events as $ajax_event ) {
      add_action( 'wp_ajax_rpress_' . $ajax_event, array( __CLASS__, $ajax_event ) );
    }
  }

  /**
   * Check whether the current request can access a frontend order action.
   *
   * Logged-in users can only access their own user-linked orders.
   * Guest orders require a valid payment key that can view the receipt.
   *
   * @since 3.2.8
   *
   * @param int $order_id Payment post ID.
   * @return bool
   */
  private static function can_access_frontend_order_action( $order_id ) {
    $order_id = absint( $order_id );
    if ( $order_id <= 0 || 'rpress_payment' !== get_post_type( $order_id ) ) {
      return false;
    }

    $user          = rpress_get_payment_meta_user_info( $order_id );
    $order_user_id = isset( $user['id'] ) ? absint( $user['id'] ) : 0;

    if ( is_user_logged_in() ) {
      return ( $order_user_id > 0 && get_current_user_id() === $order_user_id );
    }

    if ( $order_user_id > 0 ) {
      return false;
    }

    $payment_key = isset( $_REQUEST['payment_key'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['payment_key'] ) ) : '';
    if ( empty( $payment_key ) ) {
      return false;
    }

    $payment_id_from_key = absint( rpress_get_purchase_id_by_key( $payment_key ) );
    if ( $payment_id_from_key !== $order_id ) {
      return false;
    }

    return (bool) rpress_can_view_receipt( $payment_key );
  }
  /**
   *  for order reorder.
   */
  public static function  reorder() {
    check_ajax_referer( 'show-order-details', 'security' );

    $order_id = isset( $_POST['order_id'] ) ? absint( wp_unslash( $_POST['order_id'] ) ) : 0;
    if ( ! self::can_access_frontend_order_action( $order_id ) ) {
      wp_send_json_error(
        array(
          'message' => esc_html__( 'You do not have permission to reorder this order.', 'restropress' ),
        ),
        403
      );
    }

    $payment = get_post( $order_id );
    if( empty( $payment ) ) return;
    $cart = rpress_get_payment_meta_cart_details( $payment->ID, true );
    if ( $cart ) {
        foreach( $cart as $key=>$fooditem ) {
            $instructions   = isset( $item['instruction'] ) ? $item['instruction'] : '';
            $fooditem_id    = $fooditem['id'];
            $quantity       = $fooditem['quantity'];
            $items          = '';
            $options        = array();
            $addon_items    = $fooditem['addon_items'];
            
            foreach( $addon_items as $key => $value ) {
                if ( is_array( $value ) && ! empty( $value ) ) {
                    $options['addon_items'][$key]['addon_item_name'] = $value['addon_item_name'];
                    $options['addon_items'][$key]['addon_id'] = $value['addon_id'];
                    $options['addon_items'][$key]['price'] = $value['price'];
                    $options['addon_items'][$key]['quantity'] = $value['quantity'];
                }
            }
            //Check whether the fooditem has variable pricing
            if ( rpress_has_variable_prices( $fooditem_id ) ) {
                $price_id       = $fooditem['item_number']['options']['price_id'];
                $options['price_id'] = $price_id;
                $options['price']    = rpress_get_price_option_amount( $fooditem_id, $price_id );
            } else {
                $options['price'] = rpress_get_fooditem_price( $fooditem_id );
            }
            
            
            $options['id']          = $fooditem_id;
            $options['quantity']    = $quantity;
            $options['instruction'] = $instructions;
            $key    = rpress_add_to_cart( $fooditem_id, $options );
            $item   = array(
              'id'      => $fooditem_id,
              'options' => $options
            );
            $item   = apply_filters( 'rpress_ajax_pre_cart_item_template', $item );
            $items .= rpress_get_cart_item_template( $key, $item, true, $data_key = $key );
            $return = array(
                'subtotal'      => html_entity_decode( rpress_currency_filter( rpress_format_amount( rpress_get_cart_subtotal() ) ), ENT_COMPAT, 'UTF-8' ),
                'total'         => html_entity_decode( rpress_currency_filter( rpress_format_amount( rpress_get_cart_total() ) ), ENT_COMPAT, 'UTF-8' ),
                'cart_item'     => $items,
                'cart_key'      => $key,
                'cart_quantity' => html_entity_decode( rpress_get_cart_quantity() )
            );
            if ( rpress_use_taxes() ) {
                $cart_tax = (float) rpress_get_cart_tax();
                $return['taxes'] = html_entity_decode( rpress_currency_filter( rpress_format_amount( $cart_tax ) ), ENT_COMPAT, 'UTF-8' );
            }
            $return = apply_filters( 'rpress_cart_data', $return );
        }
    }
    $html = '<div>
    <header class="modal__header modal-header">
        <h2 class="modal__title modal-title">'. __( 'Food Order', 'restropress' ) .'</h2>
        <button class="modal__close" aria-label="Close modal" data-micromodal-close></button>
    </header>
    <main class="modal__content modal-body">
        <div class="rpress-order-details">
            <div class="rp-order-section-md-data">
                <div class="rp-detils-content-view">
                    <p>All Item from Order #'. $order_id .' have been added to your cart.</p>
                    <a class="btn btn-primary btn-block" href="'. home_url( '/order-online' ) .'">'. __('Add more items', 'restropress').'</a>
                    <a class="btn btn-primary btn-block" href="'. rpress_get_checkout_uri() .'">'. __('Checkout Now', 'restropress').'</a>
                </div>
            </div>
        </div>
    </main>
    <footer class="modal__footer modal-footer"></footer>
    </div>';
    $response = array(
      'html' => $html,
    );
    wp_send_json_success( $response );
    rpress_die();
  }
  /**
   * Add an variable price row.
   */
  public static function add_price() {
    ob_start();
    check_ajax_referer( 'add-price', 'security' );
    $current =  isset( $_POST['i'] ) && ! empty( $_POST['i'] ) ? sanitize_text_field( $_POST['i'] ) : NULL;
    include 'admin/fooditems/views/html-fooditem-variable-price.php';
    wp_die();
  }
  /**
   * Add an addon row.
   */
  public static function add_addon() {
    ob_start();
    check_ajax_referer( 'add-addon', 'security' );
    $current = isset( $_POST['i'] ) && !empty( $_POST['i'] ) ? sanitize_text_field( $_POST['i'] ) : NULL;
    if( $_POST['iscreate'] == 'true' ) {
      $addon_types  = rpress_get_addon_types();
      include 'admin/fooditems/views/html-fooditem-new-addon-category.php';
    } else {
      $addon_categories = rpress_get_addons();
      $item_id = isset( $_POST['item_id'] ) && !empty( $_POST['item_id'] ) ? sanitize_text_field( $_POST['item_id'] ) : NULL;
      include 'admin/fooditems/views/html-fooditem-addon.php';
    }
    wp_die();
  }
  /**
   * Add Category to fooditem
   */
  public static function add_category() {
    check_ajax_referer( 'add-category', 'security' );
    $parent = isset( $_POST['parent'] ) && !empty( $_POST['parent'] ) ? sanitize_text_field( wp_unslash( $_POST['parent'] ) ) : NULL;
    $name   = isset( $_POST['name'] ) && !empty( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : NULL ;
    $args   = apply_filters( 'rpress_add_category_args', array( 'parent' => $parent ) );
    $category = wp_insert_term( $name, 'food-category', $args );
    wp_send_json( $category );
  }
  /**
  *
  * Change order status from order history
  *
  * @since 3.0
  * @return mixed
  */
  public static function update_order_status() {
    check_admin_referer( 'rpress-order', 'security' );
    if ( ! empty( $_GET['status'] ) && ! empty( $_GET['payment_id'] ) ) {
      if( ! current_user_can( 'edit_shop_payments', $_GET['payment_id'] ) ) {
        wp_die( esc_html__( 'You do not have permission to update this order', 'restropress' ), esc_html__( 'Error', 'restropress' ), array( 'response' => 403 ) );
      }
      $payment_id = absint( $_GET['payment_id'] );
      $status     = sanitize_text_field( $_GET['status'] );
      $statuses = rpress_get_order_statuses();
      if ( array_key_exists( $status, $statuses ) ) {
        rpress_update_order_status( $payment_id, $status );
      }
    }
    $redirect = wp_get_referer() ? wp_get_referer() : admin_url( 'admin.php?page=rpress-payment-history' );
    
    if( ! empty( $_GET['redirect'] ) ) {
      wp_safe_redirect( esc_url( $redirect ) );
      exit;
    }
    
    wp_send_json( [ 'redirect' => esc_url( $redirect ) ], 200 );
  }

  /**
  *
  * Fetches live order status for frontend confirmation page polling.
  *
  * @since 3.2.6
  * @return void
  */
  public static function receipt_order_status() {
    $payment_id  = isset( $_REQUEST['payment_id'] ) ? absint( $_REQUEST['payment_id'] ) : 0;
    $payment_key = isset( $_REQUEST['payment_key'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['payment_key'] ) ) : '';
    $security    = isset( $_REQUEST['security'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['security'] ) ) : '';

    if ( empty( $payment_id ) || empty( $payment_key ) ) {
      wp_send_json_error(
        array(
          'message' => esc_html__( 'Missing payment details.', 'restropress' ),
        ),
        400
      );
    }

    if ( ! wp_verify_nonce( $security, 'rpress-receipt-status-' . $payment_id ) ) {
      wp_send_json_error(
        array(
          'message' => esc_html__( 'Invalid request.', 'restropress' ),
        ),
        403
      );
    }

    if ( 'rpress_payment' !== get_post_type( $payment_id ) ) {
      wp_send_json_error(
        array(
          'message' => esc_html__( 'Invalid payment.', 'restropress' ),
        ),
        404
      );
    }

    $payment_id_from_key = absint( rpress_get_purchase_id_by_key( $payment_key ) );
    if ( $payment_id_from_key !== $payment_id ) {
      wp_send_json_error(
        array(
          'message' => esc_html__( 'Payment key mismatch.', 'restropress' ),
        ),
        403
      );
    }

    if ( ! rpress_can_view_receipt( $payment_key ) ) {
      wp_send_json_error(
        array(
          'message' => esc_html__( 'Receipt access denied.', 'restropress' ),
        ),
        403
      );
    }

    $status            = sanitize_key( rpress_get_order_status( $payment_id ) );
    $status_label      = rpress_get_order_status_label( $status );
    $status_colors     = function_exists( 'rpress_get_order_status_colors' ) ? rpress_get_order_status_colors() : array();
    $status_color      = isset( $status_colors[ $status ] ) ? sanitize_hex_color( $status_colors[ $status ] ) : '';
    $payment_number    = rpress_get_payment_number( $payment_id );
    $formatted_number  = rpress_format_payment_number( $payment_number );
    $updated_at_unix   = absint( get_post_meta( $payment_id, '_rpress_order_status_updated_at', true ) );
    if ( empty( $updated_at_unix ) ) {
      $updated_at_unix = (int) get_post_modified_time( 'U', true, $payment_id );
    }

    wp_send_json_success(
      array(
        'payment_id'      => $payment_id,
        'order_number'    => $formatted_number,
        'status'          => $status,
        'status_label'    => wp_strip_all_tags( (string) $status_label ),
        'status_color'    => $status_color,
        'updated_at_unix' => $updated_at_unix,
      )
    );
  }
  /**
   * Load addon child items when after selecting parent addon
   */
  public static function load_addon_child() {
    check_ajax_referer( 'load-addon', 'security' );
    $parent      =  isset( $_POST['parent'] ) && ! empty( $_POST['parent'] ) ? sanitize_text_field( wp_unslash( $_POST['parent'] ) ) : NULL ;
    
    $current     = isset( $_POST['i'] ) && ! empty( $_POST['i'] ) ? sanitize_text_field( wp_unslash( $_POST['i'] ) ) : NULL ;
    $item_id     = isset( $_POST['item_id'] ) && ! empty( $_POST['item_id'] ) ? sanitize_text_field( wp_unslash( $_POST['item_id'] ) ) : NULL ;
    $addon_items = rpress_get_addons( $parent );
    
    $variation_label = '';
    if( ! is_null( $item_id ) && rpress_has_variable_prices( $item_id ) ) {
      $variation_label = get_post_meta( $item_id, 'rpress_variable_price_label', true );
      $variation_label = ! is_null( $variation_label ) ? $variation_label : esc_html(  __( 'Variation', 'restropress' ) ) ;
    }
    $output  = '<table class="rp-addon-items">';
    $output .= '<thead>';
    $output .= '<tr>';
    $output .= '<th class="select_addon select_all_addons">';
    $output .= '<input type="checkbox" class="rp-select-all">' . '<strong>' . esc_html__( 'Enable', 'restropress' ) . '</strong>';
    $output .= '</th>';
    $output .= '<th class="addon_name">';
    $output .= '<strong>' . esc_html__( 'Addon Name', 'restropress' ) . '</strong>';
    $output .= '</th>';
    $output .= '<th class="variation_name">';
    $output .= '<strong>' . esc_html( $variation_label ) . '</strong>';
    $output .= '</th>';
    $output .= '<th class="addon_price">';
    $output .= '<strong>' . esc_html__( 'Price', 'restropress' ) . '</strong>';
    $output .= '</th>';
    $output .= '<th class="default_addon">';
    $output .= '<strong>'. esc_html__( 'Default', 'restropress' ) . '</strong>';
    $output .= '</th>';
    $output .= '</tr>';
    $output .= '</thead>';
    $output .= '<tbody>';
    foreach( $addon_items as $addon_item ) {
      $addon_price = rpress_get_addon_data( $addon_item->term_id, '_price' );
      $addon_price = ! empty( $addon_price ) ? $addon_price : '0.00';
      
      $parent_class = ( $addon_item->parent == 0 ) ? 'rp-parent-addon' : 'rp-child-addon';
      $count = 1;
      if( ! empty( $item_id ) && rpress_has_variable_prices( $item_id ) ) {
        foreach ( rpress_get_variable_prices( $item_id ) as $price ) {
          $output .= '<tr class="' . $parent_class . '">';
          if( $count == 1 ) {
            $output .= '<td class="rp-addon-select td_checkbox"><input type="checkbox" value="' . $addon_item->term_id . '" id="' . $addon_item->slug .'" name="addons[' . $current . '][items][]" class="rp-checkbox"></td>';
          } else {
            $output .= '<td class="rp-addon-select td_checkbox">&nbsp;</td>';
          }
          $output .= '<td class="add_label"><label for="' . $addon_item->slug .'">' . $addon_item->name .'</label></td>';
          $output .= '<td class="variation_label"><label for="' . $price['name'] .'">' . $price['name'] .'</label></td>';
          $output .= '<td class="addon_price"><input class="addon-custom-price" type="number" step="any" min="0.00" placeholder="0.00" value="'.$addon_price.'" name="addons[' . $current . '][prices]['.$addon_item->term_id.']['.$price['name'].']"></td>';
          $output .= '<td class="td_checkbox"><input type="checkbox" value="' . $addon_item->term_id . '" id="' . $addon_item->slug .'" name="addons[' . $current . '][default][]" class="rp-checkbox"></td>';
          $output .= '</tr>';
          $count++;
        }
      } else { 
        $output .= '<tr class="' . $parent_class . '">';
        $output .= '<td class="rp-addon-select td_checkbox"><input type="checkbox" value="' . $addon_item->term_id . '" id="' . $addon_item->slug .'" name="addons[' . $current . '][items][]" class="rp-checkbox"></td>';
        $output .= '<td class="add_label"><label for="' . $addon_item->slug .'">' . $addon_item->name .'</label></td>';
        $output .= '<td class="variation_label">&nbsp;</label></td>';
        $output .= '<td class="addon_price"><input class="addon-custom-price" type="number" step="any" min="0.00" placeholder="0.00" value="'.$addon_price.'" name="addons[' . $current . '][prices]['.$addon_item->term_id.']"></td>';
        $output .= '<td class="td_checkbox"><input type="checkbox" value="' . $addon_item->term_id . '" id="' . $addon_item->slug .'" name="addons[' . $current . '][default][]" class="rp-checkbox"></td>';
        $output .= '</tr>';
      }
    }
    
    $output .= '</tbody>';
    $output .= '</table>';
    // Define allowed HTML tags and attributes
    $allowed_html = array(
      'table' => array(
          'class' => array(),
      ),
      'thead' => array(),
      'tbody' => array(),
      'tr' => array(
          'class' => array(),
      ),
      'th' => array(
          'class' => array(),
      ),
      'td' => array(
          'class' => array(),
      ),
      'input' => array(
          'type' => array(),
          'name' => array(),
          'value' => array(),
          'id' => array(),
          'class' => array(),
          'step' => array(),
          'min' => array(),
          'placeholder' => array(),
      ),
      'label' => array(
          'for' => array(),
      ),
      'strong' => array(),
      'span' => array(
          'class' => array(),
      ),
      '&nbsp;' => array(),
    );

    // Echo sanitized output
    echo wp_kses( $output, $allowed_html );
    wp_die();
  }
  /**
   * Load Fooditems List in the popup
   */
  public static function show_products() {
    check_ajax_referer( 'show-products', 'security' );
    $service_type = sanitize_key( (string) filter_input( INPUT_POST, 'service_type' ) );
    $selected_date = sanitize_text_field( (string) filter_input( INPUT_POST, 'selected_date' ) );
    $selected_time = sanitize_text_field( (string) filter_input( INPUT_POST, 'selected_time' ) );
    if ( empty( $_POST['fooditem_id'] ) ) {
      wp_send_json_error(
        array(
          'status' => 'error',
          'error_msg' => __( 'Unable to load item details. Please try again.', 'restropress' ),
        )
      );
    }
    $allowed_services = rpress_get_enabled_services();
    if ( empty( $service_type ) || ! in_array( $service_type, $allowed_services, true ) ) {
      $service_type = rpress_get_default_enabled_service();

      if ( empty( $service_type ) || ! in_array( $service_type, $allowed_services, true ) ) {
        wp_send_json_error(
          array(
            'status' => 'error',
            'error_msg' => __( 'Please select a service type.', 'restropress' ),
          )
        );
      }
    }
    if ( empty( $selected_date ) ) {
      $selected_date = rpress_get_first_available_service_date( $service_type, '' );
    } else {
      $selected_date_ts = strtotime( $selected_date );
      if ( false === $selected_date_ts ) {
        $selected_date = rpress_get_first_available_service_date( $service_type, '' );
      } else {
        $selected_date = date_i18n( 'Y-m-d', $selected_date_ts );
      }
    }

    if ( empty( $selected_date ) ) {
      wp_send_json_error(
        array(
          'status' => 'error',
          'error_msg' => __( 'Please select a valid service date.', 'restropress' ),
        )
      );
    }
    $selected_date = rpress_get_first_available_service_date( $service_type, $selected_date );
    $service_time_hidden = function_exists( 'rp_otil_is_service_time_hidden' ) && rp_otil_is_service_time_hidden( $service_type );
    $allow_asap = ! empty( rpress_get_option( 'enable_asap_option' ) );
    $available_slots = rpress_get_available_service_slots( $service_type, $selected_date, true );
    $service_time = ! empty( $selected_time )
      ? $selected_time
      : ( isset( $_COOKIE['service_time'] ) ? sanitize_text_field( wp_unslash( $_COOKIE['service_time'] ) ) : '' );
    if ( ! rpress_is_store_open( $service_type, $selected_date ) ) {
      $response = array( 'status' => 'error', 'error_msg' => rpress_store_closed_message( $service_type ) );
      wp_send_json_error( $response );
      die();
    }
    if ( ! $service_time_hidden ) {
      $prep_time  = (int) rpress_get_option( 'prep_time', 0 ) * 60;
      $current_time = current_time( 'timestamp' ) + $prep_time;
      $service_time = rpress_match_service_time_to_slot( $service_time, $available_slots, $allow_asap );
      if ( empty( $service_time ) ) {
        $service_time = rpress_get_next_available_service_time( $selected_date, $available_slots, $current_time );
      }
      if ( empty( $service_time ) ) {
        wp_send_json_error(
          array(
            'status' => 'error',
            'error_msg' => __( 'Please select a service time.', 'restropress' ),
          )
        );
      }
    }
    if ( ! $service_time_hidden && ! empty( $service_time ) && ! $allow_asap ) {
      $prep_time  = (int) rpress_get_option( 'prep_time', 0 ) * 60;
      $current_time = current_time( 'timestamp' ) + $prep_time;
      $service_time_ts = strtotime( $selected_date . ' ' . $service_time );
      if ( false !== $service_time_ts && $service_time_ts < $current_time ) {
        $fallback_service_time = rpress_get_next_available_service_time( $selected_date, $available_slots, $current_time );
        if ( ! empty( $fallback_service_time ) ) {
          $service_time = $fallback_service_time;
          $service_time_ts = strtotime( $selected_date . ' ' . $service_time );
        }
      }
      if ( false === $service_time_ts || $service_time_ts < $current_time ) {
        wp_send_json_error(
          array(
            'status' => 'error',
            'error_msg' => __( 'Selected time slot is no longer available. Please choose another time.', 'restropress' ),
          )
        );
      }
    }
    $fooditem_id = sanitize_text_field ( wp_unslash( $_POST['fooditem_id'] ) );
    $price = '';
    if ( ! empty( $fooditem_id ) ) {
      //Check item is variable or simple
      if ( rpress_has_variable_prices( $fooditem_id ) ) {
        $price = rpress_get_lowest_price_option( $fooditem_id );
      } else {
        $price = rpress_get_fooditem_price( $fooditem_id );
        $rate = (float) rpress_get_option( 'tax_rate', 0 );
        // Convert to a number we can use
        $item_tax = (float) $price - ( (float) $price / ( ( (float) $rate / 100 ) + 1 ) );
        $include_tax  = rpress_get_option( 'prices_include_tax', true );
        $tax_inc_exc_item_option = rpress_get_option('tax_item', true );
    
        /** 
        * Condition added to show the item price as included or excluded Tax
        * @since 2.9.6
        */
    
        if( $include_tax == 'yes' && $tax_inc_exc_item_option == 'inc_tax' ) {
          $price = get_post_meta( $fooditem_id,'rpress_price', true );
        } elseif ( $include_tax == 'yes' && $tax_inc_exc_item_option == 'exc_tax' ) {
          $item_tax = ( float ) $price - ( (float) $price / ( ( (float) $rate / 100 ) + 1 ) );
          $price = $price - $item_tax;
        } elseif ($include_tax == 'no' && $tax_inc_exc_item_option == 'inc_tax') {
          $item_tax = ( float ) $price * ( (float) $rate / 100 );
          $price = ( float ) $price + ( float ) $item_tax;
        }        
        
      }
    }
    if ( ! empty( $price ) ) {
      $formatted_price = rpress_currency_filter( rpress_format_amount( $price ) );
    }
    
    $food_title     = get_the_title( $fooditem_id );
    $fooditem_desc  = get_post_field( 'post_content', $fooditem_id );
    $image_placeholder = rpress_get_option( 'enable_image_placeholder', false );

    if ( has_post_thumbnail( $fooditem_id ) ) {
        // Post has thumbnail → use it
        $food_image = get_the_post_thumbnail_url( $fooditem_id, 'full' );

    } elseif ( $image_placeholder == 1 ) {
        // No thumbnail, but placeholder setting is enabled → show placeholder
        $food_image = RP_PLUGIN_URL . 'assets/images/no-image.png';

    } else {
        // No thumbnail and no placeholder → empty
        $food_image = '';
    }

    $item_addons    = get_fooditem_lists( $fooditem_id, $cart_key = '' );
    ob_start();
    rpress_get_template_part( 'rpress', 'show-products' );
    $data = ob_get_clean();
    $data = str_replace( '{fooditemslist}', $item_addons, $data );
    $data = str_replace( '{itemdescription}', $fooditem_desc, $data );
    $response = array(
      'price'       => $formatted_price,
      'price_raw'   => $price,
      'html'        => $data,
      'html_title'  => apply_filters( 'rpress_modal_title' , $food_title ),
      'description' => $fooditem_desc,
      'image_url'   => $food_image,
    );
    wp_send_json_success( $response );
    rpress_die();
  }
  /**
   * Show Service Options in the popup
   */
  public static function show_delivery_options() {
    check_ajax_referer( 'service-type', 'security' );
    $fooditem_id      = isset( $_POST['fooditem_id'] ) && ! empty( $_POST['fooditem_id'] ) ? sanitize_text_field( wp_unslash( $_POST['fooditem_id'] ) )  : NULL;
    $delivery_steps   = rpress_get_delivery_steps( $fooditem_id );
    $response = array(
      'html'        => $delivery_steps,
      'html_title'  => apply_filters( 'rpress_delivery_options_title', esc_html__( 'Your Order Settings', 'restropress' ) ),
    );
    wp_send_json_success( $response );
    rpress_die();
  }
  /**
   * Check Service Options availibility
   */
  public static function check_service_slot() {
    check_ajax_referer( 'service-type', 'security' );
    $data = rpress_sanitize_array( $_POST );
    $response = apply_filters( 'rpress_check_service_slot', $data );
    $response = apply_filters( 'rpress_validate_slot', $response );
    wp_send_json( $response );
    wp_die();
  }
  /**
   * Edit fooditem in the popup
   */
  public static function edit_cart_fooditem() {
    check_ajax_referer( 'edit-cart-fooditem', 'security' );
    $cart_key  = ! empty( $_POST['cartitem_id'] ) ? sanitize_text_field( wp_unslash( $_POST['cartitem_id'] ) )  : 0 ;
    $cart_key  = absint( $cart_key );
    $fooditem_id = ! empty( $_POST['fooditem_id'] ) ? sanitize_text_field ( wp_unslash( $_POST['fooditem_id'] ) ) : NULL ;
    $food_title  = ! empty( $_POST['fooditem_name'] ) ? sanitize_text_field( wp_unslash( $_POST['fooditem_name'] ) ) : get_the_title( $fooditem_id );
    $fooditem_desc  = get_post_field( 'post_content', $fooditem_id );
    $image_placeholder = rpress_get_option( 'enable_image_placeholder', false );
    if ( has_post_thumbnail( $fooditem_id ) ) {
        // Post has thumbnail → use it
        $food_image = get_the_post_thumbnail_url( $fooditem_id, 'full' );

    } elseif ( $image_placeholder == 1 ) {
        // No thumbnail, but placeholder setting is enabled → show placeholder
        $food_image = RP_PLUGIN_URL . 'assets/images/no-image.png';

    } else {
        // No thumbnail and no placeholder → empty
        $food_image = '';
    }
    if ( ! empty( $fooditem_id)  ) {
      $price = '';
      if ( ! empty( $fooditem_id ) ) {
        //Check item is variable or simple
        if ( rpress_has_variable_prices( $fooditem_id ) ) {
          $price = rpress_get_lowest_price_option( $fooditem_id );
        } else {
          $price = rpress_get_fooditem_price( $fooditem_id );
          $rate = (float) rpress_get_option( 'tax_rate', 0 );
          // Convert to a number we can use
          $item_tax = (float) $price - ( (float) $price / ( ( (float) $rate / 100 ) + 1 ) );
          $include_tax  = rpress_get_option( 'prices_include_tax', true );
          $tax_inc_exc_item_option = rpress_get_option('tax_item', true );
      
          /** 
          * Condition added to show the item price as included or excluded Tax
          * @since 2.9.6
          */
      
          if( $include_tax == 'yes' && $tax_inc_exc_item_option == 'inc_tax' ) {
            $price = get_post_meta( $fooditem_id,'rpress_price', true );
          } elseif ( $include_tax == 'yes' && $tax_inc_exc_item_option == 'exc_tax' ) {
            $item_tax = ( float ) $price - ( (float) $price / ( ( (float) $rate / 100 ) + 1 ) );
            $price = $price - $item_tax;
          } elseif ($include_tax == 'no' && $tax_inc_exc_item_option == 'inc_tax') {
            $item_tax = ( float ) $price * ( (float) $rate / 100 );
            $price = ( float ) $price + ( float ) $item_tax;
          }        
  
        }
      }
      if ( ! empty( $price ) ) {
        $formatted_price = rpress_currency_filter( rpress_format_amount( $price ) );
      }
      $parent_addons = get_fooditem_lists( $fooditem_id, $cart_key );
      $special_instruction = rpress_get_instruction_by_key( $cart_key );
      ob_start();
      rpress_get_template_part( 'rpress', 'edit-product' );
      $data = ob_get_clean();
      $data = str_replace( '{itemdescription}', $fooditem_desc, $data );
      $data = str_replace( '{fooditemslist}', $parent_addons, $data );
      $data = str_replace( '{cartinstructions}', $special_instruction, $data );
    }
    $cart_details = RPRESS()->cart->get_contents_details();
    $addon_items  = isset( $cart_details[$cart_key]['addon_items'] ) ? $cart_details[$cart_key]['addon_items'] : array();
    $response = array(
      'price'       => $formatted_price,
      'price_raw'   => $price,
      'html'        => $data,
      'html_title'  => apply_filters( 'rpress_modal_title' , $food_title),
      'description' => $fooditem_desc,
      'image_url'   => $food_image,
      'addon_items' => $addon_items,
    );
    wp_send_json_success( $response );
    rpress_die();
  }
  /**
   * Add To Cart in the popup
   */
  public static function add_to_cart() {
    // Remove all cart fees.
    RPRESS()->session->set('rpress_cart_fees', null);
    // Remove any resuming payments.
    RPRESS()->session->set('rpress_resume_payment', null);
    check_ajax_referer( 'add-to-cart', 'security' );
    if ( empty( $_POST['fooditem_id'] ) ) {
      return;
    }
    $fooditem_id  = sanitize_text_field( wp_unslash( $_POST['fooditem_id'] ) );
    $quantity     = ! empty( $_POST['fooditem_qty'] ) ? sanitize_text_field( wp_unslash( $_POST['fooditem_qty'] ) )  : 1;
    $instructions = ! empty( $_POST['special_instruction'] ) ? sanitize_text_field( wp_unslash( $_POST['special_instruction'] ) ): '';
    $addon_items  = ! empty( $_POST['post_data'] ) ? (array) $_POST['post_data'] : array() ;
    $addon_items  = rpress_sanitize_array( $addon_items );
    $items   = '';
    $options = array();
    //Check whether the fooditem has variable pricing
    if ( rpress_has_variable_prices( $fooditem_id ) ) {
      $price_id = ! empty( $addon_items[0]['value'] ) ? $addon_items[0]['value'] : 0;
      $options['price_id'] = $price_id;
      $options['price']    = rpress_get_price_option_amount( $fooditem_id, $price_id );
    } else {
      $options['price'] = rpress_get_fooditem_price( $fooditem_id );
    }
    $options['id'] = $fooditem_id;
    $options['quantity'] = $quantity;
    $options['instruction'] = $instructions;
    if ( is_array( $addon_items ) && ! empty( $addon_items ) ) {
      foreach( $addon_items as $key => $get_items ) {
        $addon_data = explode( '|', sanitize_text_field( $get_items[ 'value' ] ) );
        if ( is_array( $addon_data ) && ! empty( $addon_data ) ) {
          $addon_item_like = isset( $addon_data[3] ) ? $addon_data[3] : 'checkbox';
          $addon_id     = ! empty( $addon_data[0] ) ? $addon_data[0] : '';
          $addon_qty    = ! empty( $addon_data[1] ) ? $addon_data[1] : '';
          $addon_price  = ! empty( $addon_data[2] ) ? $addon_data[2] : '';
          $addon_details = get_term_by( 'id', $addon_id, 'addon_category' );
          if (  $addon_details ) {
            $addon_item_name = $addon_details->name;
            $options['addon_items'][$key]['addon_item_name'] = $addon_item_name;
            $options['addon_items'][$key]['addon_id'] = $addon_id;
            $options['addon_items'][$key]['price'] = $addon_price;
            $options['addon_items'][$key]['quantity'] = $addon_qty;
          }
        }
      }
    }
    $key = rpress_add_to_cart( $fooditem_id, $options );
    $item = array(
      'id'      => $fooditem_id,
      'options' => $options
    );
    $item   = apply_filters( 'rpress_ajax_pre_cart_item_template', $item );
    $items .= rpress_get_cart_item_template( $key, $item, true, $data_key = $key );
    $return = array(
     'subtotal'      => html_entity_decode( rpress_currency_filter( rpress_format_amount( rpress_get_cart_subtotal() ) ), ENT_COMPAT, 'UTF-8' ),
     'total'         => html_entity_decode( rpress_currency_filter( rpress_format_amount( rpress_get_cart_total() ) ), ENT_COMPAT, 'UTF-8' ),
     'cart_item'     => $items,
     'cart_key'      => $key,
     'cart_quantity' => html_entity_decode( rpress_get_cart_quantity() )
    );
    if ( rpress_use_taxes() ) {
      $cart_tax = (float) rpress_get_cart_tax();
      $return['taxes'] = html_entity_decode( rpress_currency_filter( rpress_format_amount( $cart_tax ) ), ENT_COMPAT, 'UTF-8' );
    }
    $return = apply_filters( 'rpress_cart_data', $return );
    wp_send_json( $return );
    rpress_die();
  }
  /**
   * Update Cart Items
   */
  public static function update_cart_items() {
    check_ajax_referer( 'update-cart-item', 'security' );
    $cart_key     = isset( $_POST['fooditem_cartkey'] ) && ! empty( $_POST['fooditem_cartkey'] ) ? sanitize_text_field( wp_unslash( $_POST['fooditem_cartkey'] ) ) : NULL;
    $fooditem_id  = isset( $_POST['fooditem_id'] ) && ! empty( $_POST['fooditem_id'] ) ? sanitize_text_field( wp_unslash( $_POST['fooditem_id'] ) )  : NULL;
    $item_qty     = isset( $_POST['fooditem_qty'] ) && ! empty( $_POST['fooditem_qty'] ) ? sanitize_text_field( wp_unslash( $_POST['fooditem_qty'] ) )  : 1;
    if ( empty( $cart_key ) && empty( $fooditem_id ) ) {
      return;
    }
    
    $special_instruction = isset( $_POST['special_instruction'] ) ? sanitize_text_field( $_POST['special_instruction'] ) : '';
    $addon_items = isset( $_POST['post_data'] ) ? (array) $_POST['post_data']  : array();
    $addon_items = rpress_sanitize_array( $addon_items );
    $options = array();
    $options['id'] = $fooditem_id;
    $options['quantity'] = $item_qty;
    $options['instruction'] = $special_instruction;
    $price_id = '';
    $items    = '';
    if( rpress_has_variable_prices( $fooditem_id ) ) {
      if ( isset( $addon_items[0]['name'] ) && sanitize_text_field( $addon_items[0]['name'] ) == 'price_options' ) {
        $price_id = sanitize_text_field( $addon_items[0]['value'] );
      }
    }
    $options['price_id'] = $price_id;
    if ( is_array( $addon_items ) && ! empty( $addon_items ) ) {
      foreach( $addon_items as $key => $item ) {
        $value = sanitize_text_field( $item['value'] );

          // Validate expected format: number|number|decimal|string (e.g. 26|1|5|checkbox)
          if ( preg_match( '/^\d+\|\d+\|[\d.]+\|[a-zA-Z0-9_-]+$/', $value ) ) {
              $addon_data = explode( '|', $value );

              if ( count( $addon_data ) === 4 ) {
                  list( $addon_id, $addon_qty, $addon_price, $addon_type ) = $addon_data;

                  $addon_details = get_term_by( 'id', $addon_id, 'addon_category' );

                  if ( $addon_details ) {
                      $addon_item_name = $addon_details->name;

                      $options['addon_items'][$key] = array(
                          'addon_item_name' => $addon_item_name,
                          'addon_id'        => absint( $addon_id ),
                          'price'           => floatval( $addon_price ),
                          'quantity'        => absint( $addon_qty ),
                          'type'            => sanitize_key( $addon_type ),
                      );
                  }
              }
          }
      }
    }
    RPRESS()->cart->set_item_quantity( $fooditem_id, $item_qty, $options );
    $item = array(
      'id'      => $fooditem_id,
      'options' => $options
    );
    $item   = apply_filters( 'rpress_ajax_pre_cart_item_template', $item );
    $items  = rpress_get_cart_item_template( $cart_key, $item, true, $data_key = '' );
    $return = array(
     'subtotal'      => html_entity_decode( rpress_currency_filter( rpress_format_amount( rpress_get_cart_subtotal() ) ), ENT_COMPAT, 'UTF-8' ),
     'total'         => html_entity_decode( rpress_currency_filter( rpress_format_amount( rpress_get_cart_total() ) ), ENT_COMPAT, 'UTF-8' ),
     'cart_item'     => $items,
     'cart_key'      => $cart_key,
     'cart_quantity' => html_entity_decode( rpress_get_cart_quantity() )
    );
    if ( rpress_use_taxes() ) {
      $cart_tax = (float) rpress_get_cart_tax();
      $return['tax'] = html_entity_decode( rpress_currency_filter( rpress_format_amount( $cart_tax ) ), ENT_COMPAT, 'UTF-8' );
    }
    $return = apply_filters( 'rpress_cart_data', $return );
    echo wp_json_encode( $return );
    rpress_die();
  }
  /**
   * Remove an item from Cart
   */
  public static function remove_from_cart() {
    check_ajax_referer( 'edit-cart-fooditem', 'security' );
    
    if ( isset( $_POST['cart_item'] ) ) {
      rpress_remove_from_cart( absint( $_POST['cart_item'] ) );
      $return = array(
        'removed'       => 1,
        'subtotal'      => html_entity_decode( rpress_currency_filter( rpress_format_amount( rpress_get_cart_subtotal() ) ), ENT_COMPAT, 'UTF-8' ),
        'total'         => html_entity_decode( rpress_currency_filter( rpress_format_amount( rpress_get_cart_total() ) ), ENT_COMPAT, 'UTF-8' ),
        'cart_quantity' => html_entity_decode( rpress_get_cart_quantity() ),
      );
      if ( rpress_use_taxes() ) {
        $cart_tax = (float) rpress_get_cart_tax();
        $return['tax'] = html_entity_decode( rpress_currency_filter( rpress_format_amount( $cart_tax ) ), ENT_COMPAT, 'UTF-8' );
      }
      $return = apply_filters( 'rpress_cart_data', $return );
      wp_send_json( $return );
    }
    rpress_die();
  }
  /**
  * Clear cart
  */
  public static function clear_cart() {
    check_ajax_referer( 'clear-cart', 'security' );
    
    rpress_empty_cart();
    // Removing Service Time Cookie
    if ( isset( $_COOKIE['service_time'] ) ) {
      unset( $_COOKIE['service_time'] );
      setcookie( "service_time", "", time() - 300,"/" );
    }
    // Removing Service Type Cookie
    if ( isset( $_COOKIE['service_type'] ) ) {
      unset( $_COOKIE['service_type'] );
      setcookie( "service_type", "", time() - 300,"/" );
    }
    // Removing Delivery Date Cookie
    if ( isset( $_COOKIE['delivery_date'] ) ) :
      unset( $_COOKIE['delivery_date'] );
      setcookie( "delivery_date", "", time() - 300,"/" );
    endif;
    $return['status']   = 'success';
    $return['response'] = '<li class="cart_item empty"><span class="rpress_empty_cart">'.apply_filters( 'rpress_empty_cart_message', '<span class="rpress_empty_cart">' .esc_html__( 'CHOOSE AN ITEM FROM THE MENU TO GET STARTED.', 'restropress' ) . '</span>' ).'</span></li>';
    echo wp_json_encode( $return );
    rpress_die();
  }
  /**
  * Proceed Checkout
  */
  public static function proceed_checkout() {
    check_ajax_referer( 'proceed-checkout', 'security' );

    $response = rpress_pre_validate_order();
    $response = apply_filters( 'rpress_proceed_checkout', $response );
    wp_send_json( $response );
    rpress_die();
    
  }
  /**
   * Get Order Details
   */
  public static function get_order_details() {
    check_admin_referer( 'rpress-preview-order', 'security' );
    $order_id = isset( $_GET['order_id'] ) ? absint( wp_unslash( $_GET['order_id'] ) ) : 0;

    if ( empty( $order_id ) ) {
      wp_send_json_error(
        array(
          'message' => esc_html__( 'Invalid order request.', 'restropress' ),
        ),
        400
      );
    }

    if ( ! current_user_can( 'edit_shop_payments', $order_id ) ) {
      wp_die( esc_html__( 'You do not have permission to update this order', 'restropress' ), esc_html__( 'Error', 'restropress' ), array( 'response' => 403 ) );
    }

    $order = rpress_get_payment( $order_id );
    if ( $order ) {
      include_once 'admin/payments/class-payments-table.php';
      wp_send_json_success( RPRESS_Payment_History_Table::order_preview_get_order_details( $order ) );
    }
    rpress_die();
  }
  /**
  * Get Fooditem Variations
  */
  public static function check_for_fooditem_price_variations() {
    // Check if current user can edit products.
    if ( ! current_user_can( 'edit_products' ) ) {
        die( '-1' );
    }

    $fooditem_id = isset( $_POST['fooditem_id'] ) ? absint( $_POST['fooditem_id'] ) : '';
    if ( empty( $fooditem_id ) ) {
        return;
    }

    ob_start();

    if ( rpress_has_variable_prices( $fooditem_id ) ) :
        $get_lowest_price_id = rpress_get_lowest_price_id( $fooditem_id );
        $get_lowest_price    = rpress_get_lowest_price_option( $fooditem_id );
        ?>
        <div class="rpress-get-variable-prices">
            <!-- This hidden input is optional if JavaScript handles price properly -->
            <input type="hidden" class="rpress_selected_price" name="rpress_selected_price" value="<?php echo esc_attr( $get_lowest_price ); ?>">

            <select name="rpres_price_name" class="rpress-price-dropdown rpress_price_options_select">
                <?php foreach ( rpress_get_variable_prices( $fooditem_id ) as $key => $options ) : 
                    $option_price = $options['amount'];
                    $price = rpress_currency_filter( rpress_format_amount( $option_price ) );
                    $option_name = $options['name'];
                    $selected = selected( $get_lowest_price_id, $key, false );
                ?>
                    <option 
                        value="<?php echo esc_attr( $key ); ?>" 
                        data-price="<?php echo esc_attr( rpress_sanitize_amount( $option_price ) ); ?>"
                        <?php echo esc_attr($selected); ?>>
                        <?php echo esc_html( $option_name . ' (' . $price . ')' ); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php
    else :
        $normal_price = rpress_get_fooditem_price( $fooditem_id );
        $price = rpress_currency_filter( rpress_format_amount( $normal_price ) );
        ?>
        <span class="rpress-price-name"><?php echo esc_html(rpress_currency_symbol()); ?></span>
        <input type="text" class="rpress_selected_price" name="rpress_selected_price" value="<?php echo esc_attr(rpress_sanitize_amount( $normal_price )); ?>">
        <?php
    endif;

    $output = ob_get_contents();
    ob_end_clean();
    // Define allowed HTML and attributes
    $allowed_html = array(
      'div'    => array( 'class' => true ),
      'span'   => array( 'class' => true ),
      'input'  => array(
          'type'  => true,
          'class' => true,
          'name'  => true,
          'value' => true,
      ),
      'select' => array( 'name' => true, 'class' => true ),
      'option' => array(
          'value'      => true,
          'data-price' => true,
          'selected'   => true,
      ),
    );

    echo wp_kses( $output, $allowed_html );
    rpress_die();
}

  /**
  * Get addon items in the admin order screen
  */
  public static function admin_order_addon_items() {
    check_ajax_referer( 'load-admin-addon', 'security' );
    $fooditem_id = isset( $_POST['fooditem_id' ] ) ? sanitize_text_field( wp_unslash( $_POST['fooditem_id'] ) ) : NULL;
    if( ! empty( $fooditem_id ) ) {
      rpress_addon_items_by_fooditem( $fooditem_id );
    }
    
    rpress_die();
  }
  /**
   * Gets the cart's subtotal via AJAX.
   *
   * @since 1.0
   * @return void
   */
  public static function get_subtotal() {
    echo esc_html(rpress_currency_filter( rpress_get_cart_subtotal() ));
    rpress_die();
  }
  /**
   * Validates the supplied discount sent via AJAX.
   *
   * @since 1.0
   * @return void
   */
  public static function apply_discount() {
    if ( ! check_ajax_referer( 'rpress_checkout_nonce', 'security', false ) ) {
      echo wp_json_encode(
        array(
          'msg'  => esc_html__( 'Security check failed. Please refresh and try again.', 'restropress' ),
          'code' => '',
        )
      );
      rpress_die();
    }

    if ( isset( $_POST['code'] ) ) {
      $discount_code = sanitize_text_field( wp_unslash( $_POST['code'] ) );
      $return = array(
        'msg'  => '',
        'code' => $discount_code
      );
      $user = '';
      if ( is_user_logged_in() ) {
        $user = get_current_user_id();
      } else {
        parse_str( sanitize_text_field( wp_unslash( $_POST['form'] ) ), $form );
        if ( ! empty( $form['rpress_email'] ) ) {
          $user = urldecode( $form['rpress_email'] );
        }
      }
      if ( rpress_is_discount_valid( $discount_code, $user ) ) {
        $discount  = rpress_get_discount_by_code( $discount_code );
        $amount    = rpress_format_discount_rate( rpress_get_discount_type( $discount->ID ), rpress_get_discount_amount( $discount->ID ) );
        $discounts = rpress_set_cart_discount( $discount_code );
        $total     = rpress_get_cart_total( $discounts );
        $discount_value = rpress_currency_filter( rpress_format_amount( RPRESS()->cart->get_discounted_amount() ) );
        $return = array(
          'msg'         => 'valid',
          'discount_value' => $discount_value,
          'amount'      => $amount,
          'total_plain' => $total,
          'total'       => html_entity_decode( rpress_currency_filter( rpress_format_amount( $total ) ), ENT_COMPAT, 'UTF-8' ),
          'code'        => $discount_code,
          'html'        => rpress_get_cart_discounts_html( $discounts )
        );
      } else {
        $errors = rpress_get_errors();
        $return['msg']  = $errors['rpress-discount-error'];
        rpress_unset_error( 'rpress-discount-error' );
      }
      // Allow for custom discount code handling
      $return = apply_filters( 'rpress_ajax_discount_response', $return );
      echo wp_json_encode( $return );
    }
    rpress_die();
  }
  /**
   * Removes a discount code from the cart via ajax
   *
   * @since  1.0.0
   * @return void
   */
  public static function remove_discount() {
    if ( ! check_ajax_referer( 'rpress_checkout_nonce', 'security', false ) ) {
      rpress_die();
    }

    if ( isset( $_POST['code'] ) ) {
      rpress_unset_cart_discount( urldecode( sanitize_text_field( wp_unslash( $_POST['code'] ) ) ) );
      $total = rpress_get_cart_total();
      $return = array(
        'total'     => html_entity_decode( rpress_currency_filter( rpress_format_amount( $total ) ), ENT_COMPAT, 'UTF-8' ),
        'code'      => sanitize_text_field( wp_unslash( $_POST['code'] ) ),
        'discounts' => rpress_get_cart_discounts(),
        'html'      => rpress_get_cart_discounts_html()
      );
      echo wp_json_encode( $return );
    }
    rpress_die();
  }
  /**
   * Loads Checkout Login Fields the via AJAX
   *
   * @since 1.0
   * @return void
   */
  public static function checkout_login() {
    if ( ! check_ajax_referer( 'rpress_checkout_nonce', 'security', false ) ) {
      rpress_die();
    }

    do_action( 'rpress_purchase_form_login_fields' );
    rpress_die();
  }
  /**
   * Load Checkout Register Fields via AJAX
   *
   * @since 1.0
   * @return void
  */
  public static function checkout_register() {
    if ( ! check_ajax_referer( 'rpress_checkout_nonce', 'security', false ) ) {
      rpress_die();
    }

    do_action( 'rpress_purchase_form_register_fields' );
    rpress_die();
  }
  /**
   * Recalculate cart taxes
   *
   * @since  1.0.0
   * @return void
   */
  public static function recalculate_taxes() {
    if ( ! check_ajax_referer( 'rpress_checkout_nonce', 'security', false ) ) {
      rpress_die();
    }

    if ( ! rpress_get_cart_contents() ) {
      return false;
    }
    if ( empty( $_POST['billing_country'] ) ) {
      $_POST['billing_country'] = rpress_get_shop_country();
    }
    ob_start();
    rpress_checkout_cart();
    $cart     = ob_get_clean();
    $response = array(
      'html'         => $cart,
      'tax_raw'      => rpress_get_cart_tax(),
      'tax'          => html_entity_decode( rpress_cart_tax( false ), ENT_COMPAT, 'UTF-8' ),
      'tax_rate_raw' => rpress_get_tax_rate(),
      'tax_rate'     => html_entity_decode( rpress_get_formatted_tax_rate(), ENT_COMPAT, 'UTF-8' ),
      'total'        => html_entity_decode( rpress_cart_total( false ), ENT_COMPAT, 'UTF-8' ),
      'total_raw'    => rpress_get_cart_total(),
    );
    echo wp_json_encode( $response );
    rpress_die();
  }
  /**
   * Retrieve a states drop down
   *
   * @since  1.0.0
   * @return void
   */
  public static function get_states() {
    $security = isset( $_REQUEST['security'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['security'] ) ) : '';

    if ( empty( $security ) || ! ( wp_verify_nonce( $security, 'rpress_checkout_nonce' ) || wp_verify_nonce( $security, 'rpress_get_states_nonce' ) ) ) {
      rpress_die();
    }

    if ( empty( $_POST['country'] ) ) {
        $_POST['country'] = rpress_get_shop_country();
    }

    $country = sanitize_text_field( wp_unslash( $_POST['country'] ) );
    $states  = rpress_get_states( $country );

    if ( ! empty( $states ) ) {
        $field_name = isset( $_POST['field_name'] ) ? sanitize_text_field( wp_unslash( $_POST['field_name'] ) ) : '';

        $args = array(
            'name'             => $field_name,
            'id'               => $field_name,
            'class'            => $field_name . ' rpress-select',
            'options'          => $states,
            'show_option_all'  => false,
            'show_option_none' => false,
        );

        $response = RPRESS()->html->select( $args );

        // Escape HTML output
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo $response;

    } else {
        // Escape the string too, just in case
        echo esc_html__( 'nostates', 'restropress' );
    }

    rpress_die();
  }
  /**
   * Search food items
   *
   * @since  1.0.0
   * @return void
   */
  public static function fooditem_search() {
    global $wpdb;
    $search   = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';
    $excludes = ( isset( $_GET['current_id'] ) ? (array) $_GET['current_id'] : array() );
    $excludes = array_unique( array_map( 'absint', $excludes ) );
    $variations = isset( $_GET['variations'] ) ? filter_var( $_GET['variations'], FILTER_VALIDATE_BOOLEAN ) : false;
    $results = array();
    $sql      = "SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = 'fooditem' AND post_title LIKE %s";
    $params   = array( '%' . $wpdb->esc_like( $search ) . '%' );

    if ( ! empty( $excludes ) ) {
      $exclude_placeholders = implode( ',', array_fill( 0, count( $excludes ), '%d' ) );
      $sql                 .= " AND ID NOT IN ($exclude_placeholders)";
      $params               = array_merge( $params, $excludes );
    }

    if ( ! current_user_can( 'edit_products' ) ) {
      $status = apply_filters( 'rpress_product_dropdown_status_nopriv', array( 'publish' ) );
    } else {
      $status = apply_filters( 'rpress_product_dropdown_status', array( 'publish', 'draft', 'private', 'future' ) );
    }
    if ( is_array( $status ) && ! empty( $status ) ) {
      $status               = array_values( array_filter( array_map( 'sanitize_key', $status ) ) );
      if ( ! empty( $status ) ) {
        $status_placeholders  = implode( ',', array_fill( 0, count( $status ), '%s' ) );
        $sql                 .= " AND post_status IN ($status_placeholders)";
        $params               = array_merge( $params, $status );
      } else {
        $sql      .= ' AND post_status = %s';
        $params[]  = 'publish';
      }
    } else {
      $sql      .= ' AND post_status = %s';
      $params[]  = 'publish';
    }

    $sql               .= ' LIMIT 50';
    $prepared_statement = call_user_func_array(
      array( $wpdb, 'prepare' ),
      array_merge( array( $sql ), $params )
    );
    // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter -- Statement is prepared above.
    $items = $wpdb->get_results( $prepared_statement );
    if( $items ) {
      foreach( $items as $item ) {
        $results[] = array(
          'id'   => $item->ID,
          'name' => wp_strip_all_tags( $item->post_title )
        );
        if ( $variations && rpress_has_variable_prices( $item->ID ) ) {
          $prices = rpress_get_variable_prices( $item->ID );
          foreach ( $prices as $key => $value ) {
            $name   = ! empty( $value['name'] )   ? $value['name']   : '';
            $amount = ! empty( $value['amount'] ) ? $value['amount'] : '';
            $index  = ! empty( $value['index'] )  ? $value['index']  : $key;
            if ( $name && $index ) {
              $results[] = array(
                'id'   => $item->ID . '_' . $key,
                'name' => esc_html( $item->post_title . ': ' . $name ),
              );
            }
          }
        }
      }
    } else {
      $results[] = array(
        'id'   => 0,
        'name' => __( 'No results found', 'restropress' )
      );
    }
    echo wp_json_encode( $results );
    rpress_die();
  }
  /**
   * Search the customers database via AJAX
   *
   * @since  1.0.0
   * @return void
   */
  public static function customer_search() {
    global $wpdb;
    $search  = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';
    $results = array();
    $customer_view_role = apply_filters( 'rpress_view_customers_role', 'view_shop_reports' );
    if ( ! current_user_can( $customer_view_role ) ) {
      $customers = array();
    } else {
      $table_name = esc_sql( $wpdb->prefix . 'rpress_customers' );
      if ( is_numeric( $search ) ) {
        $like_value = '%' . $wpdb->esc_like( $search ) . '%';
        $customers  = $wpdb->get_results(
          $wpdb->prepare(
            "SELECT id, name, email FROM {$table_name} WHERE id LIKE %s OR user_id LIKE %s LIMIT 50",
            $like_value,
            $like_value
          )
        );
      } else {
        $like_value = '%' . $wpdb->esc_like( $search ) . '%';
        $customers  = $wpdb->get_results(
          $wpdb->prepare(
            "SELECT id, name, email FROM {$table_name} WHERE name LIKE %s OR email LIKE %s LIMIT 50",
            $like_value,
            $like_value
          )
        );
      }
    }
    if( $customers ) {
      foreach( $customers as $customer ) {
        $customer_name  = isset( $customer->name ) ? wp_strip_all_tags( $customer->name ) : '';
        $customer_email = isset( $customer->email ) ? sanitize_email( $customer->email ) : '';
        $results[] = array(
          'id'   => $customer->id,
          'name' => $customer_name . '(' .  $customer_email . ')'
        );
      }
    } else {
      $results[] = array(
        'id'   => 0,
        'name' => __( 'No results found', 'restropress' )
      );
    }
    echo wp_json_encode( $results );
    rpress_die();
  }
  /**
   * Search the users database via AJAX
   *
   * @since 1.0.0
   * @return void
   */
  public static function user_search() {
    global $wpdb;
    $search         = isset( $_GET['s'] ) ? esc_sql( sanitize_text_field( wp_unslash( $_GET['s'] ) ) ) : '';
    $results        = array();
    $user_view_role = apply_filters( 'rpress_view_users_role', 'view_shop_reports' );
    if ( ! current_user_can( $user_view_role ) ) {
      $results = array();
    } else {
      $user_args = array(
        'search' => '*' . esc_attr( $search ) . '*',
        'number' => 50,
      );
      $users = get_users( $user_args );
    }
    if ( $users ) {
      foreach( $users as $user ) {
        $results[] = array(
          'id'   => $user->ID,
          'name' => wp_strip_all_tags( $user->display_name ),
        );
      }
    } else {
      $results[] = array(
        'id'   => 0,
        'name' => __( 'No users found', 'restropress' )
      );
    }
    echo wp_json_encode( $results );
    rpress_die();
  }
  /**
   * Searches for users via ajax and returns a list of results
   *
   * @since  1.0.0
   * @return void
   */
  public static function search_users() {
    if( current_user_can( 'manage_shop_settings' ) ) {
      $search_query = isset( $_POST['user_name'] ) ? trim( sanitize_text_field( wp_unslash( $_POST['user_name'] ) ) ) : '';
      $exclude      = isset( $_POST['exclude'] ) ? trim( sanitize_text_field( wp_unslash( $_POST['exclude'] ) ) ) : '';
      $get_users_args = array(
        'number' => 9999,
        'search' => $search_query . '*'
      );
      if ( ! empty( $exclude ) ) {
        $exclude_array = explode( ',', $exclude );
        $get_users_args['exclude'] = $exclude_array;
      }
      $get_users_args = apply_filters( 'rpress_search_users_args', $get_users_args );
      $found_users = apply_filters( 'rpress_ajax_found_users', get_users( $get_users_args ), $search_query );
      $user_list = '<ul>';
      if( $found_users ) {
        foreach( $found_users as $user ) {
          $user_list .= '<li><a href="#" data-userid="' . esc_attr( $user->ID ) . '" data-login="' . esc_attr( $user->user_login ) . '">' . esc_html( $user->user_login ) . '</a></li>';
        }
      } else {
        $user_list .= '<li>' . __( 'No users found', 'restropress' ) . '</li>';
      }
      $user_list .= '</ul>';
      echo wp_json_encode( array( 'results' => $user_list ) );
    }
    die();
  }
  /**
   * Check for new orders and send notification
   *
   * @since       2.0.1
   * @param       void
   * @return      json | user notification json object
   */
  public static function check_new_orders() {
    $orders_cap = apply_filters( 'rpress_check_new_orders_cap', 'edit_shop_payments' );
    if ( ! current_user_can( $orders_cap ) ) {
      wp_send_json_error(
        array(
          'message' => esc_html__( 'You do not have permission to access this resource.', 'restropress' ),
        ),
        403
      );
    }

    check_ajax_referer( 'rpress-check-new-orders', 'security' );

    $last_order = get_option( 'rp_last_order_id' );
    $order      = rpress_get_payments( array( 'number' => 1, 'status' => array( 'publish'     => __( 'Paid', 'restropress' ), 'processing'  => __( 'Processing', 'restropress' )) ) );
    if( is_array( $order ) && $order[0]->ID != $last_order ) {
      $payment_id = $order[0]->ID;
      $payment  = new RPRESS_Payment( $payment_id );
      $placeholder = array( '{order_id}' => $payment_id );
      $service_type = get_post_meta( $payment_id, '_rpress_delivery_type', true );
      if ( ! empty( $service_type ) ) {
        $service_type = ucfirst( $service_type );
      }
      $service_date = get_post_meta( $payment_id, '_rpress_delivery_date', true );
      if ( ! empty( $service_date ) ) {
        $service_date = rpress_local_date( $service_date );
      }
      $payment_status = $payment->status;
      if ( $payment_status == 'publish' ) {
        $payment_status = 'Paid';
      }
      $payment_status = ucfirst( $payment_status );
      $search = array( '{order_id}', '{service_type}', '{payment_status}', '{service_date}' );
      $replace = array( $payment_id, $service_type, $payment_status, $service_date );
      $body = rpress_get_option( 'notification_body' );
      $body = str_replace( $search, $replace, $body );
      $notification = array(
        'title' => rpress_get_option( 'notification_title' ),
        'body'  => $body,
        'icon'  => rpress_get_option( 'notification_icon' ),
        'sound' => rpress_get_option( 'notification_sound' ),
        'url'   => admin_url( 'admin.php?page=rpress-payment-history&view=view-order-details&id=' . $payment_id )
      );
      update_option( 'rp_last_order_id', $payment_id  );
      wp_send_json( $notification );
    }
    wp_die();
  }
  /**
   * Activate addon license with ajax call
   *
   * @since 2.5
   * @author RestrPress
   */
  public static function activate_addon_license() {

    check_ajax_referer( 'activate-license', 'security' );

    if ( ! self::can_manage_addon_licenses() ) {
      wp_send_json_error(
        array(
          'message' => esc_html__( 'You do not have permission to manage addon licenses.', 'restropress' ),
        ),
        403
      );
    }

    // listen for our activate button to be clicked
    if( isset( $_POST['license_key'] ) ) {
      // Get the license from the user
      // Item ID (Normally a 2 or 3 digit code)
      $item_id = isset( $_POST['item_id'] ) ? absint( $_POST['item_id'] ) : '';
      // The actual license code
      $license = isset( $_POST['license'] ) ? trim( sanitize_text_field( $_POST['license'] ) ) : '';
      // Name of the addon (Print Receipts)
      $name = isset( $_POST['product_name'] ) ? sanitize_text_field( $_POST['product_name'] )  : '';
      // Key to be saved in to DB
      $license_key = isset( $_POST['license_key'] ) ? self::sanitize_addon_license_option_key( wp_unslash( $_POST['license_key'] ) ) : '';
      if ( empty( $license_key ) ) {
        wp_send_json_error(
          array(
            'message' => esc_html__( 'Invalid license key reference.', 'restropress' ),
          ),
          400
        );
      }
      // data to send in our API request
      $api_params = array(
        'edd_action' => 'activate_license',
        'item_id'    => $item_id,
        'item_name'  => urlencode( $name ),
        'license'    => $license,
        'url'        => home_url()
      );
      // Call the custom API.
      $verify_ssl = (bool) apply_filters( 'rpress_remote_request_verify_ssl', true );
      $response = wp_remote_post( 'https://www.restropress.com', array( 'timeout' => 15, 'sslverify' => $verify_ssl, 'body' => $api_params ) );
      // make sure the response came back okay
      if ( is_wp_error( $response )
        || 200 !== wp_remote_retrieve_response_code( $response ) ) {
        if ( is_wp_error( $response ) ) {
          $message = $response->get_error_message();
        }
        else {
          $message = __( 'An error occurred, please try again.' );
        }
      } else {
        $license_data = json_decode( wp_remote_retrieve_body( $response ) );
        if ( false === $license_data->success ) {
          switch( $license_data->error ) {
              case 'expired' :
                $message = sprintf(
                  __( 'Your license key expired on %s.' ),
                  date_i18n( get_option( 'date_format' ), strtotime( $license_data->expires, current_time( 'timestamp' ) ) )
                );
                break;
              case 'revoked' :
                $message = __( 'Your license key has been disabled.' );
                break;
              case 'missing' :
                $message = __( 'Invalid license.' );
                break;
              case 'invalid' :
              case 'site_inactive' :
                $message = __( 'Your license is not active for this URL.' );
                break;
              case 'item_name_mismatch' :
                $message = sprintf( __( 'This appears to be an invalid license key for %s.' ), $name );
                break;
              case 'no_activations_left':
                $message = __( 'Your license key has reached its activation limit.' );
                break;
              default :
                $message = __( 'An error occurred, please try again.' );
                break;
          }
        }
      }
      // Check if anything passed on a message constituting a failure
      if ( ! empty( $message ) )
        $return = array( 'status' => 'error', 'message' => $message );
      else {
        //Save the license key in database
        update_option( $license_key, $license );
        // $license_data->license will be either "valid" or "invalid"
        update_option( $license_key . '_status', $license_data->license );
        $return = array( 'status' => 'updated', 'message' => 'Your license is successfully activated.' );
      }
      echo wp_json_encode( $return );
      wp_die();
    }
  }
  /**
   * Deactivate the license of plugin with AJAX call
   *
   * @since 2.5
   * @author RestroPress
   * @return void
   */
  public static function deactivate_addon_license() {

    check_ajax_referer( 'deactivate-license', 'security' );

    if ( ! self::can_manage_addon_licenses() ) {
      wp_send_json_error(
        array(
          'message' => esc_html__( 'You do not have permission to manage addon licenses.', 'restropress' ),
        ),
        403
      );
    }

    if( isset($_POST['license_key']) ) {
      $license_key = isset( $_POST['license_key'] ) ? self::sanitize_addon_license_option_key( wp_unslash( $_POST['license_key'] ) ) : '';
      if ( empty( $license_key ) ) {
        wp_send_json_error(
          array(
            'message' => esc_html__( 'Invalid license key reference.', 'restropress' ),
          ),
          400
        );
      }
      // retrieve the license from the database
      $license = trim( get_option( $license_key ) );
      $item_name = isset( $_POST['product_name'] ) ? sanitize_text_field( $_POST['product_name'] ) : '';
      // data to send in our API request
      $api_params = array(
        'edd_action' => 'deactivate_license',
        'license'    => $license,
        'item_name'  => urlencode( $item_name ), // the name of our product in EDD
        'url'        => home_url()
      );
      // Call the custom API.
      $verify_ssl = (bool) apply_filters( 'rpress_remote_request_verify_ssl', true );
      $response = wp_remote_post( 'https://www.restropress.com', array( 'timeout' => 15, 'sslverify' => $verify_ssl, 'body' => $api_params ) );
      // make sure the response came back okay
      if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
        if ( is_wp_error( $response ) ) {
          $message = $response->get_error_message();
        } else {
          $message = __( 'An error occurred, please try again.', 'restropress' );
        }
        $return = array( 'status' => 'error', 'message' => $message );
      } else{
        // decode the license data
        $license_data = json_decode( wp_remote_retrieve_body( $response ) );
        // $license_data->license will be either "deactivated" or "failed"
        if( $license_data->license == 'deactivated' ) {
          delete_option( $license_key . '_status' );
          delete_option( $license_key );
        }
        $return = array( 'status' => 'updated', 'message' => __( 'License successfully deactivated.', 'restropress' ) );
      }
      echo wp_json_encode( $return );
      wp_die();
    }
  }

  /**
   * Check whether the current user can manage addon licenses.
   *
   * @since 3.2.8
   * @return bool
   */
  private static function can_manage_addon_licenses() {
    return current_user_can( 'manage_shop_settings' );
  }

  /**
   * Validate the stored option name used for addon license data.
   *
   * @since 3.2.8
   * @param string $license_key Raw option name from the request.
   * @return string
   */
  private static function sanitize_addon_license_option_key( $license_key ) {
    $license_key = sanitize_key( $license_key );

    if ( empty( $license_key ) || '_license' !== substr( $license_key, -8 ) ) {
      return '';
    }

    return $license_key;
  }
  /**
   * Show order details with AJAX call
   *
   * @since 2.7.2
   * @author RestroPress
   * @return void
   */
  public static function show_order_details() {
    
    check_ajax_referer( 'show-order-details', 'security' );
    $order_id = isset( $_POST['order_id'] ) ? absint( wp_unslash( $_POST['order_id'] ) ) : 0;

    if ( ! self::can_access_frontend_order_action( $order_id ) ) {
      wp_send_json_error(
        array(
          'message' => esc_html__( 'You do not have permission to view this order.', 'restropress' ),
        ),
        403
      );
    }

    $_POST['order_id'] = $order_id;
    ob_start();
    rpress_get_template_part( 'rpress', 'show-order-details' );
    $html = ob_get_clean();
    $response = array(
      'html' => $html,
    );
    wp_send_json_success( $response );
    rpress_die();
  }
  /**
   * Infinite Scroll more order history 
   * @since 2.7.3
   * @author RestroPress
   * @return json
   */
  public static function more_order_history() {
    check_ajax_referer( 'show-order-details', 'security' );

    if ( ! is_user_logged_in() ) {
      wp_send_json_error(
        array(
          'message' => esc_html__( 'You must be logged in to view order history.', 'restropress' ),
        ),
        403
      );
    }

    ob_start();
    include RP_PLUGIN_DIR . '/templates/rpress-order-history-load-more.php';
    $html = ob_get_clean();
    wp_send_json_success( [ 'html' => $html, 'found_post' => $found_post ] );
    rpress_die();
  }
  public static function delete_user_address(){
    check_ajax_referer( 'rpress-user-address', 'security' );

    if ( ! is_user_logged_in() ) {
      wp_send_json_error( array( 'success' => false ), 403 );
    }

    if( isset( $_POST['index'] ) ) {
      $index    = absint( wp_unslash( $_POST['index'] ) );
      $user_id  = get_current_user_id();
      // Get user addresses
      $user_addresses = get_user_meta($user_id, 'user_addresses', true);
      
      if(!empty($user_addresses) && isset( $user_addresses[ $index ] )){
          // Remove the address array from the main array
          unset($user_addresses[$index]);
          
          // Update user meta data
          $updated = update_user_meta($user_id, 'user_addresses', $user_addresses);
          
          if($updated){
              // Return success response
              echo wp_json_encode(['success' => true]);
          } else {
              // Return failure response
              echo wp_json_encode(['success' => false]);
          }
      } else {
          // No addresses found
          echo wp_json_encode(['success' => false]);
      }
    }
  }
  public static function default_user_address(){
    check_ajax_referer( 'rpress-user-address', 'security' );

    if ( ! is_user_logged_in() ) {
      wp_send_json_error( array( 'success' => false ), 403 );
    }

    if( isset( $_POST['index'] ) ) {
      $index    = absint( wp_unslash( $_POST['index'] ) );
      $user_id  = get_current_user_id();
      // Get user addresses
      $user_addresses = get_user_meta( $user_id, 'user_addresses', true );
      if ( empty( $user_addresses ) || ! isset( $user_addresses[ $index ] ) ) {
        echo wp_json_encode( ['success' => false] );
        return;
      }
      $default_address = $user_addresses[$index];
      
      $new_address = array(
        'address'         => $default_address['address'] ,
        'flat'            => $default_address['apt_suite'],
        'city'            => $default_address['city'],
        'postcode'        => $default_address['pincode'],  
      );
      
      update_user_meta( $user_id, 'first_name', $default_address['first_name'] );
      update_user_meta( $user_id, 'last_name', $default_address['last_name'] );
      update_user_meta( $user_id, '_rpress_phone', $default_address['phone'] );
      update_user_meta( $user_id, '_rpress_user_delivery_address', $new_address );
       
      $updated = update_user_meta( $user_id, 'user_default_address_index', $index );
      
      if ( $updated ) {
        
          echo wp_json_encode( ['success' => true] );
      } else {
           
          echo wp_json_encode( ['success' => false] );
      }
      
    }
  }
  /**
   * Get Delivery address
   * @since 2.7.3
   * @author Magnigeeks
   * @return json
   */
  public static function checkout_update_service_option() {
    check_ajax_referer( 'update-service', 'security' );
    do_action( 'rpress_checkout_service_option_updated' );
    ob_start();
    rpress_order_details_fields();
    $order_html = ob_get_clean();
    ob_start();
    rpress_get_template_part( 'checkout_cart' );
    $cart_html = ob_get_clean();
    
    $total = rpress_get_cart_total();
    $subtotal = rpress_get_cart_subtotal();
    $total_amount_html = '<span class="rpress_cart_amount" data-subtotal="' . rpress_format_amount( $subtotal ) . '" data-total="'. rpress_format_amount( $total ) .'">'. rpress_currency_filter( rpress_format_amount( $total ) ) .'</span>';
    $data = [ 'order_html' => $order_html, 'cart_html' => $cart_html,'total_amount' => $total_amount_html ];
    $response = apply_filters( 'rpress_checkout_update_service_option_response', $data );
    wp_send_json_success( $response );
    rpress_die();
  }
  public static function remove_fees_after_empty_cart() {
    check_ajax_referer( 'clear-cart', 'security' );
    
    RPRESS()->session->set('rpress_cart', null);
    // Remove all cart fees.
    RPRESS()->session->set('rpress_cart_fees', null);
    // Remove any resuming payments.
    RPRESS()->session->set('rpress_resume_payment', null);
    
    // You can also send a response back to the AJAX request if needed
    $response = array('message' => 'Cart emptied successfully');
    wp_send_json($response);
    
    // Make sure to exit to prevent any additional output
    exit;
  }

  public static function update_modal_on_service_switch() {
    check_ajax_referer( 'service-type', 'security' );

    $service_type = isset( $_GET['service_type'] ) ? sanitize_text_field( wp_unslash( $_GET['service_type'] ) ) : '';
   
    ob_start();
    rpress_get_template_part('rpress','datetime-popup');
    $modal_html = ob_get_clean();
    ob_start();
    $template = rpress_get_option('template', 'list');
    rpress_get_template_part($template . '/time-option');
    $time_option_html = ob_get_clean();
    wp_send_json_success(['modal_html' => $modal_html, 'time_option_html' => $time_option_html]);
    wp_die( );
  }
}
RP_AJAX::init();
