<?php
declare(strict_types=1);
/**
 * Created by PhpStorm.
 * User: jaemmer
 * Date: 1/4/18
 * Time: 12:34 PM
 */

// 1 todo
// SKIP widget title requried and set to empty (or menu's name by default)
// DONE allow featured products to have multiple sets of saving
// DONE saving not working after it's set
// switch html from bootstrap to  grid


// 2 todo
// duplicate for categories (allow for subcategory saving. name each group?)
// DONE REMOVE featured product checkbox on individual page

// 3 todo
// eventually add subcategories to IO software, create subcategory pages etc

$io_widget_cart = 0;


// The widget class
//class Widget_Featured extends WP_Widget {
class IO_Featured extends WP_Widget {

    // Main constructor
    public function __construct() {
        parent::__construct(
            'widget_featured',
            __( 'InflatableOffice Featured Products', 'text_domain' ),
            array(
                'customize_selective_refresh' => true,
            )
        );
    }
    // The widget form (for the backend )
    public function form( $instance )
    {
        // Set widget defaults
        $defaults = array(
            'title' => 'Featured Products',
            'number_of_columns' => 4,
            'add_to_cart' => 0,
            'show_price' => 0,
            'show_desc' => 0,
            'view_product_hover' => 0,
            'cat_only' => 0,
            'scrolling_view' => 0,
            'items' => Array(),
            'categories' => Array(),
            'io_id' => rand(1000, 100000)
        );

        // Parse current settings with defaults
        extract(wp_parse_args(( array )$instance, $defaults));

        $add_to_cart_checked = '';
        if(!empty($add_to_cart)) $add_to_cart_checked = 'checked="checked"';
        $show_price_checked = '';
        if(!empty($show_price)) $show_price_checked = 'checked="checked"';
        $show_desc_checked = '';
        if(!empty($show_desc)) $show_desc_checked = 'checked="checked"';
        $view_product_hover_checked = '';
        if(!empty($view_product_hover)) $view_product_hover_checked = 'checked="checked"';
        $cat_only_checked = '';
        if(!empty($cat_only)) $cat_only_checked = 'checked="checked"';
        $scrolling_view_checked = '';
        if(!empty($scrolling_view)) $scrolling_view_checked = 'checked="checked"';
        ?>

        <!--p>
            <label
                for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php _e('Widget Title', 'text_domain'); ?></label>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('title')); ?>"
                   name="<?php echo esc_attr($this->get_field_name('title')); ?>" type="text"
                   value="<?php echo esc_attr($title); ?>"/>
        </p-->

        <p>
            <label for="<?php echo esc_attr($this->get_field_id('number_of_columns')); ?>">
                <?php _e('# of Columns', 'text_domain'); ?>
            </label>
            <select class="widefat" id="<?php echo esc_attr($this->get_field_id('number_of_columns')); ?>"
                    name="<?php echo esc_attr($this->get_field_name('number_of_columns')); ?>">
                <?php
                for ($i = 1; $i <= 10; $i++) {
                    echo '<option value="' . esc_attr($i) . '" ' . selected($number_of_columns, $i, false) . '>' . $i . '</option>';
                }
                ?>
            </select>
            <script>
                jQuery( document ).ready(function() {
                    if ( jQuery("#<?php echo esc_attr($this->get_field_id('scrolling_view')); ?>").is(':checked') ) {
                        jQuery("#<?php echo esc_attr($this->get_field_id('number_of_columns')); ?>").attr('disabled','disabled');
                    } else {
                        jQuery("#<?php echo esc_attr($this->get_field_id('number_of_columns')); ?>").removeAttr('disabled');
                    }
                    jQuery("#<?php echo esc_attr($this->get_field_id('scrolling_view')); ?>").change(function() {
                        if ( jQuery(this).is(':checked') ) {
                            jQuery("#<?php echo esc_attr($this->get_field_id('number_of_columns')); ?>").attr('disabled','disabled');
                        } else {
                            jQuery("#<?php echo esc_attr($this->get_field_id('number_of_columns')); ?>").removeAttr('disabled');
                        }
                    });
                });
            </script>
        </p>

        <p>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('add_to_cart')); ?>"
                   name="<?php echo esc_attr($this->get_field_name('add_to_cart')); ?>" type="checkbox"
                   value="1" <?php echo esc_attr($add_to_cart_checked); ?>"/>
            <label
                    for="<?php echo esc_attr($this->get_field_id('add_to_cart')); ?>"><?php _e('Include Cart', 'text_domain'); ?></label>
            <br>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('show_price')); ?>"
                   name="<?php echo esc_attr($this->get_field_name('show_price')); ?>" type="checkbox"
                   value="1" <?php echo esc_attr($show_price_checked); ?>"/>
            <label
                    for="<?php echo esc_attr($this->get_field_id('show_price')); ?>"><?php _e('Show Price', 'text_domain'); ?></label>
            <br>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('show_desc')); ?>"
                   name="<?php echo esc_attr($this->get_field_name('show_desc')); ?>" type="checkbox"
                   value="1" <?php echo esc_attr($show_desc_checked); ?>"/>
            <label
                    for="<?php echo esc_attr($this->get_field_id('show_desc')); ?>"><?php _e('Show Description', 'text_domain'); ?></label>
            <br>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('view_product_hover')); ?>"
                   name="<?php echo esc_attr($this->get_field_name('view_product_hover')); ?>" type="checkbox"
                   value="1" <?php echo esc_attr($view_product_hover_checked); ?>"/>
            <label
                    for="<?php echo esc_attr($this->get_field_id('view_product_hover')); ?>"><?php _e('Include View Product Hover', 'text_domain'); ?></label>
            <br>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('scrolling_view')); ?>"
                   name="<?php echo esc_attr($this->get_field_name('scrolling_view')); ?>" type="checkbox"
                   value="1" <?php echo esc_attr($scrolling_view_checked); ?>"/>
            <label
                    for="<?php echo esc_attr($this->get_field_id('scrolling_view')); ?>"><?php _e('Scrolling View', 'text_domain'); ?></label>

            <br>Unique Widget ID: <input class="widefat" id="<?php echo esc_attr($this->get_field_id('io_id')); ?>"
                   name="<?php echo esc_attr($this->get_field_name('io_id')); ?>" type="text"
                   value="<?php echo $io_id ?>"/>
        </p>


        <?php // Dropdown ?>
        <p>

            <?php _e('Hold Ctrl to select multiple', 'text_domain'); ?><br>
            <b><label for="<?php echo $this->get_field_id('categories'); ?>">Categories</label></b> <a onclick="jQuery('#<?php echo $this->get_field_id('categories'); ?>').val([]);" style="cursor:pointer">Clear</a>
            <br>
            <input class="widefat" id="<?php echo esc_attr($this->get_field_id('cat_only')); ?>"
                   name="<?php echo esc_attr($this->get_field_name('cat_only')); ?>" type="checkbox"
                   value="1" <?php echo esc_attr($cat_only_checked); ?>"/>
            <label for="<?php echo esc_attr($this->get_field_id('cat_only')); ?>"><?php _e('Show category only', 'text_domain'); ?></label>
            <select name="<?php echo $this->get_field_name('categories'); ?>[]" id="<?php echo $this->get_field_id('categories'); ?>" class="widefat" multiple style="height:100px; resize: block; overflow: auto;">
                <?php
                $args = array('orderby' => 'name', 'order' => 'ASC', 'post_type' => 'page', 'posts_per_page' => -1);
                $loop = new WP_Query($args);
                $io_inventory_page_id = 0;
                while ( $loop->have_posts() ) : $loop->the_post();
                    //$options[$post->post_id] = array($post->post_title, 'text_domain');;
                    $key = get_the_id();
                    $name = get_the_title();
                    $content = get_the_content();
                    $include_page = get_post_meta( $key, "io-include-featured", true) === 'true' ? true : false;
                    //make sure it's an io page
                    if(strpos($content,'[sc :io_category')!==FALSE || $include_page) {
                        $select = in_array($key, $categories) ? $key : 0;
                        echo '<option value="' . esc_attr($key) . '" id="' . esc_attr($key) . '" ' . selected($select, $key, false) . '>' . $name . '</option>';
                    }
                    if(strpos($content,'[sc :io_all_cat')!==FALSE) {
                        $io_inventory_page_id = $key;
                    }
                endwhile;
                wp_reset_postdata();
                    update_option("io_inventory_page_id", $io_inventory_page_id);//used to set the order on display
                ?>
            </select>
            <br><br>
            <b><label for="<?php echo $this->get_field_id('items'); ?>">Items</label></b> <a onclick="jQuery('#<?php echo $this->get_field_id('items'); ?>').val([]);" style="cursor:pointer">Clear</a>
            <select name="<?php echo $this->get_field_name('items'); ?>[]" id="<?php echo $this->get_field_id('items'); ?>" class="widefat" multiple style="height:200px; resize: block; overflow: auto;">
                <?php
                $args = array('orderby' => 'name', 'order' => 'ASC', 'post_type' => 'page', 'posts_per_page' => -1);
                $loop = new WP_Query($args);
                while ( $loop->have_posts() ) : $loop->the_post();
                    //$options[$post->post_id] = array($post->post_title, 'text_domain');;
                    $key = get_the_id();
                    $name = get_the_title();
                    $content = get_the_content();
                    //make sure it's an io page
                    if(strpos($content,'[sc :io_rental')!==FALSE) {
                        $select = in_array($key, $items) ? $key : 0;
                        echo '<option value="' . esc_attr($key) . '" id="' . esc_attr($key) . '" ' . selected($select, $key, false) . '>' . $name . '</option>';
                    }
                endwhile;
                wp_reset_postdata();
                ?>
            </select>
        </p>

    <?php }
    // Update widget settings (also called on widget display)
    public function update( $new_instance, $old_instance ) {
        $instance = $old_instance;

        $instance['title']              = isset( $new_instance['title'] ) ? wp_strip_all_tags( $new_instance['title'] ) : '';
        $instance['width']              = isset( $new_instance['width'] ) ? wp_strip_all_tags( $new_instance['width'] ) : '';
        $instance['number_of_columns']  = isset( $new_instance['number_of_columns'] ) ? wp_strip_all_tags( $new_instance['number_of_columns'] ) : '';
        $instance['add_to_cart']        = isset( $new_instance['add_to_cart'] ) ? wp_strip_all_tags( $new_instance['add_to_cart'] ) : '';
        $instance['show_price']         = isset( $new_instance['show_price'] ) ? wp_strip_all_tags( $new_instance['show_price'] ) : '';
        $instance['show_desc']          = isset( $new_instance['show_desc'] ) ? wp_strip_all_tags( $new_instance['show_desc'] ) : '';
        $instance['view_product_hover'] = isset( $new_instance['view_product_hover'] ) ? wp_strip_all_tags( $new_instance['view_product_hover'] ) : '';
        $instance['scrolling_view']     = isset( $new_instance['scrolling_view'] ) ? wp_strip_all_tags( $new_instance['scrolling_view'] ) : '';
        $instance['cat_only']           = isset( $new_instance['cat_only'] ) ? wp_strip_all_tags( $new_instance['cat_only'] ) : '';
        $instance['io_id']              = isset( $new_instance['io_id'] ) ? wp_strip_all_tags( $new_instance['io_id'] ) : rand(1000, 100000);
        // $instance['text']     = isset( $new_instance['text'] ) ? wp_strip_all_tags( $new_instance['text'] ) : '';
        // $instance['textarea'] = isset( $new_instance['textarea'] ) ? wp_kses_post( $new_instance['textarea'] ) : '';
        //$instance['checkbox'] = isset( $new_instance['checkbox'] ) ? 1 : false;
        //$instance['items']   = isset( $new_instance['items'] ) ? wp_strip_all_tags( $new_instance['items'] ) : '';

        $instance['categories'] = array();
        $instance['items'] = array();

        if ( isset ( $new_instance['categories'] ) )
        {
            foreach ( $new_instance['categories'] as $value )
            {
                if ( '' !== trim( $value ) )
                    $instance['categories'][] = $value;
            }
        }

        if ( isset ( $new_instance['items'] ) )
        {
            foreach ( $new_instance['items'] as $value )
            {
                if ( '' !== trim( $value ) )
                    $instance['items'][] = $value;
            }
        }

        //get all featured & turn off
        /* if( sizeof($new_instance['items'])>1) {//this is here so it doesn't clear everything when you add the widget to a section.
             $args = array('orderby' => 'name', 'order' => 'ASC', 'post_type' => 'page', 'posts_per_page' => 1000, 'meta_key' => '_featured_item_box', 'meta_value' => 1);
             $loop = new WP_Query($args);
             while ($loop->have_posts()) : $loop->the_post();
                 $key = get_the_id();
                 update_post_meta($key, '_featured_item_box', 0);
             endwhile;
         }*/

        //run through list and turn on
        /*foreach($new_instance['items'] as $key){
            update_post_meta($key, '_featured_item_box', 1);
        }*/


        return $instance;
    }
    // Display the widget
    public function widget( $args, $instance ) {
        global $io_widget_cart;
        extract( $args );
        // Check the widget options
        $title              = isset( $instance['title'] ) ? apply_filters( 'widget_title', $instance['title'] ) : '';
        $show_desc          = isset( $instance['show_desc'] ) ? $instance['show_desc'] : '';
        $scrolling_view     = isset( $instance['scrolling_view'] ) ? $instance['scrolling_view'] : '';
        $cat_only           = isset( $instance['cat_only'] ) ? $instance['cat_only'] : '';
        $items              = isset( $instance['items'] ) ? $instance['items'] : $args['items'];
        $items              = empty($items) ? Array(-1) : $items;
        $categories         = isset( $instance['categories'] ) ? $instance['categories'] : $args['categories'];
        $categories         = empty($categories) ? Array(-1) : $categories;
        $instance_id        = isset( $instance['io_id'] ) ? $instance['io_id'] : '';

        if(isset( $instance['show_price'] )){
            $show_price = $instance['show_price'];
        }else if(isset( $args['show_price'] )){
            $show_price = $args['show_price'];
        }else{
            $show_price = '';
        }
        if(isset( $instance['add_to_cart'] )){
            $add_to_cart = $instance['add_to_cart'];
        }else if(isset( $args['add_to_cart'] )){
            $add_to_cart = $args['add_to_cart'];
        }else{
            $add_to_cart = '';
        }
        if(isset( $instance['view_product_hover'] )){
            $view_product_hover = $instance['view_product_hover'];
        }else if(isset( $args['view_product_hover'] )){
            $view_product_hover = $args['view_product_hover'];
        }else{
            $view_product_hover = '';
        }
        if(!empty( $instance['number_of_columns'] )){
            $number_of_columns = $instance['number_of_columns'];
        }else if(!empty( $args['number_of_columns'] )){
            $number_of_columns = $args['number_of_columns'];
        }else{
            if((isset($instance['width']) && $instance['width']>=450) || (isset($args['width']) && $args['width']>=450))
                $number_of_columns = 2;
            else
                $number_of_columns = 4;
        }
        if(!$instance_id && isset($args['io_id'])){
            $instance_id = $args['io_id'];
        }

        $io_mm_outer_style = '';
        $cat_img_style = '';
        if (!empty($number_of_columns) && empty($scrolling_view))
        {
            if($number_of_columns > 450) $number_of_columns = 2;
            elseif($number_of_columns > 10) $number_of_columns = 4;

            $standard_grid_gap = 15;
            $total_grid_gap = ($number_of_columns - 1) * $standard_grid_gap .'px';
			$io_mm_outer_style .= 'grid-template-columns:repeat('.$number_of_columns.', calc((100% - ' . $total_grid_gap .')/' . $number_of_columns .')); display:grid;';
        }

        // WordPress core before_widget hook (always include )
        echo $before_widget;
        // Display the widget
        echo '<div class="widget-text wp_widget_plugin_box panel-grid panel-has-style" style="margin-top:0px;">';
        // Display widget title if defined
        /*if ( $title ) {
            echo $before_title . $title . $after_title;
        }*/

        /*
        if(!empty($width) && empty($scrolling_view)){
            $io_mm_outer_style.= 'grid-template-columns:repeat(auto-fit, minmax('.($width-100).'px, '.$width.'px)); display:grid;';
            if($width>500) $max_height = 300;
            if($width<=500) $max_height = 275;
            if($width<=300) $max_height = 250;
            if($width<=200) $max_height = 200;
            if($width<=75) $max_height = 120;
            $cat_img_style.= 'max-height:'.$max_height.'px;';
        }
        */

        //$args = array( 'orderby'=>'modified','order'=>'DESC','post_type' => 'page', 'posts_per_page' => 10,'meta_key'=>'_featured_item_box','meta_value'=> 1);
        $merged = array_merge($items,$categories);
        $args = array( 'orderby'=>'name','order'=>'ASC', 'posts_per_page' => -1,'post_type' => 'page', 'post__in'=>$merged);
        $loop = new WP_Query( $args );
        $widget_div = '<div class="io_mm_outer ';
        $widget_div .= 'io_widget_' . $instance_id . ' ';

        $scrolling_view_script = '';
        if(!empty($scrolling_view)) {
            $widget_div .= 'io_featured_scroll" ';
            $scrolling_view_script = trim("
                <script> 
                    jQuery(document).ready(function(){
                        jQuery('.io_featured_scroll').flickity({
                          wrapAround: true,
                          draggable: false,
                          cellAlign: 'left',
                          groupCells: true,
                          lazyLoad: 1,
                          resize: true
                        });

                        setTimeout(featuredFlickityRefresh, 500);

                        jQuery('.io_featured_scroll').css('display', 'block')

                        jQuery('.io_featured_scroll .item_image').css('object-fit', 'cover')

                        jQuery('.io_featured_scroll .cat_img').css('object-fit', 'cover')

                        jQuery('.io_mm_item_scrolling .io_item2_list').css('box-shadow', 'none')
                        jQuery('.io_mm_item_scrolling .io_item2_list').addClass('nohover')

                        jQuery('.io_mm_item_scrolling .io_item2_listcat').css('box-shadow', 'none')
                        jQuery('.io_mm_item_scrolling .io_item2_listcat').addClass('nohover')
                    })

                    function featuredFlickityRefresh(){
                        jQuery('.io_featured_scroll').flickity('resize');
                    }
                </script>
            ");
        } else{
            $widget_div .= '" ';
        }

        echo "<script>
              jQuery(document).ready(function(){
                  jQuery('.io_mm_item .io_item2_list').css('box-shadow', 'none')
                  jQuery('.io_mm_item .io_item2_list').addClass('nohover')

                  jQuery('.io_mm_item .io_item2_listcat').css('box-shadow', 'none')
                  jQuery('.io_mm_item .io_item2_listcat').addClass('nohover')
              })
             </script>";

        $widget_div .= 'style="' . $io_mm_outer_style . '">';
        echo $widget_div;

        $instance_css = '';
        if(empty($add_to_cart)){
            $instance_css.='.io_widget_'.(isset($instance_id) ? $instance_id : '').' .io_item2_list_inner .rentNameIO_button {display:none !important;} ';
        }
        if(empty($show_price)){
            $instance_css.='.io_widget_'.(isset($instance_id) ? $instance_id : '').' .io_item2_list_inner .rentNameIO_price {display:none !important;} ';
        }
        if(empty($view_product_hover)){
            $instance_css.='.io_widget_'.(isset($instance_id) ? $instance_id : '').' .io_item2_list .view-product-button {display:none !important;} ';
            $instance_css.='.io_widget_'.(isset($instance_id) ? $instance_id : '').' .io_item2_listcat .view-product-button {display:none !important;} ';
        }
        if(empty($show_desc)){
            $instance_css.='.io_widget_'.(isset($instance_id) ? $instance_id : '').' .io_item2_listcat .catDescriptionIO {display:none;} ';
        }
        echo '<style>'.$instance_css.'</style>';

        $i=0;
        $flag_feature_count=0;
        $posts = Array();
        $titles = Array();
        $i=0;
        while ( $loop->have_posts() ) : $loop->the_post();
        $title = get_the_title();
        $posts[] = Array(
            'order'=>$i,
            'id'=>get_the_id(),
            'content'=>get_the_content(),
            'permalink'=>get_permalink(),
            'title'=>$title,
        );
        $titles[] = str_replace("–", "-", trim(html_entity_decode($title)));
        $i++;
        endwhile;

        wp_reset_postdata();

        //use inventory page to set order #10068
        $io_inventory_page_id = get_option("io_inventory_page_id");
        if($io_inventory_page_id>0) {
            $inv_content = get_the_content(null,false,$io_inventory_page_id);
            $inv_array = explode('[sc :io_all_cat ',$inv_content);
            $i=0;
            foreach ($inv_array as $cat) {
                $name_start = strpos($cat, 'rental_name="');
                $name = '';
                $key = false;
                if($name_start!==FALSE) {
                    $name_start += 13;
                    $name_end = strpos($cat, '"', $name_start);
                    $name = str_replace("''",'"',substr($cat, $name_start, $name_end - $name_start));
                    $key = array_search(str_replace("–", "-", trim(html_entity_decode($name))), $titles);
                }
                if($key!==FALSE){
                    $posts[$key]['order']=$i;
                }
                $i++;
            }
        }
        $posts_ordered = $this->array_orderby($posts, 'order', SORT_ASC, 'title', SORT_ASC);
        foreach($posts_ordered as $post){
            $key = $post['id'];
            $content = $post['content'];
            $include_page = get_post_meta( $key, "io-include-featured", true) === 'true' ? true : false;

            //loop for categories, product pages are single.
            //todo clear selection in select
            $content_arr = Array();

            preg_match_all("/\[sc :io_[^\]]*\]/", $content, $content_arr);
            $content_arr = $content_arr[0];
            if($include_page){
                $cat_img_style_hide = '';
                $image = wp_get_attachment_image_src( get_post_thumbnail_id( $key ), 'single-post-thumbnail' )[0];
                $title = $post['title'];
                $name = sanitize_html_class(str_replace(' ', '_', $title));
                if(!empty($scrolling_view)){
                    $item_class = "io_mm_item_scrolling";
                } else{
                    $item_class = "io_mm_item";
                }
                echo '<div class="'.$item_class.' elementor-widget-heading simpleCart_ioShelfItem" name="maindiv_'.$name.'" style="text-align:center">';
                ?>
                <a class="item_href" href="<?php echo $post['permalink'] ?>">
                    <div class="cat_div">
                        <div class="btn btn-primary view-product-button" <?php if(!$view_product_hover){ echo 'style="display:none;"'; }?>><?php echo "View More" ?></div>
                        <img class="cat_img item_image" src="<?php echo $image; ?>" alt="<?php echo $title; ?>"
                             title="<?php echo $title; ?>" style="<?php echo $cat_img_style.$cat_img_style_hide ?>">
                    </div>
                </a>
                <div class="io_item2_list_inner io_mm_title">
                <a href="<?php echo $post['permalink'] ?>"><p class="elementor-heading-title rentNameIO item_name"><?php echo $title; ?></p></a>
                </div>
                <?php
                echo '</div>';
                $flag_feature_count++;
            }else{
                foreach($content_arr as $item_key=>$item_html) {
                    $cat_img_style_hide="";
                    if(!empty($cat_only) && has_post_thumbnail( $key )){
                        //for categories we need to use the featured img bc the cat img doesn't appear in the actual code
                        $image = wp_get_attachment_image_src( get_post_thumbnail_id( $key ), 'single-post-thumbnail' )[0];
                    }else {
                        $image_start = strpos($item_html, 'image_big="') + 11;
                        if($image_start<=strlen($item_html)) $image_end = strpos($item_html, '"', $image_start);
                        if (($image_end - $image_start) <= 0) {
                            $image_start = strpos($item_html, 'image="') + 7;
                            $image_end = strpos($item_html, '"', $image_start);
                        }
                        $image = str_replace("''",'"',substr($item_html, $image_start, $image_end - $image_start));
                        if(strpos($image, "rental.software") === false && !empty($number_of_columns) && $number_of_columns<=500){
                            $image_path = $this->ContentUrlToLocalPath($image);
                            if(!empty($image_path)) {
                                list($image_width, $image_height, $image_type, $image_attr) = @getimagesize($image_path);
                                if(!empty($image_height)) $image_ratio = $image_width / $image_height;
                                $max_height = 250; // Setting to former default.
                                $w = (int)round($image_ratio * $max_height);
                                if(!empty($image_height) && $w<200 && ($image_ratio > .9 && $image_ratio < 1.1)) {
                                    //prefer built in thumb if available as it will be optimized better, but is cropped
                                    $image = substr_replace($image, "-150x150", strrpos($image, "."), 0);
                                }elseif(!empty($image_height)) {
                                    $image = $this->generateThumbnail($image, $w, $max_height);
                                }
                            }
                            /*$image_path = $this->ContentUrlToLocalPath($image);
                            $image_small = substr_replace($image, "-150x150", strrpos($image, "."), 0);
                            $image_small_path = $this->ContentUrlToLocalPath($image_small);
                            if(file_exists($image_small_path)) {
                                list($image_width, $image_height, $image_type, $image_attr) = getimagesize($image_path);
                                $image_ratio = $image_width / $image_height;//don't use cropped thumb for wide or tall img
                                if (($image_ratio > .9 && $image_ratio < 1.1)) {
                                    $image = $image_small;
                                }
                            }*/
                        }
                    }
                    if(empty($image)) $cat_img_style_hide="display:none;";

                    if($cat_only || $titles[0] == "Inventory"){
                        $view_product_text = "View Products";
                    } else{
                        $view_product_text = "View Product";
                    }

                    if(strpos($item_html, "io_category") !== false || $title == "Inventory"){
                        $name_start_pos = strpos($item_html, "cat_name");
                        if($name_start_pos) $name_first_quote_pos = strpos($item_html, '"', $name_start_pos);
                        if($name_start_pos) $name_second_quote_pos = strpos($item_html, '"', $name_first_quote_pos+1);
                        $title = substr($item_html, $name_first_quote_pos+1, ($name_second_quote_pos-$name_first_quote_pos)-1);
                        $name = sanitize_html_class(str_replace(' ', '_', $title));
                    }
                    ?>


                    <?php //echo shortcoder(Array('io_category'),$content);
                        if(!empty($scrolling_view)){
                            $item_class = "io_mm_item_scrolling";
                        } else{
                            $item_class = "io_mm_item";
                        }
                        if(substr($item_html, 0, 4) == "[sc ") $offset = 4;
                        $item_html = substr($item_html, $offset, -1);
                        if(empty($cat_only)){
                            if(substr($item_html, 0, 18) == ":io_category_cart ") continue;
                            if(substr($item_html, 0, 11) == ":io_rental ") $item_html = str_replace(":io_rental", ":io_category", $item_html);
                            if(substr($item_html, 0, 15) == ":io_all_rental ") $item_html = str_replace(":io_all_rental", ":io_category", $item_html);
                            echo '<div class="'.$item_class.' elementor-widget-heading simpleCart_ioShelfItem" name="maindiv_'.$name.'" style="text-align:center">';
                            $offset = 0;
                            $sc_attr = shortcode_parse_atts( $item_html );
                            echo shortcoder($sc_attr, "");
                            echo '</div>';
                        }else{
                            if(substr($item_html, 0, 13) == ":io_category ") continue;
                            if(substr($item_html, 0, 12) == ":io_all_cat ") continue;
                            if(substr($item_html, 0, 15) == ":io_all_rental ") continue;
                            if(substr($item_html, 0, 11) == ":io_rental ") {
                                $item_html = str_replace(":io_rental", ":io_category", $item_html);
                                echo '<div class="'.$item_class.' elementor-widget-heading simpleCart_ioShelfItem" name="maindiv_'.$name.'" style="text-align:center">';
                                $offset = 0;
                                $sc_attr = shortcode_parse_atts( $item_html );
                                echo shortcoder($sc_attr, "");
                                echo '</div>';
                                continue;
                            }
                            echo '<div class="'.$item_class.' elementor-widget-heading simpleCart_ioShelfItem" name="maindiv_'.$name.'" style="text-align:center">';
                            ?>
                                <a class="item_href" href="<?php echo $post['permalink'] ?>">
                                    <div class="cat_div">
                                        <div class="btn btn-primary view-product-button" <?php if(!$view_product_hover){ echo 'style="display:none;"'; }?>><?php echo $view_product_text ?></div>
                                        <img class="cat_img item_image" src="<?php echo $image; ?>" alt="<?php echo $title; ?>"
                                             title="<?php echo $title; ?>" style="<?php echo $cat_img_style.$cat_img_style_hide ?>">
                                    </div>
                                </a>
                                <div class="io_item2_list_inner io_mm_title">
                                <a href="<?php echo $post['permalink'] ?>"><p class="elementor-heading-title rentNameIO item_name"><?php echo $title; ?></p></a>
                                </div>
                            <?php
                            echo '</div>';
                        }

                    ?>
                    <?php
                    $flag_feature_count++;
                    $i++;
                }
            }
        }
        //echo ($i%2==0)?'':'</div>';//class row
        if($flag_feature_count == 0)
        {
            echo '<p>No Products Found</p>';
        }
        echo '</div>';

        echo '</div>';
        echo $scrolling_view_script;
        echo '<style> .io_mm_item .io_item2_list, .io_mm_item .io_item2_listcat, .io_mm_item .io_item2_listrent { margin-bottom: 0px !important; }</style>';

        if(!empty($add_to_cart) && $io_widget_cart==0){
            $io_widget_cart = 1;
            echo '<!-- Cart -->
                <div class="cartInfo" style="display:none">
                    <i class="cartIcon fas fa-shopping-cart"></i>
                    <span class="simpleCart_quantity"></span> items
                </div>';
            //note: cart won't work in megamenu. even if we get the SC to work, the pop-up will render inside the megamenu page.
        }

        // WordPress core after_widget hook (always include )
        echo $after_widget;
    }

    function array_orderby()
    {
        $args = func_get_args();
        $data = array_shift($args);
        foreach ($args as $n => $field) {
            if (is_string($field)) {
                $tmp = array();
                foreach ($data as $key => $row)
                    $tmp[$key] = $row[$field];
                $args[$n] = $tmp;
            }
        }
        $args[] = &$data;
        call_user_func_array('array_multisort', $args);
        return array_pop($args);
    }

    function ContentUrlToLocalPath($url){
        preg_match('/.*(\/wp\-content\/uploads\/\d+\/\d+\/.*)/', $url, $mat);
        if(count($mat) > 0) return ABSPATH . $mat[1];
        return '';
    }
    /**
     * Generate a thumbnail
     *
     * @param string $url url of image
     * @param int $w         The width of the image
     * @param int $h         The height of the image
     * @return mixed            The src of the new image
     */
    function generateThumbnail($url, $w = 100, $h = 100)
    {
        //$imageArr = wp_get_attachment_image_src($attachmentId, 'single-post-thumbnail');
        $imageSrc = $url;//$imageArr[0];
        $imagePath = realpath(str_replace(get_bloginfo('url'), '.', $imageSrc));
        if($imagePath) {
            $name = basename($imagePath);
            $newImagePath = str_replace($name, 'thumb_' . $w . 'x' . $h . '_' . $name, $imagePath);
            $newImageSrc = str_replace($name, 'thumb_' . $w . 'x' . $h . '_' . $name, $imageSrc);
            if (!file_exists($newImagePath)) {
                $image = wp_get_image_editor($imagePath);
                if (!is_wp_error($image)) {
                    $image->resize($w, $h, false);
                    $image->save($newImagePath);
                }
            }
        }
        else {
            $newImageSrc = "#";
        }
        return $newImageSrc;
    }

}

