<?php
$b2b_as_global_sale = rwmb_meta_before_init_theme_setting("b2b-global-sale");
$b2b_use_tax = rwmb_meta_before_init_theme_setting("b2b-use-tax");

// add user role for b2b
function create_b2b_customer_role()
{
  add_role(
    'b2b',
    'B2B',
    [
      'read' => true,
      'edit_posts' => false,
      'upload_files' => false,
    ]
  );
}
add_action('init', 'create_b2b_customer_role');


/**
   * 
   * Support for new B2B
   * 
   */
if(!empty($b2b_as_global_sale) && $b2b_as_global_sale){

/**
 * AJAX handler for adding variables to cart
 */
function add_to_cart_variables_ajax_handler() {
    // Check if this is an rc-ajax request
    if (!isset($_GET['rc-ajax']) || $_GET['rc-ajax'] !== 'add_to_cart_variables') {
        return;
    }

    // Verify nonce for security
    if (!wp_verify_nonce($_POST['_wpnonce'] ?? '')) {
        wp_die('Security check failed');
    }

    $response = array(
        'success' => false,
        'message' => '',
        'data' => array()
    );

    try {
        // Get the product ID
        $product_id = intval($_POST['product_id'] ?? 0);
        $open_minicart = $_POST['open_minicart'] ?? '0';

        // Get all variation IDs from the form data
        $variation_ids = array();
        foreach ($_POST as $key => $value) {
            if (strpos($key, 'variation_id-') === 0) {
                $variation_id = intval($value);
                if ($variation_id > 0) {
                    $variation_ids[] = $variation_id;
                }
            }
        }

        // Add each variation to cart
        $added_count = 0;
        foreach ($variation_ids as $variation_id) {
            $variation = wc_get_product($variation_id);
            if ($variation && $variation->is_type('variation')) {
              $variationQuantity = intval($_POST["quantity-{$variation_id}"] ?? 0);
                $cart_item_key = WC()->cart->add_to_cart($variation_id, $variationQuantity);
                if ($cart_item_key) {
                    $added_count++;
                }
            }
        }

        // Update cart fragments
        WC()->cart->calculate_totals();

        $response['success'] = true;
        $response['message'] = sprintf('%d variation(s) added to cart', $added_count);
        $response['data'] = array(
            'added_count' => $added_count,
            'cart_count' => WC()->cart->get_cart_contents_count(),
            'cart_total' => WC()->cart->get_cart_total(),
            'open_minicart' => $open_minicart === '1'
        );

    } catch (Exception $e) {
        $response['message'] = $e->getMessage();
    }

    // Send JSON response
    wp_send_json($response);
}

// Hook the AJAX handler to WordPress
add_action('wp_loaded', 'add_to_cart_variables_ajax_handler');
}

if($b2b_as_global_sale && !$b2b_use_tax){
  function custom_b2b_price($price, $product)
    {
      if (is_user_logged_in()) {
            $user = wp_get_current_user();
            if (in_array('b2b', (array) $user->roles)) {
                  $discount_percentage = rwmb_meta('b2b-percentage', ["object_type" => "setting"], 'options');
                  
                  if (empty($discount_percentage)) {
                      $discount_percentage = 20;
                  }
                  
                  $discount_multiplier = (100 - $discount_percentage) / 100;
  
                  $regular_price = get_post_meta( $product->get_id(), '_regular_price', true);
                  if (!empty($regular_price)) {
                    $price = floatval($regular_price) * $discount_multiplier;
                  } 

            }
        }
        return $price;
    }
    // Apply the B2B price to all relevant price filters
    add_filter('woocommerce_product_get_price', 'custom_b2b_price', 90, 2);
    add_filter('woocommerce_product_variation_get_price', 'custom_b2b_price', 90, 2);
    add_filter('woocommerce_product_get_regular_price', 'custom_b2b_price', 90, 2);
    add_filter('woocommerce_product_variation_get_regular_price', 'custom_b2b_price', 90, 2);
    add_filter('woocommerce_product_get_sale_price', 'custom_b2b_price', 90, 2);
    add_filter('woocommerce_product_variation_get_sale_price', 'custom_b2b_price', 90, 2);

    // Add support for variation prices (for all variation price-related hooks)
    add_filter('woocommerce_variation_prices_price', 'custom_b2b_price', 90, 2);
    add_filter('woocommerce_variation_prices_sale_price', 'custom_b2b_price', 90, 2);
    add_filter('woocommerce_variation_prices_regular_price', 'custom_b2b_price', 90, 2);
    add_filter('woocommerce_variation_prices_discounted_price', 'custom_b2b_price', 90, 2);
} else {
  /**
   * 
   * Support for old B2B
   * 
   */

  // add B2B field to WooCommerce Product Data > General tab
  function add_b2b_price_field_to_general_tab()
  {
    global $post;

    $b2b_price = get_post_meta($post->ID, '_b2b_price', true);
  ?>
    <div class="options_group">
      <p class="form-field">
        <label for="b2b_price_field"><?php _e('B2B Cena', 'inoby'); ?></label>
        <input type="number" step="0.01" min="0" id="b2b_price_field" name="b2b_price_field"
          value="<?php echo esc_attr($b2b_price); ?>" placeholder="<?php _e('Zadajte B2B cenu', 'inoby'); ?>" />
      </p>
    </div>
  <?php
  }
  add_action('woocommerce_product_options_pricing', 'add_b2b_price_field_to_general_tab');

  // save B2B price
  function save_b2b_price_in_general_tab($product)
  {
    if (isset($_POST['b2b_price_field'])) {
      $b2b_price = sanitize_text_field($_POST['b2b_price_field']);
      $product->update_meta_data('_b2b_price', $b2b_price);
    }
  }
  add_action('woocommerce_admin_process_product_object', 'save_b2b_price_in_general_tab');

  // add B2B field to variants
  function add_b2b_price_to_variations($loop, $variation_data, $variation)
  {
    $b2b_price = get_post_meta($variation->ID, '_b2b_price', true);
  ?>
    <p class="form-row form-row-first">
      <label for="b2b_price_<?php echo $variation->ID; ?>">
        <?php _e('B2B Cena', 'inoby'); ?>
      </label>
      <input type="number" step="0.01" min="0" name="b2b_price[<?php echo $variation->ID; ?>]"
        value="<?php echo esc_attr($b2b_price); ?>" />
    </p>
  <?php
  }
  add_action('woocommerce_variation_options_pricing', 'add_b2b_price_to_variations', 10, 3);

  // save B2B prices to variants
  function save_b2b_price_for_variations($variation_id, $i)
  {
    if (isset($_POST['b2b_price'][$variation_id])) {
      $b2b_price = sanitize_text_field($_POST['b2b_price'][$variation_id]);
      update_post_meta($variation_id, '_b2b_price', $b2b_price);
    }
  }
  add_action('woocommerce_save_product_variation', 'save_b2b_price_for_variations', 10, 2);


  // Extend woocommerce_format_price_range function to display price range for B2B users
  add_filter('woocommerce_format_price_range', 'custom_b2b_variation_price_range', 9999, 3);
  function custom_b2b_variation_price_range($price, $from, $to)
  {
    global $product;

    if(!$product){
      return;
    }

    // If user is 'b2b'
    if (is_user_logged_in() && wc_current_user_has_role('b2b')) {
      // If the product is variable
      if ($product->is_type('variable')) {
        $variations = $product->get_available_variations();
        $b2b_prices = [];

        // Loop through variations to gather B2B prices
        foreach ($variations as $variation) {
          $variation_id = $variation['variation_id'];
          // $b2b_price = get_post_meta($variation_id, '_b2b_price', true);
          //without tax
          $b2b_price = wc_get_price_excluding_tax(wc_get_product($variation_id), array('price' => get_post_meta($variation_id, '_b2b_price', true)));

          // Collect B2B prices
          if (!empty($b2b_price)) {
            $b2b_prices[] = floatval($b2b_price);
          }
        }

        // If there are B2B prices, return the B2B price range
        if (!empty($b2b_prices)) {
          $min_b2b_price = min($b2b_prices);
          $max_b2b_price = max($b2b_prices);

          return '<div class="price-range">' . __('Od ', 'inoby') . wc_price($min_b2b_price) . '</div>';
        }
      }
    }

    // If user is not 'b2b', return the default price range
    if ($product->is_type('variable')) {
      // For variable products, use the sale price range if available
      $sale_prices = [];
      $regular_prices = [];
      foreach ($product->get_available_variations() as $variation) {
        $sale_price = get_post_meta($variation['variation_id'], '_sale_price', true);
        $regular_price = get_post_meta($variation['variation_id'], '_regular_price', true);

        // Collect sale and regular prices
        if (!empty($sale_price)) {
          $sale_prices[] = floatval($sale_price);
        }
        if (!empty($regular_price)) {
          $regular_prices[] = floatval($regular_price);
        }
      }

      // Get the min and max prices from sale and regular prices
      $min_price = min(array_merge($sale_prices, $regular_prices));
      $max_price = max(array_merge($sale_prices, $regular_prices));

      return '<div class="price-range">' . __('Od ', 'inoby') . wc_price($min_price) . '</div>';
    }

    // Return default price for simple products
    return $price;
  }

  // B2B custom prices for products and variations, with support for sale prices
  function custom_b2b_price($price, $product)
  {
    $b2b_price = $product->get_meta('_b2b_price');
    if (is_user_logged_in() && wc_current_user_has_role('b2b')) {
      if (!empty($b2b_price)) {
        return floatval($b2b_price);
      }
    }
    return $price;
  }
  // Apply the B2B price to all relevant price filters
  add_filter('woocommerce_product_get_price', 'custom_b2b_price', 90, 2);
  add_filter('woocommerce_product_variation_get_price', 'custom_b2b_price', 90, 2);
  add_filter('woocommerce_product_get_regular_price', 'custom_b2b_price', 90, 2);
  add_filter('woocommerce_product_variation_get_regular_price', 'custom_b2b_price', 90, 2);
  add_filter('woocommerce_product_get_sale_price', 'custom_b2b_price', 90, 2);
  add_filter('woocommerce_product_variation_get_sale_price', 'custom_b2b_price', 90, 2);

  // Add support for variation prices (for all variation price-related hooks)
  // add_filter('woocommerce_variation_prices_price', 'custom_b2b_price', 90, 2);
  add_filter('woocommerce_variation_prices_sale_price', 'custom_b2b_price', 90, 2);
  add_filter('woocommerce_variation_prices_regular_price', 'custom_b2b_price', 90, 2);
  add_filter('woocommerce_variation_prices_discounted_price', 'custom_b2b_price', 90, 2);

  function custom_b2b_price_without_tax($price, $product)
  {
    $b2b_price = $product->get_meta('_b2b_price');
    if (is_user_logged_in() && wc_current_user_has_role('b2b')) {
      if (!empty($b2b_price)) {
        return wc_get_price_excluding_tax($product, array('price' => floatval($b2b_price)));
      }
    }
    return $price;
  }
  add_filter('woocommerce_variation_prices_price', 'custom_b2b_price_without_tax', 90, 2);


  // Change price suffix for B2B users
  add_filter('woocommerce_get_price_suffix', 'custom_price_display_suffix', 1, 2);
  function custom_price_display_suffix($suffix, $product)
  {
    if (is_user_logged_in() && wc_current_user_has_role('b2b')) {
      return '<span class="vat-text">' . __('bez DPH', 'inoby') . '</span>';
    }
    return $suffix;
  }

  function calculate_b2b_price_without_tax($price, $product_id)
  {
    $tax_rates = WC_Tax::get_rates('');
    $tax_rate = !empty($tax_rates) ? reset($tax_rates)['rate'] : 0; // Použijeme prvú dostupnú sadzbu DPH
    $price_without_tax = $price / (1 + ($tax_rate / 100)); // Odpočítanie DPH
    return $price_without_tax;
  }

  function display_b2b_price_without_tax($price, $product)
  {
    if (is_user_logged_in() && wc_current_user_has_role('b2b')) {
      $b2b_price = $product->get_meta('_b2b_price');

      if (!empty($b2b_price)) {
        // Vypočítať cenu bez DPH
        $price_without_tax = calculate_b2b_price_without_tax(floatval($b2b_price), $product->get_id());

        // Formátovanie ceny
        return wc_price($price_without_tax) . ' <span class="vat-text">' . __('bez DPH', 'inoby') . '</span>';
      }
    }
    return $price; // Vrátiť štandardnú cenu pre ostatných používateľov
  }
  add_filter('woocommerce_get_price_html', 'display_b2b_price_without_tax', 20, 2);
}



    function disable_woocommerce_price_transients($prices_array, $product, $for_display)
    {
      if (is_user_logged_in() && wc_current_user_has_role('b2b')) {
        // Vynútia sa dynamické ceny, transienty sa nepoužijú
        $prices_array[] = microtime();
      }
      return $prices_array;
    }
    add_filter('woocommerce_get_variation_prices_hash', 'disable_woocommerce_price_transients', 10, 3);