<?php

/**
 * Plugin Name: EITA Commerce
 * Plugin URI: https://gitlab.com/eita/eitacommerce/
 * Description: This plugin adds some essential missings funcionalities to Woocommerce.
 * Version: 1.0.0
 * Author: Cooperativa EITA
 * Author URI: https://eita.coop.br
 * Text Domain: eitacommerce
 */

add_action( 'wp_enqueue_scripts', 'eitacommerce_enqueue_styles' );
function eitacommerce_enqueue_styles() {
		wp_enqueue_style(
			'eitacommerce-css',
			plugins_url( 'assets/css/style.css', __FILE__ )
		);
}

/**
 * Shortcode to show all products separated by a taxonomy (currently, only category)
 */

add_shortcode( 'show_categories_and_products', 'show_categories_and_products');
function show_categories_and_products( $atts ){

    if( isset($atts['columns'] ) && $atts['columns'] ) {
        $cols = $atts['columns'];
    } else {
        $cols = 5;
    }

    if( isset($atts['taxonomy']) && $atts['taxonomy'] ) {
        $taxonomy = $atts['taxonomy'];
    } else {
        $taxonomy = 'product_cat';
    }

    $categories = get_terms( array( 'taxonomy' => $taxonomy, 'hide_empty' => true) );

    $html = "";
    foreach ($categories as $category) {

        $args = array(
            'post_type' => 'product',
            'posts_per_page' => -1,
            'tax_query' => array(
                'relation' => 'AND',
                array(
                  'taxonomy' => $taxonomy,
                  'field' => 'term_id',
                  'terms' => $category->term_id
                ),
                array(
                  'taxonomy' => 'product_visibility',
                  'field' => 'name',
                  'terms' => ['outofstock', 'exclude-from-catalog'],
                  'operator' => 'NOT IN'
                )
	    ),
        );

        $posts = get_posts( $args );


        if ($posts) {
						$posts = array_map( function( $k ) { return $k->ID; }, $posts);
						$posts = implode( ",", $posts );

            $html .= '
              <h2>'.$category->name.'</h2>
							<!-- wp:woocommerce/handpicked-products {"columns":'.$cols.', "editMode":false, "orderby": "title", "products":['.$posts.']} /-->
              <!-- wp:spacer {"height":100} -->
                <div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div>
              <!-- /wp:spacer -->
            ';
        }
    }
    $blocks = parse_blocks( $html );
    $output = "";
    foreach( $blocks as $block ) {
        $output .= render_block( $block );
    }
    return $output;
}

/**
 * Override loop template and show quantities next to add to cart buttons
 */

add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_woocommerce_loop_add_to_cart_link', 10, 2 );
function quantity_inputs_for_woocommerce_loop_add_to_cart_link( $html, $product ) {
        if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
                $html = '<form action="' . esc_url( $product->add_to_cart_url() ) . '" class="cart" method="post" enctype="multipart/form-data">';
                $html .= woocommerce_quantity_input( array(), $product, false );
                $html .= '<button type="submit" class="button alt">' . esc_html( $product->add_to_cart_text() ) . '</button>';
                $html .= '</form>';
        }
        return $html;
}

/**
 * Same as before, now applied to Woocommerce blocks
 */
function add_qty_selector( $html, $data, $product ) {

        $button = '<form action="' . esc_url( $product->add_to_cart_url() ) . '" class="cart" method="post" enctype="multipart/form-data">';
        $button .= woocommerce_quantity_input( array(), $product, false );
        $button .= '<button type="submit" class="button alt">' . esc_html( $product->add_to_cart_text() ) . '</button>';
        $button .= '</form>';


        $html = "<li class=\"wc-block-grid__product\">
                <a href=\"{$data->permalink}\" class=\"wc-block-grid__product-link\">
                {$data->image}
                {$data->title}
                </a>
                {$data->badge}
                {$data->price}
                {$data->rating}
                {$button}
                </li>";

        return $html;

}
add_filter( 'woocommerce_blocks_product_grid_item_html', 'add_qty_selector', 10, 3 );

/*
* Adds a dynamic menu with the terms of a taxonomy. User must add a menu item a set it class as automenu_{taxonomy_name}. Example: automenu_product_tag. This menu item must have a submenu item to be copied.
*/
function add_taxonomy_to_menu( $nav_menu, $args ){

	$menu_items = wp_get_nav_menu_items( $args->menu );
	$js = "";
	foreach ($menu_items as $menu_item) {
		if (substr($menu_item->classes[0],0,9) == 'automenu_'){

			$taxonomy = substr($menu_item->classes[0],9);
			if ( ! taxonomy_exists( $taxonomy )){ return ""; }

			$terms = get_terms( array( 'taxonomy' => $taxonomy, 'hide_empty' => 'true' ));
			$js .= '
				<script>
					var submenu = jQuery(".'.$menu_item->classes[0].' .sub-menu");
					var first_list_item = jQuery(".'.$menu_item->classes[0].' .sub-menu li");
					var list_item = first_list_item.clone();
			';

			foreach ($terms as $term) {

				$args = array(
					'post_type' 			=> 'product',
					'posts_per_page' 	=> -1,
					'tax_query' 			=> array(
						'relation' 				=> 'AND',
						array(
							'taxonomy' 	=> $taxonomy,
							'field' 		=> 'term_id',
							'terms' 		=> $term->term_id
						),
						array(
							'taxonomy' 	=> 'product_visibility',
							'field' 		=> 'name',
							'terms' 		=> ['outofstock', 'exclude-from-catalog'],
							'operator' 	=> 'NOT IN'
						)
					),
				);

        $posts = get_posts( $args );
				if ( $posts ){
					$link = get_term_link( $term );
					$js .= '
						var term = list_item.clone();
						term.children("a").attr("href", "'.$link.'");
						term.children("a").text("'.$term->name.'");
						submenu.append(term);
					';
				}
			}
			$js .= '
				first_list_item.remove();
				</script>
			';
		}
	}

	return $nav_menu . $js;
}
add_filter( 'wp_nav_menu', 'add_taxonomy_to_menu', 10, 2);
