<?php
//========================== Shortcode For Best Tools Section Of Home Page Start ========================

// Shortcode function to display parent category name and list its child categories
function parent_child_categories_shortcode($atts) {
    $get_all_child_array = array();

    // Shortcode attributes (if any)
    $atts = shortcode_atts(
        array(
            'parent_slug' => '', // Default parent category slug
            'show_products' => 8,
        ),
        $atts,
        'parent_child_categories'
    );

    // Get parent category ID from slug
    $parent_category = get_term_by('slug', $atts['parent_slug'], 'product_cat');

    // Check if parent category exists
    if (!$parent_category || is_wp_error($parent_category)) {
        return 'Parent category not found.';
    }

    // Get all child categories of the parent category
    $child_args = array(
        'taxonomy'   => 'product_cat',
        'hide_empty' => false, // Set to true if you want to hide empty categories
        'parent'     => $parent_category->term_id,
    );

    $child_categories = get_terms($child_args);

    foreach ($child_categories as $child_category) {
        $get_all_child_array[] = $child_category->slug; // Changed to slug for consistency
    }

    ob_start();
    $all_products_tabs  = $get_all_child_array;
    ?>
    <div class="home-product-tab-sec">
        <div class="home-product-tab-container">
            <div class="home-product-tab-wrapper">
                <div class="product-cat">
                    <ul class="nav flex-column product-top-nav nav-pills" id="v-pills-tab" role="tablist" aria-orientation="vertical">
                        <?php foreach ($all_products_tabs as $all_products_tabs_cat_key => $all_products_tabs_cat_value): ?>
                            <li class="nav-item" role="presentation">
                                <a class="nav-link <?php if($all_products_tabs_cat_key==0){ echo 'active'; } ?>" id="v-pills1-<?php echo esc_attr($all_products_tabs_cat_key);?>-tab" data-bs-toggle="pill" href="#v-pills1-<?php echo esc_attr($all_products_tabs_cat_key);?>" role="tab" aria-controls="v-pills1-<?php echo esc_attr($all_products_tabs_cat_key);?>" aria-selected="<?php if($all_products_tabs_cat_key==0){ echo 'true'; } else { echo 'false'; } ?>">
                                    <i class="fa-solid fa-screwdriver-wrench"></i>
                                    <?php
                                        $term = get_term_by('slug', $all_products_tabs_cat_value, 'product_cat' );
                                        if ($term) {
                                            $name = $term->name;
                                            echo esc_html($name);
                                        }
                                    ?>
                                </a>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                    <div class="best-handyman-wrapper">
                        <div class="sm-image-box-wrapper">
                            <div class="tab_chota_banner_wrap_content">
                                <h3><?php echo esc_html(get_theme_mod('cln_elemento_pro_slider_small_heading')); ?></h3>
                                <div class="primary-btn-icon">
                                    <a href="<?php echo esc_html(get_theme_mod('cln_elemento_pro_button_link')); ?>">
                                        <span class="elementor-button-content-wrapper">
                                            <span class="elementor-button-icon"><i class="fa-solid fa-user"></i></span>
                                            <span class="elementor-button-text"><?php echo esc_html(get_theme_mod('cln_elemento_pro_button_text')); ?></span>
                                        </span>
                                    </a>
                                </div>
                            </div>
                            <div class="tab_chota_banner_img">
                                <?php $best_handyman = get_theme_mod('cln_elemento_pro_image'); ?>
                                <img src="<?php echo esc_attr($best_handyman); ?>">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="all-product">
                    <div class="tab-content" id="v-pills-tabContent">
                        <?php foreach ($all_products_tabs as $all_products_tabs_cat_key => $all_products_tabs_cat_value): ?>
                            <?php
                                $args = array(
                                    'posts_per_page' => $atts['show_products'],  // Number of products to display
                                    'tax_query' => array(
                                        array(
                                            'taxonomy' => 'product_cat',
                                            'field'    => 'slug',
                                            'terms'    => $all_products_tabs_cat_value,
                                        ),
                                    ),
                                    'post_type' => 'product',
                                );
                                $loop = new WP_Query($args);
                            ?>
                            <div class="tab-pane fade <?php if($all_products_tabs_cat_key==0){ echo 'active show'; } ?>" id="v-pills1-<?php echo esc_attr($all_products_tabs_cat_key); ?>" role="tabpanel" aria-labelledby="v-pills1-<?php echo esc_attr($all_products_tabs_cat_key); ?>-tab">
                                <div class="product-items-wrapper">
                                    <?php while ($loop->have_posts()): $loop->the_post(); ?>
                                        <div class="product-item-box">
                                            <div class="pro-img">
                                                <a href="<?php the_permalink(); ?>">
                                                    <?php the_post_thumbnail();?>
                                                </a>
                                            </div>
                                            <div class="product-content">
                                                <div class="product-content-info">
                                                    <div class="">
                                                        <div>
                                                            <h5 class="product-brand">
                                                                <?php
                                                                    $product_brand = wp_get_post_terms(get_the_ID(), 'brand');
                                                                    if ($product_brand && count($product_brand) && isset($product_brand[0])) {
                                                                        echo esc_html($product_brand[0]->name);
                                                                    }
                                                                ?>
                                                            </h5>
                                                        </div>
                                                    </div>
                                                    <div class="pro-content">
                                                        <div class="home-product-title">
                                                            <h4 class="product-title">
                                                                <a href="<?php the_permalink(); ?>">
                                                                    <?php echo get_the_title(); ?>
                                                                </a>
                                                            </h4>
                                                        </div>
                                                        <div class="product-price">
                                                            <div class="product-price-rate">
                                                                <?php
                                                                    $product = wc_get_product(get_the_ID());
                                                                    echo $product->get_price_html();
                                                                ?>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="product-content-btns">
                                                    <div class="wishlist-quick-view">
                                                        <?php echo do_shortcode('[yith_wcwl_add_to_wishlist]'); ?>
                                                        <div class="quick_view"><?php echo do_shortcode('[yith_quick_view]'); ?></div>
                                                    </div>
                                                    <div class="add-to-cart">
                                                        <span class="cart-btn my-2">
                                                            <?php if($product->is_type('variable')) { woocommerce_template_loop_add_to_cart($loop->post, $product); } ?>
                                                        </span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endwhile; wp_reset_query(); ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php
    return ob_get_clean();
}

// Register shortcode
add_shortcode('parent_child_categories', 'parent_child_categories_shortcode');

//=========================== Shortcode For Best Tools Section Of Home Page End  =========================
//========================== Shortcode For Best Best Supplies Section Of Home Page Start  =======================

function get_products_by_categories($atts) {
  static $instance = 0;
  $instance++;

  // Extract shortcode attributes
  $atts = shortcode_atts(
      array(
          'categories' => '',
          'show_products' => 8, 
      ), $atts, 'products_by_categories'
  );
  
  // Split categories by comma
  $categories = explode(',', $atts['categories']);
  
  // Remove whitespace and ensure categories are trimmed
  $categories = array_map('trim', $categories);
  
  // Start output buffering
  ob_start();
  
  $all_products_tabs  = $categories;
  ?>
<div class="home-product-tab-sec">
      <div class="home-product-tab-container">
          <div class="home-product-tab-wrapper">
              <div class="product-cat">
                  <div class="best-supplies-heading-section"></div>
                  <ul class="nav nav-pills product-top-nav" id="pills-tab-<?php echo esc_attr($instance); ?>" role="tablist">
                      <?php foreach ( $all_products_tabs as $all_products_tabs_cat_key => $all_products_tabs_cat_value ): ?>
                          <li class="nav-item" role="presentation">
                              <a
                                  class="nav-link <?php if($all_products_tabs_cat_key==0){ echo 'active'; } ?> "
                                  id="pills-<?php echo esc_attr($instance); ?>-<?php echo esc_attr($all_products_tabs_cat_key);?>-tab"
                                  data-bs-toggle="pill" href="#pills-<?php echo esc_attr($instance); ?>-<?php echo esc_attr($all_products_tabs_cat_key);?>"
                                  role="tab"
                                  aria-controls="pills-<?php echo esc_attr($instance); ?>-<?php echo esc_attr($all_products_tabs_cat_key);?>"
                                  aria-selected="<?php if($all_products_tabs_cat_key==0){ echo 'true'; } else { echo 'false'; } ?>"
                              >
                              <i class="fa-solid fa-screwdriver-wrench"></i>
                                  <?php
                                      $term = get_term_by('slug', $all_products_tabs_cat_value, 'product_cat' );
                                      if ($term) {
                                          $name = $term->name;
                                          echo esc_html( $name );
                                      }
                                  ?>
                              </a>
                          </li>
                      <?php endforeach; ?>
                  </ul>
              </div>
              <div class="all-product">
                  <div class="tab-content" id="pills-tabContent-<?php echo esc_attr($instance); ?>">
                      <?php foreach ($all_products_tabs as $all_products_tabs_cat_key => $all_products_tabs_cat_value ): ?>
                          <?php
                              $args = array(
                                  'posts_per_page' => $atts['show_products'],  // Number of products to display
                                  'tax_query' => array(
                                      array(
                                          'taxonomy' => 'product_cat',
                                          'field'    => 'slug',
                                          'terms'    => $all_products_tabs_cat_value,
                                      ),
                                  ),
                                  'post_type' => 'product',
                                  'meta_key' => 'total_sales', // Specify the custom field
                                  'orderby' => 'meta_value_num', // Order by numeric value of the custom field
                                  'order' => 'DESC', // Descending order
                              );
                              $loop = new WP_Query($args);
                          ?>
                          <div class="tab-pane fade <?php if($all_products_tabs_cat_key==0){ echo 'active show'; } ?>" id="pills-<?php echo esc_attr($instance); ?>-<?php echo esc_attr($all_products_tabs_cat_key); ?>" role="tabpanel" aria-labelledby="pills-<?php echo esc_attr($instance); ?>-<?php echo esc_attr($all_products_tabs_cat_key); ?>-tab">
                              <div class="product-items-wrapper">
                                  <?php while ( $loop->have_posts() ) : $loop->the_post();
                                      $product = wc_get_product( get_the_ID() );
                                      $product_categories = wc_get_product_category_list( get_the_ID());
                                      $product_brand = wp_get_post_terms(get_the_ID(), "brand");
                                  ?>
                                      <div class="product-item-box">
                                          <div class="pro-img">
                                              <a href="<?php the_permalink(); ?>">
                                                  <?php the_post_thumbnail();?>
                                              </a>
                                          </div>
                                          <div class="product-content">
                                              <div class="product-content-info">
                                                  <div class="">
                                                      <div>
                                                          <h5 class="product-brand">
                                                              <?php
                                                                  if ($product_brand && count($product_brand) && isset($product_brand[0])) {
                                                                      echo  esc_html($product_brand[0]->name);
                                                                  }
                                                              ?>
                                                          </h5>
                                                      </div>
                                                  </div>
                                                  <div class="pro-content">
                                                      <div class="home-product-title "> 
                                                          <h4 class="product-title ">
                                                              <a href="<?php the_permalink(); ?>">
                                                                  <?php echo get_the_title(); ?>
                                                              </a>
                                                          </h4>
                                                      </div>
                                                      <div class="product-price ">
                                                          <div class="product-price-rate">
                                                              <?php echo $product->get_price_html(); ?>
                                                          </div>
                                                      </div>
                                                  </div>
                                              </div>
                                              <div class="product-content-btns">
                                                  <div class="wishlist-quick-view">
                                                      <?php echo do_shortcode('[yith_wcwl_add_to_wishlist]'); ?>
                                                      <div class="quick_view"><?php echo do_shortcode('[yith_quick_view]'); ?> </div>
                                                  </div>
                                                  <div class="add-to-cart">
                                                      <span class="cart-btn my-2">
                                                          <?php if( $product->is_type( 'variable' ) ){ woocommerce_template_loop_add_to_cart( $loop->post, $product ); } ?>
                                                      </span>
                                                  </div>
                                              </div>
                                          </div>
                                      </div>
                                  <?php endwhile; wp_reset_query(); ?>
                              </div>
                          </div>
                      <?php endforeach; ?>
                  </div>
              </div>
          </div>
      </div>
  </div>
  <?php
  
  // Return the buffered content
  return ob_get_clean();
}

// Register the shortcode
add_shortcode('products_by_categories', 'get_products_by_categories');

//======================= Shortcode For Best Supplies Section Of Home Page End ====================
//======================= Shortcode For Best Handyman Section Start ====================

function handyman_shortcode($atts) {
    $atts = shortcode_atts(
        array(
            'posts_per_page' => 5,
            'paged' => 1,
        ),
        $atts,
        'handyman'
    );

    $paged = get_query_var('paged') ? get_query_var('paged') : 1;

    $args = array(
        'post_type' => 'handyman',
        'posts_per_page' => $atts['posts_per_page'],
        'paged' => $paged,
    );

    $handyman_query = new WP_Query($args);

    ob_start();

    if ($handyman_query->have_posts()) {
        echo '<div class="handyman-list">';
        while ($handyman_query->have_posts()) {
            $handyman_query->the_post();
           $handyman_contact = esc_html(get_post_meta(get_the_ID(),'handyman_phone',true));
           $handyman_designation = esc_html(get_post_meta(get_the_ID(),'handyman_designation',true));
            ?>
            <div class="handyman-item">
                <div class="handyman-img">
                    <?php the_post_thumbnail() ?>
                </div>
                <div class="handyman-content">
                    <div class="handyman-contact">
                        <span>
                            <span class="icon"><i class="fa-brands fa-whatsapp"></i></span>
                            <a href="tel:<?php echo $handyman_contact?>"><?php echo $handyman_contact?></a>
                        </span>                       
                    </div>
                    <div class="handyman-details">
                        <h4><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h4>
                        <p>
                            <?php echo $handyman_designation?>
                         </p>
                    </div>
                </div>
               
            </div>
            <?php
        }
        echo '</div>';
        echo '<div class="handyman-pagination-sec">';
        echo '<div class="handyman-pagination">';
        // Pagination
        $big = 999999999; // need an unlikely integer
        echo paginate_links(array(
            'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
            'format' => '?paged=%#%',
            'current' => max(1, get_query_var('paged')),
            'total' => $handyman_query->max_num_pages,
        ));
        echo '</div>';
        echo '</div>';
    } else {
        echo '<p>No handymen found.</p>';
    }

    wp_reset_postdata();

    return ob_get_clean();
}
add_shortcode('handyman', 'handyman_shortcode');

//======================= Shortcode For Best Handyman Section End ====================
