<?php
if (!defined('ABSPATH')) {
  exit; // Exit if accessed directly.
}
/*
 * @package shop builder
 * since 1.0.0
 * 
*/


// image size
add_image_size('storzen_255x283', 255, 283, true);
add_image_size('storzen_260x290', 260, 290, false);
add_image_size('storzen_152x244', 152, 244, false);
add_image_size('storzen_540x728', 540, 728, false);



if (!function_exists('storzen_post_query')) {
  function storzen_post_query($post_type)
  {
    $post_list = get_posts(array(
      'post_type' => $post_type,
      'showposts' => -1,
    ));
    $posts = array();

    if (!empty($post_list) && !is_wp_error($post_list)) {
      foreach ($post_list as $post) {
        $options[$post->ID] = $post->post_title;
      }
      return $options;
    }
  }
}

if (!function_exists('storzen_post_category')) {
  //select category
  function storzen_post_category($terms = 'product_cat')
  {
    /**
     * One cached list per request. Elementor's editor AJAX calls register_controls() on
     * every widget; many widgets each used this twice (include + exclude), which
     * duplicated get_terms() dozens of times and timed out the panel (spinner).
     */
    static $cached_options = null;
    if ($cached_options !== null) {
      return $cached_options;
    }

    /**
     * Cap terms so Elementor editor AJAX (widget controls config) does not time out
     * or return oversized JSON when many categories exist.
     *
     * @param int $max Maximum terms to load.
     */
    $max = (int) apply_filters('storzen_post_category_max_terms', 200);

    $categories = get_terms(array(
      'taxonomy' => 'product_cat',
      'hide_empty' => false,
      'number' => $max > 0 ? $max : 200,
    ));

    $options = array();

    if (!is_wp_error($categories) && !empty($categories)) {
      foreach ($categories as $category) {
        // Handle both array and object formats
        $term_id = is_array($category) ? $category['term_id'] : $category->term_id;
        $name = is_array($category) ? $category['name'] : $category->name;

        $options[$term_id] = $name;
      }
    }

    $cached_options = $options;
    return $cached_options;
  }
}

if (!function_exists('storzen_select_post')) {
  //select post 
  function storzen_select_post()
  {

    $args       = array('post_type' => 'product', 'posts_per_page' => -1);
    $post_lists = [];

    if ($postlists = get_posts($args)) {
      foreach ($postlists as $postlist) {
        (int) $post_lists[$postlist->ID] = $postlist->post_title;
      }
    } else {
      (int) $post_lists['0'] = esc_html__('No Post Found', 'storzen');
    }

    return $post_lists;
  }
}

if (!function_exists('storzen_get_cat_name')) {
  function storzen_get_cat_name($cat_id)
  {
    $cat_id   = (int) $cat_id;
    $category = get_term($cat_id, 'product_cat');

    if (!$category || is_wp_error($category)) {
      return '';
    }

    return $category->name;
  }
}

if (!function_exists('storzen_get_cat_slug')) {
  // category slug
  function storzen_get_cat_slug($cat_id)
  {
    $cat_id   = (int) $cat_id;
    $category = get_term($cat_id, 'product_cat');

    if (!$category || is_wp_error($category)) {
      return '';
    }

    return $category->slug;
  }
}


if (!function_exists('storzen_slug')) {
  function storzen_slug()
  {
    global $post;

    $storzen_link = get_permalink($post->ID);

    if (empty($storzen_link)) {
      return FALSE;
    } else {
      $storzen_link = str_replace(home_url('/'), '', $storzen_link);
      return $storzen_link;
    }
  }
}


if (!function_exists('storzen_get_template')) :
  function storzen_get_template($template_name = null)
  {
    $template_path = apply_filters('storzen-elementor/template-path', 'elementor-templates/');
    $template = locate_template($template_path . $template_name);
    if (!$template) {
      $template = STORZEN_ELEMENTOR  . '/templates/' . $template_name;
    }
    if (file_exists($template)) {
      return $template;
    } else {
      return false;
    }
  }
endif;


if (!function_exists('storzen_display_percentage_on_sale_badge')) {
  function storzen_display_percentage_on_sale_badge()
  {
    global $product;

    if ($product->is_on_sale()) {
      $discount = 0;

      if ($product->is_type('variable')) {
        // Get the variation prices
        $prices = $product->get_variation_prices();

        // Get the minimum regular price for the variable product
        $min_regular_price = min($prices['regular_price']);

        // Get the minimum sale price for the variable product
        $min_sale_price = min(array_filter($prices['sale_price']));

        if ($min_regular_price > 0) {
          $discount = round((($min_regular_price - $min_sale_price) / $min_regular_price) * 100);
        }
      } else {
        $regular_price = $product->get_regular_price();
        if ($regular_price) {
          $sale_price = $product->get_sale_price();
          $discount = round((($regular_price - $sale_price) / $regular_price) * 100);
        }
      }

      if ($discount > 0) {
        echo '<span class="bgc-primary">' . esc_html((string) $discount) . '% </span>';
      }
    }
  }
}



if (!function_exists('storzen_add_to_cart_button')) {
  function storzen_add_to_cart_button()
  {
    global $product;
    $storzen_ajax_cart_class = (get_option('woocommerce_enable_ajax_add_to_cart') == 'yes' ? 'storzen_ajax' : '');
    if ($product->is_type('variable')) {

      return sprintf(
        '<a href="%s" class="%s">%s</a>',
        esc_url($product->add_to_cart_url()),
        esc_attr(implode(' ', array_filter(array(
          'button',
          'product_type_' . $product->get_type(),
          'swp-readmore-arrow swp-add-to-cart'
        )))),
        '<i class="fas fa-cart-shopping" aria-hidden="true"></i>'
      );
    } else {
      // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- WooCommerce wc_implode_html_attributes returns sanitized attribute string.
      return sprintf(
        '<a href="%s" data-quantity="1" class="%s" %s>%s</a>',
        esc_url($product->add_to_cart_url()),
        esc_attr(implode(' ', array_filter(array(
          'button',
          'product_type_' . $product->get_type(),
          $product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
          $product->supports('ajax_add_to_cart') ? 'swp-readmore-arrow swp-add-to-cart ajax_add_to_cart' : 'swp-readmore-arrow swp-add-to-cart ',
          $storzen_ajax_cart_class
        )))),
        wc_implode_html_attributes(array(
          'data-product_id'  => $product->get_id(),
          'data-product_sku' => $product->get_sku(),
          'aria-label'       => $product->add_to_cart_description(),
          'rel'              => 'nofollow',
        )),
        '<i class="fas fa-cart-shopping" aria-hidden="true"></i>'
      );
    }
  }
}


if (!function_exists('storzen_add_to_cart_text_button')) {
  function storzen_add_to_cart_text_button()
  {
    global $product;
    $storzen_ajax_cart_class = (get_option('woocommerce_enable_ajax_add_to_cart') == 'yes' ? 'storzen_ajax' : '');
    if ($product->is_type('variable')) {

      echo sprintf(
        '<a href="%s" class="%s">%s</a>',
        esc_url($product->add_to_cart_url()),
        esc_attr(implode(' ', array_filter(array(
          'button',
          'product_type_' . $product->get_type(),
          'swp-readmore-arrow swp-add-to-cart swp-readmore-arrow-btn'
        )))),
        esc_html($product->add_to_cart_text())
      );
    } else {
      // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- WooCommerce wc_implode_html_attributes returns sanitized attribute string.
      echo sprintf(
        '<a href="%s" data-quantity="1" class="%s" %s>%s</a>',
        esc_url($product->add_to_cart_url()),
        esc_attr(implode(' ', array_filter(array(
          'button',
          'product_type_' . $product->get_type(),
          $product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
          $product->supports('ajax_add_to_cart') ? 'swp-readmore-arrow swp-add-to-cart ajax_add_to_cart swp-readmore-arrow-btn' : 'swp-readmore-arrow swp-add-to-cart swp-readmore-arrow-btn',
          $storzen_ajax_cart_class
        )))),
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- WooCommerce wc_implode_html_attributes returns sanitized attribute string.
        wc_implode_html_attributes(array(
          'data-product_id'  => $product->get_id(),
          'data-product_sku' => $product->get_sku(),
          'aria-label'       => $product->add_to_cart_description(),
          'rel'              => 'nofollow',
        )),
        esc_html($product->add_to_cart_text())
      );
    }
  }
}



if (!function_exists('storzen_invert_formatted_sale_price')) {
  add_filter('woocommerce_format_sale_price', 'storzen_invert_formatted_sale_price', 10, 3);
  function storzen_invert_formatted_sale_price($price, $regular_price, $sale_price)
  {
    return '<ins>' . (is_numeric($sale_price) ? wc_price($sale_price) : $sale_price) . '</ins> <del>' . (is_numeric($regular_price) ? wc_price($regular_price) : $regular_price) . '</del>';
  }
}

if (!function_exists('storzen_body_classes')) {
  function storzen_body_classes($classes)
  {
    $classes[] = 'storzenduct';

    return $classes;
  }
  add_filter('body_class', 'storzen_body_classes');
}


if (!function_exists('storzen_elementor_style_options')) :
  function storzen_elementor_style_options($agrs, $label, $selector, $condition, $style = 'color', $typo = true, $color = true)
  {

    if ($style == 'background-color') :
      if ($color) :
        $agrs->add_control(
          str_replace(' ', '_', $label) . '_color',
          [
            'label' => __('Background Color', 'storzen'),
            'type' => \Elementor\Controls_Manager::COLOR,
            'selectors' => [
              $selector => $style . ': {{VALUE}} !important;',
            ],
            'condition' => [
              'style' => $condition
            ]
          ]
        );
      endif;
      return;
    endif;

    //Label
    $agrs->add_control(
      str_replace(' ', '_', $label) . '_title',
      [
        'type' => \Elementor\Controls_Manager::HEADING,
        // phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText -- Dynamic label passed by caller.
        'label' => __($label, 'storzen'),
        'separator' => 'after',
        'condition' => [
          'style' => $condition
        ]
      ]
    );

    $agrs->add_responsive_control(
      str_replace(' ', '_', $label) . '_padding',
      [
        'label' => __(' Padding', 'storzen'),
        'type' => \Elementor\Controls_Manager::DIMENSIONS,
        'size_units' => ['px', 'em', '%'],
        'selectors' => [
          $selector => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
        ],
        'condition' => [
          'style' => $condition
        ]
      ]
    );

    $agrs->add_responsive_control(
      str_replace(' ', '_', $label) . '_margin',
      [
        'label' => __(' Margin', 'storzen'),
        'type' => \Elementor\Controls_Manager::DIMENSIONS,
        'size_units' => ['px', 'em', '%'],
        'selectors' => [
          $selector => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
        ],
        'condition' => [
          'style' => $condition
        ]
      ]
    );

    if ($typo) :
      $agrs->add_group_control(
        \Elementor\Group_Control_Typography::get_type(),
        [
          'name' => str_replace(' ', '_', $label) . '_typo',
          'label' => esc_html__(' Typography', 'storzen'),
          'selector' => $selector,
          'condition' => [
            'style' => $condition
          ]
        ]
      );

    endif;
    if ($color) :
      $agrs->add_control(
        str_replace(' ', '_', $label) . '_color',
        [
          'label' => __('Color', 'storzen'),
          'type' => \Elementor\Controls_Manager::COLOR,
          'selectors' => [
            $selector => $style . ': {{VALUE}} !important;',
          ],
          'condition' => [
            'style' => $condition
          ]
        ]
      );
    endif;
  }
endif;

if (!function_exists('storzen_elementor_sidebar_filter_widget_style_sections')) :
  /**
   * Style tab for standalone Sidebar Filter widgets (Search / list filters).
   *
   * @param \Elementor\Widget_Base $widget  Elementor widget instance ($this).
   * @param string                 $variant 'list' (categories, attributes, stock, ratings) or 'search'.
   */
  function storzen_elementor_sidebar_filter_widget_style_sections($widget, $variant = 'list')
  {
    $c = array('style-1');
    $widget->start_controls_section(
      'sidebar_style',
      array(
        'label' => esc_html__('Sidebar Style', 'storzen'),
        'tab'   => \Elementor\Controls_Manager::TAB_STYLE,
      )
    );
    storzen_elementor_style_options($widget, 'Widget Title', '{{WRAPPER}} .shop-sidebar .widget-title', $c);
    if ('search' === $variant) {
      storzen_elementor_style_options($widget, 'Search Input', '{{WRAPPER}} .shop-sidebar .szp-keyword-input', $c);
      storzen_elementor_style_options($widget, 'Search Button', '{{WRAPPER}} .shop-sidebar .szp-keyword-filter-form button', $c);
    } else {
      storzen_elementor_style_options($widget, 'Filter Link', '{{WRAPPER}} .shop-sidebar .szp-filter-link', $c);
      storzen_elementor_style_options($widget, 'Filter Count', '{{WRAPPER}} .shop-sidebar .szp-filter-link span', $c);
      storzen_elementor_style_options($widget, 'Active Filter', '{{WRAPPER}} .shop-sidebar .szp-filter-link.is-active', $c);
      storzen_elementor_style_options($widget, 'Active Filter Background', '{{WRAPPER}} .shop-sidebar .szp-filter-link.is-active', $c, 'background-color', false, true);
    }
    $widget->end_controls_section();
  }
endif;

if (!function_exists('storzen_elementor_shop_sidebar_content_style_section')) :
  /**
   * Product grid / archive content styles (Shop With Sidebar, Sidebar Filter AJAX — widgets that render the grid).
   * Selectors use {{WRAPPER}}; standalone filter widgets (e.g. Search only) do not include this section.
   *
   * @param \Elementor\Widget_Base $widget Elementor widget instance ($this).
   */
  function storzen_elementor_shop_sidebar_content_style_section($widget)
  {
    $c = array('style-1');
    $widget->start_controls_section(
      'content_style',
      array(
        'label' => esc_html__('Content Style', 'storzen'),
        'tab'   => \Elementor\Controls_Manager::TAB_STYLE,
      )
    );
    storzen_elementor_style_options($widget, 'Title', '{{WRAPPER}} .content .woo-title', $c);
    storzen_elementor_style_options($widget, 'Category', '{{WRAPPER}} .content .category', $c);
    storzen_elementor_style_options($widget, 'Pricing', '{{WRAPPER}} .prices span', $c);
    storzen_elementor_style_options($widget, 'New Badge', '{{WRAPPER}} .bgc-black', $c);
    storzen_elementor_style_options($widget, 'New Badge Background', '{{WRAPPER}} .bgc-black', $c, 'background-color', false, true);
    storzen_elementor_style_options($widget, 'Sale Badge', '{{WRAPPER}} .bgc-primary', $c);
    storzen_elementor_style_options($widget, 'Sale Badge Background', '{{WRAPPER}} .bgc-primary', $c, 'background-color', false, true);
    storzen_elementor_style_options($widget, 'List Description', '{{WRAPPER}} .shop-list-sidebar .content p', $c);
    storzen_elementor_style_options($widget, 'List Rating Stars', '{{WRAPPER}} .shop-list-sidebar .ratting i', $c);
    storzen_elementor_style_options($widget, 'Action Icons', '{{WRAPPER}} .shop-card-items .social-style-two i, {{WRAPPER}} .shop-list-sidebar .cart-btns i, {{WRAPPER}} .shop-list-sidebar .shop-icon i', $c);
    storzen_elementor_style_options($widget, 'No Products Message', '{{WRAPPER}} .no-post-found', $c);
    $widget->end_controls_section();
  }
endif;

if (!function_exists('storzen_elementor_button_style_options')) :
  function storzen_elementor_button_style_options($init, $label, $selector, $hover_bg_selector = '', $condition = 'layout_one')
  {
    //Label
    $init->add_control(
      str_replace(' ', '_', $label) . '_subtitle_label',
      [
        'type' => \Elementor\Controls_Manager::HEADING,
        // phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText -- Dynamic label passed by caller.
        'label' => __($label, 'storzen'),
        'separator' => 'after',
        'condition' => [
          'style' => $condition
        ]
      ]
    );

    $init->add_responsive_control(
      str_replace(' ', '_', $label) . '_padding',
      [
        'label' => __('Padding', 'storzen'),
        'type' => \Elementor\Controls_Manager::DIMENSIONS,
        'size_units' => ['px', 'em', '%'],
        'selectors' => [
          $selector => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
        ],
        'condition' => [
          'style' => $condition
        ]
      ]
    );

    $init->add_group_control(
      \Elementor\Group_Control_Typography::get_type(),
      [
        'name' => str_replace(' ', '_', $label) . '_typography',
        'selector' => $selector,
        'condition' => [
          'style' => $condition
        ]
      ]
    );

    $init->add_group_control(
      \Elementor\Group_Control_Border::get_type(),
      [
        'name' => str_replace(' ', '_', $label) . '_border',
        'selector' => $selector,
        'condition' => [
          'style' => $condition
        ]
      ]
    );

    $init->add_control(
      str_replace(' ', '_', $label) . '_border_radius',
      [
        'label' => __('Border Radius', 'storzen'),
        'type' => \Elementor\Controls_Manager::DIMENSIONS,
        'size_units' => ['px', '%'],
        'selectors' => [
          $selector => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
        ],
        'condition' => [
          'style' => $condition
        ]
      ]
    );

    $init->add_group_control(
      \Elementor\Group_Control_Box_Shadow::get_type(),
      [
        'name' => str_replace(' ', '_', $label) . '_box_shadow',
        'selector' => $selector,
        'condition' => [
          'style' => $condition
        ]
      ]
    );

    $init->add_control(
      str_replace(' ', '_', $label) . '_hr',
      [
        'type' => \Elementor\Controls_Manager::DIVIDER,
        'style' => 'thick',
        'condition' => [
          'style' => $condition
        ]
      ]
    );

    $init->start_controls_tabs(str_replace(' ', '_', $label) . '_tabs_button');

    $init->start_controls_tab(
      str_replace(' ', '_', $label) . '_tab_button_normal',
      [
        'label' => __('Normal', 'storzen'),
        'condition' => [
          'style' => $condition
        ]
      ]
    );

    $init->add_control(
      str_replace(' ', '_', $label) . '_color',
      [
        'label' => __('Text Color', 'storzen'),
        'type' => \Elementor\Controls_Manager::COLOR,
        'default' => '',
        'selectors' => [
          $selector => 'color: {{VALUE}};',
        ],
        'condition' => [
          'style' => $condition
        ]
      ]
    );

    $init->add_control(
      str_replace(' ', '_', $label) . '_bg_color',
      [
        'label' => __('Background Color', 'storzen'),
        'type' => \Elementor\Controls_Manager::COLOR,
        'selectors' => [
          $selector => 'background-color: {{VALUE}} !important;',
        ],
        'condition' => [
          'style' => $condition
        ]
      ]
    );

    $init->end_controls_tab();

    $init->start_controls_tab(
      str_replace(' ', '_', $label) . '_tab_button_hover',
      [
        'label' => __('Hover', 'storzen'),
        'condition' => [
          'style' => $condition
        ]
      ]
    );

    $init->add_control(
      str_replace(' ', '_', $label) . '_hover_color',
      [
        'label' => __('Text Color', 'storzen'),
        'type' => \Elementor\Controls_Manager::COLOR,
        'selectors' => [
          $selector . ':hover,' . $selector . ':focus' => 'color: {{VALUE}};',
        ],
        'condition' => [
          'style' => $condition
        ]
      ]
    );

    $init->add_control(
      str_replace(' ', '_', $label) . '_hover_bg_color',
      [
        'label' => __('Background Color', 'storzen'),
        'type' => \Elementor\Controls_Manager::COLOR,
        'selectors' => [
          $hover_bg_selector => 'background-color: {{VALUE}};',
        ],
        'condition' => [
          'style' => $condition
        ]
      ]
    );

    $init->add_control(
      str_replace(' ', '_', $label) . '_hover_border_color',
      [
        'label' => __('Border Color', 'storzen'),
        'type' => \Elementor\Controls_Manager::COLOR,
        'condition' => [
          'button_border_border!' => '',
        ],
        'selectors' => [
          $selector . ':hover,' . $selector . ':focus' => 'border-color: {{VALUE}};',
        ],
        'condition' => [
          'style' => $condition
        ]
      ]
    );

    $init->end_controls_tab();
    $init->end_controls_tabs();
  }
endif;

/**
 * Read a value from the Shop Details admin tab (Storzen: widgets → Shop Details).
 *
 * @param string $key     Field slug.
 * @param mixed  $default Default if missing.
 * @return mixed
 */
function storzen_get_shop_details_option($key, $default = null)
{
  $opt = get_option('pk_storzen_widgets_shop_details', array());
  if (! is_array($opt)) {
    return $default;
  }
  return isset($opt[$key]) ? $opt[$key] : $default;
}

/**
 * Allow inline SVG for Product Service Info (shop-details.html icons).
 *
 * @param string $html Raw SVG markup.
 * @return string
 */
function storzen_kses_svg($html)
{
  $allowed = array(
    'svg'  => array(
      'xmlns'       => true,
      'width'       => true,
      'height'      => true,
      'viewbox'     => true,
      'viewBox'     => true,
      'fill'        => true,
      'class'       => true,
      'aria-hidden' => true,
      'role'        => true,
    ),
    'path' => array(
      'd'    => true,
      'fill' => true,
    ),
  );
  return wp_kses($html, $allowed);
}

/**
 * Default inline SVGs from shop-details.html (cycles by item index).
 *
 * @return string[]
 */
function storzen_service_info_default_svgs()
{
  static $cache = null;
  if (null !== $cache) {
    return $cache;
  }
  $file = STORZEN_INC . '/shop-details-service-svgs.php';
  if (is_readable($file)) {
    $data = include $file;
    $cache = is_array($data) ? $data : array('', '', '');
  } else {
    $cache = array('', '', '');
  }
  return $cache;
}

/**
 * Register dedicated Product Tab Description meta box.
 */
function storzen_register_tab_description_meta_box()
{
  add_meta_box(
    'storzen_tab_description',
    esc_html__('Product Tab Description', 'storzen'),
    'storzen_render_tab_description_meta_box',
    'product',
    'normal',
    'default'
  );
}
add_action('add_meta_boxes', 'storzen_register_tab_description_meta_box');

/**
 * Render Product Tab Description meta box.
 *
 * @param \WP_Post $post Current post object.
 */
function storzen_render_tab_description_meta_box($post)
{
  wp_nonce_field('storzen_save_tab_description', 'storzen_tab_description_nonce');
  $value = get_post_meta($post->ID, '_storzen_tab_description', true);
  wp_editor(
    (string) $value,
    'storzen_tab_description_editor',
    array(
      'textarea_name' => 'storzen_tab_description',
      'textarea_rows' => 8,
      'media_buttons' => true,
    )
  );
  echo '<p class="description">' . esc_html__('This content is used only for the Product Tabs widget Description tab source: "Product tab description box".', 'storzen') . '</p>';
}

/**
 * Save Product Tab Description meta box.
 *
 * @param int $post_id Product post ID.
 */
function storzen_save_tab_description_meta_box($post_id)
{
  if (! isset($_POST['storzen_tab_description_nonce'])) {
    return;
  }
  if (! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['storzen_tab_description_nonce'])), 'storzen_save_tab_description')) {
    return;
  }
  if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
    return;
  }
  if (! current_user_can('edit_post', $post_id)) {
    return;
  }
  if (isset($_POST['storzen_tab_description'])) {
    $content = wp_kses_post(wp_unslash($_POST['storzen_tab_description']));
    update_post_meta($post_id, '_storzen_tab_description', $content);
  }
}
add_action('save_post_product', 'storzen_save_tab_description_meta_box');

if (file_exists(STORZEN_INC . '/product-details-storzen-markup.php')) {
  require_once STORZEN_INC . '/product-details-storzen-markup.php';
}

if (file_exists(STORZEN_INC . '/product-add-to-cart-storzen.php')) {
  require_once STORZEN_INC . '/product-add-to-cart-storzen.php';
}

if (file_exists(STORZEN_INC . '/shop-sidebar-helpers.php')) {
  require_once STORZEN_INC . '/shop-sidebar-helpers.php';
}




/**
 * Automatically add product to cart on visit
 */
if (!function_exists('storzen_auto_add_product_to_cart')) :
  function storzen_auto_add_product_to_cart()
  {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Public deep-link feature; reads a product title from the URL, performs no state change requiring a nonce.
    $auto_cart_status = isset($_GET['cart']) ? sanitize_text_field(wp_unslash($_GET['cart'])) : '';

    if (!is_admin() && !empty($auto_cart_status)) {
      $get_product = get_posts([
        'title'     => $auto_cart_status,
        'post_type' => 'product',
      ]);
      $product_id = $get_product[0]->ID;
      $found = false;
      //check if product already in cart
      if (sizeof(WC()->cart->get_cart()) > 0) {
        foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
          $_product = $values['data'];
          if ($_product->get_id() == $product_id)
            $found = true;
        }
        // if product not found, add it
        if (!$found)
          WC()->cart->add_to_cart($product_id);
      } else {
        // if no products in cart, add it
        WC()->cart->add_to_cart($product_id);
      }
    }
  }
  add_action('template_redirect', 'storzen_auto_add_product_to_cart');
endif;
