<?php

/**
 * The template for displaying product content within loops
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/content-product.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see     https://docs.woocommerce.com/document/template-structure/
 * @package WooCommerce\Templates
 * @version 3.6.0
 */

defined("ABSPATH") || exit();

global $product;

?>

<?php // Ensure visibility.

if (empty($product) || !$product->is_visible()) {
  return;
}
if ($product->is_type('simple')){
  $class = 'content-product-wrap product-card b2b-product-card simple';
} else {
  $class = 'content-product-wrap product-card b2b-product-card variable';
}
?>

<div <?php wc_product_class($class, $product); ?>>
    <?php woocommerce_template_loop_product_link_open(); ?>
    <div class="content-product-thumbnail">
        <?php woocommerce_template_loop_product_thumbnail(); ?>
    </div>
    <?php woocommerce_template_loop_product_link_close(); ?>
    <div class="content-product">
      <div class="info-wrp">
        <?php woocommerce_template_loop_product_link_open(); ?>
        <div class="content-product-title">
            <?php woocommerce_template_loop_product_title(); ?>
        </div>
        <div class="content-product-excerpt">
            <?php echo wp_trim_words( get_the_excerpt(), 10 ); ?>
        </div>
        <?php woocommerce_template_loop_product_link_close(); ?>

        <?php if ($product->is_type('simple')) : ?>
        <div class="content-product-sku">
            <?php echo esc_html($product->get_sku()); ?>
        </div>
        <?php ;else: ?>
        <div class="content-product-variations">
            <?php foreach ($product->get_available_variations() as $variation) : 
              $variation_id = $variation['variation_id'];
              $variation_stock = $variation['is_in_stock'];
              $variation_product_url = get_permalink($variation_id);
              // $variation_availability_html = $variation['availability_html'];
              $variation_attr = '';
              foreach($variation['attributes'] as $attribute){
                $variation_attr = $attribute;
              } 
              $class = '';
              if($variation_stock){
                $class = 'instock';
              } else {
                $class = 'outofstock';
              }
              ?>
              <a href="<?= $variation_product_url ?>" class="<?= $class ?>">
                <?= $variation_attr ?>
              </a>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
      </div>


        <div class="content-product-footer">
        <?php if ($product->is_type('variable')) : 
        woocommerce_template_loop_product_link_open(); ?>
        <div class="content-product-sku">
            <?php echo esc_html($product->get_sku()); ?>
        </div>
        <?php woocommerce_template_loop_product_link_close(); 
        endif; ?>
            <!-- quick-form -->
            <?php
            if ( $product->is_in_stock() && $product->is_type('simple') ) { ?>
          <div class="content-product-quick-form">
            <form class="quick-cart cart"
            action="<?php echo esc_url( apply_filters( 'woocommerce_add_to_cart_form_action', $product->get_permalink() ) ); ?>"
            method="post" enctype='multipart/form-data'>
            <div class="quantity-wrp">
              <p>
                <?= __("Počet kusov", 'inoby') ?>
              </p>
            <?php
                rc_quantity_input(
                  array(
                    'min_value'   => apply_filters( 'woocommerce_quantity_input_min', $product->get_min_purchase_quantity(), $product ),
                    'max_value'   => apply_filters( 'woocommerce_quantity_input_max', $product->get_max_purchase_quantity(), $product ),
                    'input_value' => isset( $_POST['quantity'] ) ? wc_stock_amount( wp_unslash( $_POST['quantity'] ) ) : $product->get_min_purchase_quantity(),
                    )
                  ); ?>
            </div>
                  <div class="add-to-cart-wrapper">
                    <div class="content-product-price">
                      <div class="normal-price-per-product">
                        <p>
                          <?= __('Maloobch. cena / ks:', 'inoby') ?>
                        </p>
                        <?php 
                          $regular_price = get_post_meta($product->get_id(), '_regular_price', true);

                          echo '<div class="price-range">' . wc_price($regular_price) . '</div>';
                        ?>
                      </div>
                      <span class="line"></span>
                      <div class="b2b-price-per-product">
                        <p>
                          <?= __('Veľkoobch. cena / ks:', 'inoby') ?>
                        </p>
                        <?php woocommerce_template_single_price(); ?>
                      </div>
                      <span class="line"></span>

                      <div class="normal-price">
                        <p>
                          <?= __('Maloobch. cena', 'inoby') ?>
                        </p>
                        <?php 
                          $regular_price = get_post_meta($product->get_id(), '_regular_price', true);

                          echo '<div class="price-range">' . wc_price($regular_price) . '</div>';
                          echo '<span class="screen-reader-text">' . $regular_price . '</span>';
                        ?>
                      </div>
                      <span class="line"></span>
                      <div class="b2b-price">
                        <p>
                          <?= __('Veľkoobch. cena', 'inoby') ?>
                        </p>
                        <?php woocommerce_template_single_price(); 
                        $discount_percentage = rwmb_meta('b2b-percentage', ["object_type" => "setting"], 'options');                        
                        if (empty($discount_percentage)) {
                              $discount_percentage = 20;
                          }
                          
                          $discount_multiplier = (100 - $discount_percentage) / 100;
                        if (!empty($regular_price)) {
                          $price = floatval($regular_price) * $discount_multiplier;
                          echo '<span class="screen-reader-text">' . $price . '</span>';
                        }
                        ?>
                      </div>
                    </div>
                <button type="submit" class="button add-to-cart-single-btn"><svg width="16" height="17" viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M3.3 2.5L3.75 3.25L3.9 3.45L4.15 4L7 8.95L14.85 6.8L14.4 8.45L6.25 10.65L6 10.25L5.5 9.35L2.45 4H1V2.5H3.3ZM8 13.5C8 14.6 7.1 15.5 6 15.5C4.9 15.5 4 14.6 4 13.5C4 12.45 4.85 11.55 5.9 11.5H6H12.5H12.6C13.65 11.55 14.5 12.45 14.5 13.5C14.5 14.6 13.6 15.5 12.5 15.5C11.4 15.5 10.5 14.6 10.5 13.5C10.5 13.35 10.5 13.15 10.55 13H7.9C8 13.15 8 13.35 8 13.5ZM12.5 13C12.2 13 12 13.2 12 13.5C12 13.8 12.2 14 12.5 14C12.8 14 13 13.8 13 13.5C13 13.2 12.8 13 12.5 13ZM6 13C5.7 13 5.5 13.2 5.5 13.5C5.5 13.8 5.7 14 6 14C6.3 14 6.5 13.8 6.5 13.5C6.5 13.2 6.3 13 6 13ZM14.65 4.5H15.5L14.45 8.45L12.8 8.9L13.6 6H4.65L4.05 4.5H14.65Z" fill="#00A448"/></svg><?= __('Vložiť do košíka', 'inoby') ?></button>

                <input type="hidden" name="rc-add-to-cart" value="<?= $product->get_id(); ?>">
                <input type="hidden" name="open_minicart" value="1">
                  </div>
            </form>

          </div>
          <?php 
            }
          else{
            ?>
            <div class="add-to-cart-wrapper">
              <div class="content-product-price">
                <div class="normal-price">
                  <p>
                    <?= __('Maloobch. cena od / ks:', 'inoby') ?>
                  </p>
                  <?php 
                  
                    $regular_prices = [];
                    foreach ($product->get_available_variations() as $variation) {
                      $regular_price = get_post_meta($variation['variation_id'], '_regular_price', true);

                      if (!empty($regular_price)) {
                        $regular_prices[] = floatval($regular_price);
                      }
                    }

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

                    echo '<div class="price-range">' . wc_price($min_price) . '</div>';
                  
                  ?>
                </div>
                <span class="line"></span>
                <div class="b2b-price">
                  <p>
                    <?= __('Veľkoobch. cena od / ks:', 'inoby') ?>
                  </p>
                  <?php woocommerce_template_single_price(); ?>
                </div>
              </div>
              <div class="content-product-button">
                <a href="#0" class="link"><?= __('Zobraziť varianty','rootscope') ?><svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M7.5 10.45L12.95 5L14 6.05L7.5 12.6L1 6.1L2.05 5.05L7.5 10.45Z" fill="#0029FF"/></svg></a>
              </div>
            </div>
          <?php
          } 
          ?>
          <!-- quick-form -->

        </div>
    </div>
    <?php if($product->is_type('variable')) { ?>
      <?php 
                  $attributes = [];
                  $parsedVariations = [];
                  foreach ($product->get_available_variations() as $variation) {
                    $product = wc_get_product($variation['variation_id']);
                      $variation_id = $variation['variation_id'];
                      $variation_stock = $variation['is_in_stock'];
                      $sku = $variation['sku'];
                      $variation_product_url = get_permalink($variation_id);
                      $variation_availability_html = $variation['availability_html'];
                      $normalPrice = number_format(get_post_meta($variation_id, '_regular_price', true), 2) . get_woocommerce_currency_symbol();
                      $b2bPrice = $product->get_price_html();
                      if(strpos($variation_availability_html, 'outofstock') !== false){
                        $max_stock = 0;
                      } else {
                        $max_stock = $product->get_max_purchase_quantity();
                      }
                      $variation_attr = '';
                      foreach($variation['attributes'] as $attribute){
                        $variation_attr = $attribute;
                      } 

                      $parsedVariations[] = [
                        'id'  => $variation_id,
                        'attribute'   => $variation_attr,
                        'sku'         => $sku,
                        'max_stock'   => $max_stock,
                        'availability_html'     => $variation_availability_html,
                        'stock'     => $variation_stock,
                        'normalPrice' => $normalPrice,
                        'b2bPrice'    => $b2bPrice,
                      ];
                      $attributes  = array_keys( $variation['attributes'] );
                  }
      ?>

      <div class="variable-details">
        <form class="quick-cart cart-variations"
            action="<?php echo esc_url( apply_filters( 'woocommerce_add_to_cart_form_action', $product->get_permalink() ) ); ?>"
            method="post" enctype='multipart/form-data'>
            <table>
              <tr class="label-row">
                <td class="label">
                <?php foreach ( $attributes as $attribute_name ) : 
                    $taxonomy = str_replace( 'attribute_', '', $attribute_name );
                    echo wc_attribute_label( $taxonomy );
                endforeach; ?>
                </td>
                <td class="label">
                  <?= __("Kód variantu", 'inoby') ?>
                </td>
                <td class="label">
                  <?= __("Počet kusov", 'inoby') ?>
                </td>
                <td class="label">
                  <?= __("Na sklade", 'inoby') ?>
                </td>
                <td class="label">
                  <?= __("Maloobch. cena / ks", 'inoby') ?>
                </td>
                <td class="label">
                  <?= __("Veľkoobch. cena / ks", 'inoby') ?>
                </td>
              </tr>

              <?php foreach($parsedVariations as $var) { ?>
                <tr class="variation">
                  <?php if(isset($var['attribute'])){ ?>
                    <td class="attribute">
                      <?= $var['attribute'] ?>
                    </td>
                  <?php } ?>

                  <?php if(isset($var['sku'])){ ?>
                    <td class="sku">
                      <?= $var['sku'] ?>
                    </td>
                  <?php } ?>

                  <?php if(isset($var['stock']) && $var['stock']){ ?>
                    <td class="quantity-col">
                  <?php
                  rc_quantity_input(
                    array(
                      'min_value'   => 0,
                      'max_value'   => $var['max_stock'] ?? 0,
                      'input_value' => isset( $_POST['quantity'] ) ? wc_stock_amount( wp_unslash( $_POST['quantity'] ) ) : 1,
                      'input_name'  => 'quantity-'.$var['id'],
                    ),
                    wc_get_product($var['id']) ?? null
                    ); ?>
                    </td>
                  <?php } else { ?>
                    <td class="quantity-col">
                      <?php
                    rc_quantity_input(
                      array(
                        'min_value'   => 0,
                        'max_value'   => 0,
                        'input_value' => 0,
                      'input_name'  => 'quantity-'.$var['id'],
                      ),
                      wc_get_product($var['id']) ?? null
                      ); ?>
                    </td>
                    <?php } ?>

                    <?php if(isset($var['id'])){ ?>
                    <td class="availability_html">
                        <?php
                        $product = wc_get_product($var['id']);
                        
                        // Check the actual stock status using WooCommerce's built-in method
                        $stock_status = $product->get_stock_status();
                        
                        if ($product->get_stock_quantity() > 0) {

                            if($product->get_stock_quantity() === 1){
                              echo '<span class="stock instock">';
                              echo sprintf(__('%s kus skladom', 'rootscope'), $product->get_stock_quantity());
                              echo '</span>';
                            } elseif($product->get_stock_quantity() > 1 && $product->get_stock_quantity() < 5){
                              echo '<span class="stock instock">';
                              echo sprintf(__('%s kusy skladom', 'rootscope'), $product->get_stock_quantity());
                              echo '</span>';
                            } else {
                              echo '<span class="stock instock">';
                              echo sprintf(__('%s kusov skladom', 'rootscope'), $product->get_stock_quantity());
                              echo '</span>';
                            }
                        } else {
                            // When stock quantity is 0, check the actual stock status
                            if ($stock_status === 'onbackorder') {
                                echo '<span class="stock onbackorder">';
                                esc_attr_e('Na objednávku', 'rootscope');
                                echo '</span>';
                            } else {
                                echo '<span class="stock outofstock">';
                                esc_attr_e('Nie je skladom', 'rootscope');
                                echo '</span>';
                            }
                        }
                      ?>
                    </td>
                    <?php } ?>

                  <?php if(isset($var['normalPrice'])){ ?>
                    <td class="normalPrice">
                      <?= $var['normalPrice'] ?>
                    </td>
                  <?php } ?>

                  <?php if(isset($var['b2bPrice'])){ ?>
                    <td class="b2bPrice">
                      <?= $var['b2bPrice'] ?>
                    </td>
                  <?php } ?>
                </tr>
              <?php } ?>
            </table>

              <table class="summary">
                <tr>
                  <td class="summary-label">
                    <?= __("Spolu: ", 'inoby') ?>
                  </td>
                  <td class="summary-quantity">
                    <span class="quantity-text">

                    </span>
                    <span class="value">
                      <?= __("KS", 'inoby') ?>
                    </span>
                  </td>
                  <td class="summary-normalPrice">
                    <span class="normalPrice-value">

                    </span>
                    <span class="normalPrice-currency-symbol">
                      <?= get_woocommerce_currency_symbol() ?>
                    </span>
                  </td>
                  <td class="summary-b2bPrice">
                    <span class="b2bPrice-value">

                    </span>
                    <span class="b2bPrice-currency-symbol">
                      <?= get_woocommerce_currency_symbol() ?>
                    </span>
                  </td>
                </tr>
              </table>            

            <div class="items-end">
                
                <button type="submit" class="button add-to-cart-variations-button"><svg width="16" height="17" viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M3.3 2.5L3.75 3.25L3.9 3.45L4.15 4L7 8.95L14.85 6.8L14.4 8.45L6.25 10.65L6 10.25L5.5 9.35L2.45 4H1V2.5H3.3ZM8 13.5C8 14.6 7.1 15.5 6 15.5C4.9 15.5 4 14.6 4 13.5C4 12.45 4.85 11.55 5.9 11.5H6H12.5H12.6C13.65 11.55 14.5 12.45 14.5 13.5C14.5 14.6 13.6 15.5 12.5 15.5C11.4 15.5 10.5 14.6 10.5 13.5C10.5 13.35 10.5 13.15 10.55 13H7.9C8 13.15 8 13.35 8 13.5ZM12.5 13C12.2 13 12 13.2 12 13.5C12 13.8 12.2 14 12.5 14C12.8 14 13 13.8 13 13.5C13 13.2 12.8 13 12.5 13ZM6 13C5.7 13 5.5 13.2 5.5 13.5C5.5 13.8 5.7 14 6 14C6.3 14 6.5 13.8 6.5 13.5C6.5 13.2 6.3 13 6 13ZM14.65 4.5H15.5L14.45 8.45L12.8 8.9L13.6 6H4.65L4.05 4.5H14.65Z" fill="#00A448"/></svg><?= __('Vložiť do košíka', 'inoby') ?></button>
                
                <input type="hidden" name="open_minicart" value="1"> <!-- Add this line -->
                <input type="hidden" name="rc-add-to-cart" value="<?php echo absint( $product->get_id() ); ?>"> <!-- Add this line -->
                <input type="hidden" name="product_id" value="<?php echo absint( $product->get_id() ); ?>" />
                <?php foreach($parsedVariations as $var){ ?>
                  <input type="hidden" name="variation_id-<?= $var['id'] ?>" value="<?= $var['id'] ?>">
                <?php } ?>
            </div>
          </form>
      </div>
      <?php } ?>
</div>