<?php

add_filter('woocommerce_enqueue_styles', '__return_empty_array');

add_action('woocommerce_product_query', 'stockie_products_per_page', 1, 50);
function stockie_products_per_page($query)
{
    if ($query->is_main_query()) {
        $query->set('posts_per_page', '12');
    }
}


// Widgets
function stockie_woocommerce_tag_cloud_widget()
{
    $args = array(
        'smallest' => 11,
        'largest' => 11,
        'unit' => 'px',
        'number' => 15,
        'taxonomy' => 'product_tag'
    );
    return $args;
}

add_filter('woocommerce_product_tag_cloud_widget_args', 'stockie_woocommerce_tag_cloud_widget');


function stockie_woocommerce_scripts()
{

    $products_in_row = StockieSettings::get('woocommerce_products_in_row', 'global');
    if (is_string($products_in_row)) {
        $products_in_row = json_decode($products_in_row);
    }
    if ($products_in_row == NULL) {
        $products_in_row = (object)array(
            "large" => "3",
            "medium" => "2",
            "small" => "2"
        );
    }

    wp_register_script('woocommerce-hack', get_template_directory_uri() . '/assets/js/woocommerce-hack.js', array('jquery'), false, true);
    wp_enqueue_script('woocommerce-hack');

    $translation_array = array(
        'updating_text' => esc_html__('Updating...', 'stockie'),
        'warn_remove_text' => esc_html__('Are you sure you want to remove this item from cart?', 'stockie')
    );
    wp_localize_script('woocommerce-hack', 'wooajaxcart_localization', $translation_array);

    wp_add_inline_script('woocommerce-hack', "jQuery(document).on( 'ready', function() {
        wacZeroQuantityCheck = function(el_qty) { return true; };
    });");

}

add_action('wp_enqueue_scripts', 'stockie_woocommerce_scripts');


remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_title', 5);
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10);
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_rating', 10);
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_excerpt', 20);
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30);
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_meta', 40);
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_sharing', 50);

add_action('woocommerce_single_product_summary', 'woocommerce_template_single_title', 5);
add_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10);
add_action('woocommerce_single_product_summary', 'woocommerce_template_single_rating', 10);
add_action('woocommerce_single_product_summary', 'woocommerce_template_single_excerpt', 20);
add_action('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30);
add_action('woocommerce_single_product_summary', 'woocommerce_template_single_meta', 25);
add_action('woocommerce_single_product_summary', 'woocommerce_template_single_sharing', 50);


function stockie_woocommerce_message_filter_function($message)
{
    $message = preg_replace('/(<a)(.+\/a>)(.+)/i', '${3} ${1} ${2}', $message);
    $message = preg_replace('/"button/i', '"', $message);
    return $message;
}

add_filter('woocommerce_add_message', 'stockie_woocommerce_message_filter_function', 10, 1);
add_filter('woocommerce_add_error', 'stockie_woocommerce_message_filter_function', 10, 1);
add_filter('woocommerce_add_notice', 'stockie_woocommerce_message_filter_function', 10, 1);

// Custom icon for PayPal payment option on WooCommerce checkout page.
function stockie_woocommerce_isa_extended_paypal_icon()
{
    return get_template_directory_uri() . '/assets/images/paypal.svg';
}

add_filter('woocommerce_paypal_icon', 'stockie_woocommerce_isa_extended_paypal_icon');

// WooCommerce sidebar
function stockie_woocommerce_widgets_init()
{
    register_sidebar(array(
        'name' => esc_html__('Shop', 'stockie'),
        'id' => 'wc_shop',
        'description' => esc_html__('WooCommerce sidebar.', 'stockie'),
        'before_title' => '<h3 class="title widget-title">',
        'after_title' => '</h3>',
    ));
}

add_action('widgets_init', 'stockie_woocommerce_widgets_init');

function stockie_woocommerce_header_add_to_cart_fragment($fragments)
{
    global $woocommerce;
    $fragments['span.cart-count'] = '<span class="cart-count brand-bg-color">' . esc_attr($woocommerce->cart->cart_contents_count) . '</span>';
    return $fragments;
}

add_filter('woocommerce_add_to_cart_fragments', 'stockie_woocommerce_header_add_to_cart_fragment');

add_filter('woocommerce_add_to_cart_fragments', 'header_add_to_cart_fragment', 30, 1);
function header_add_to_cart_fragment($fragments)
{
    global $woocommerce;
    ob_start(); ?>
    <a class="cart-customlocation"
       href="<?php echo wc_get_cart_url(); ?>"><?php echo WC()->cart->get_cart_total(); ?></a>
    <?php
    $fragments['a.cart-customlocation'] = ob_get_clean();
    return $fragments;
}

// WooCommerce size images
function stockie_woocommerce_image_dimensions()
{
    $catalog = array(
        'width' => '800',
        'height' => '',
        'crop' => 1
    );
    $single = array(
        'width' => '600',
        'height' => '',
        'crop' => 1
    );
    $thumbnail = array(
        'width' => '120',
        'height' => '',
        'crop' => 1
    );

    update_option('shop_catalog_image_size', $catalog);
    update_option('shop_single_image_size', $single);
    update_option('shop_thumbnail_image_size', $thumbnail);
}

add_action('init', 'stockie_woocommerce_image_dimensions', 1);

// Wishlist

if (!function_exists('yith_wcwl_is_wishlist_page') && function_exists('yith_wcwl_object_id')) {
    /**
     * Check if current page is wishlist
     *
     * @return bool
     * @since 2.0.13
     */
    function yith_wcwl_is_wishlist_page()
    {
        $wishlist_page_id = yith_wcwl_object_id(get_option('yith_wcwl_wishlist_page_id'));

        if (!$wishlist_page_id) {
            return false;
        }

        return is_page($wishlist_page_id);
    }
}

//	WooProduct fallback
if (!function_exists('is_product')) {
    function is_product()
    {
        return false;
    }
}

// Standart user avatar
function stockie_override_new_gravatar($avatar_defaults)
{
    $myavatar = get_template_directory_uri() . 'assets/images/sc_gap_user.svg';
    $avatar_defaults[$myavatar] = esc_html__('Stockie Default Avatar', 'stockie');
    return $avatar_defaults;
}

add_filter('avatar_defaults', 'stockie_override_new_gravatar');

// Ajax cart
add_action('wp_ajax_stockie_ajax_add_to_cart_woo', 'stockie_ajax_add_to_cart_woo_callback');
add_action('wp_ajax_nopriv_stockie_ajax_add_to_cart_woo', 'stockie_ajax_add_to_cart_woo_callback');
function stockie_ajax_add_to_cart_woo_callback()
{
    ob_start();
    $product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
    $variation_id = $_POST['variation_id'];
    $variation = $_POST['variation'];
    $product = $product_data = wc_get_product( $variation_id ? $variation_id : $product_id );
    $quantity = empty($_POST['quantity']) ? 1 : apply_filters('woocommerce_stock_amount', $_POST['quantity']);
    $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
    $product_status = get_post_status($product_id);


    if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id, $variation)) {
        do_action('woocommerce_ajax_added_to_cart', $product_id);

        if (get_option('woocommerce_cart_redirect_after_add') == 'yes') {
            wc_add_to_cart_message(array($product_id => $quantity), false);
        }

        WC_AJAX::get_refreshed_fragments();

    } else {

        if (!$product->is_in_stock()) {
            $data = array(
                'error' => true,
                'message' => sprintf(__('You cannot add &quot;%s&quot; to the cart because the product is out of stock.', 'stockie'), $product->get_name()),
            );
        }

        if (!$product->has_enough_stock($quantity)) {
            $data = array(
                'error' => true,
                'message' => sprintf(__('You cannot add that amount of &quot;%1$s&quot; to the cart because there is not enough stock (%2$s remaining).', 'stockie'), $product->get_name(), wc_format_stock_quantity_for_display($product->get_stock_quantity(), $product)),
            );
        }

        if ($product->managing_stock()) {
            $products_qty_in_cart = WC()->cart->get_cart_item_quantities();
            if (isset($products_qty_in_cart[$product->get_stock_managed_by_id()]) && !$product->has_enough_stock($products_qty_in_cart[$product->get_stock_managed_by_id()] + $quantity)) {
                $data = array(
                    'error' => true,
                    'message' => sprintf(
                        '%s <a href="%s" class="wc-forward">%s</a>',
                        sprintf(__('You cannot add that amount to the cart &mdash; we have %1$s in stock and you already have %2$s in your cart.', 'stockie'), wc_format_stock_quantity_for_display($product->get_stock_quantity(), $product), wc_format_stock_quantity_for_display($products_qty_in_cart[$product->get_stock_managed_by_id()], $product)),
                        wc_get_cart_url(),
                        __('View cart', 'stockie')
                    ),
                );
            }
        }
        
        echo json_encode($data);
    }
    die();
}

add_action('wp_ajax_stockie_ajax_add_to_cart_woo_single', 'stockie_ajax_add_to_cart_woo_single_callback');
add_action('wp_ajax_nopriv_stockie_ajax_add_to_cart_woo_single', 'stockie_ajax_add_to_cart_woo_single_callback');
function stockie_ajax_add_to_cart_woo_single_callback()
{
    ob_start();


    $product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
    $product = wc_get_product($product_id);
    $quantity = empty($_POST['quantity']) ? 1 : apply_filters('woocommerce_stock_amount', $_POST['quantity']);
    $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
    $product_status = get_post_status($product_id);
    $variation_id = 0;
    $variation = array();


    if ($passed_validation && false !== WC()->cart->add_to_cart($product_id, $quantity, $variation_id, $variation) && 'publish' === $product_status) {

        do_action('woocommerce_ajax_added_to_cart', $product_id);
        if (get_option('woocommerce_cart_redirect_after_add') == 'yes') {
            wc_add_to_cart_message($product_id);
        }

        WC_AJAX::get_refreshed_fragments();

    } else {

        if (!$product->is_in_stock()) {
            $data = array(
                'error' => true,
                'message' => sprintf(__('You cannot add &quot;%s&quot; to the cart because the product is out of stock.', 'stockie'), $product->get_name()),
            );
        }

        if (!$product->has_enough_stock($quantity)) {
            $data = array(
                'error' => true,
                'message' => sprintf(__('You cannot add that amount of &quot;%1$s&quot; to the cart because there is not enough stock (%2$s remaining).', 'stockie'), $product->get_name(), wc_format_stock_quantity_for_display($product->get_stock_quantity(), $product)),
            );
        }

        if ($product->managing_stock()) {
            $products_qty_in_cart = WC()->cart->get_cart_item_quantities();
            if (isset($products_qty_in_cart[$product->get_stock_managed_by_id()]) && !$product->has_enough_stock($products_qty_in_cart[$product->get_stock_managed_by_id()] + $quantity)) {
                $data = array(
                    'error' => true,
                    'message' => sprintf(
                        '%s <a href="%s" class="wc-forward">%s</a>',
                        sprintf(__('You cannot add that amount to the cart &mdash; we have %1$s in stock and you already have %2$s in your cart.', 'stockie'), wc_format_stock_quantity_for_display($product->get_stock_quantity(), $product), wc_format_stock_quantity_for_display($products_qty_in_cart[$product->get_stock_managed_by_id()], $product)),
                        wc_get_cart_url(),
                        __('View cart', 'stockie')
                    ),
                );
            }
        }

        echo json_encode($data);
    }

    die();
}


add_filter('body_class', 'stockie_single_product_classes');
function stockie_single_product_classes($classes)
{
    if (is_product()) {
        $classes[] = StockieSettings::get_product_type() . '-' . StockieSettings::get_product_view_mode();
    }

    if (StockieSettings::get('woocommerce_add_to_cart_ajax', 'global')) {
        $classes[] = 'ajax-add-to-cart';
    }

    return $classes;
}


// Ajax search
add_action('wp_ajax_stockie_ajax_search', 'stockie_ajax_search');
add_action('wp_ajax_nopriv_stockie_ajax_search', 'stockie_ajax_search');
function stockie_ajax_search()
{
    global $woocommerce;
    $products = array();
    $allowed_html = array(
        'div' => array(
            'class' => true,
            'id' => true
        ),
        'img' => array(
            'class' => true,
            'src' => true,
            'alt' => true
        ),
        'span' => array(
            'class' => true
        )
    );

    if (!empty($_POST['search_query'])) {

        $args = array(
            'post_type' => 'product',
            'posts_per_page' => '3',
            'fields' => 'ids',
            's' => $_POST['search_query'],
        );

        if (!empty($_POST['search_term'])) {
            $args['tax_query'] = array(
                array(
                    'taxonomy' => 'product_cat',
                    'field' => 'id',
                    'terms' => $_POST['search_term'],
                )
            );
        }

        $ids_query = new WP_Query($args);
        $ids_query = $ids_query->posts;

        if (!empty($ids_query)) {
            $query = new WC_Product_Query(array(
                'limit' => 3,
                'orderby' => 'date',
                'order' => 'DESC',
                'include' => $ids_query
            ));
            $products = $query->get_products();
        }

    } else {

        $args = array(
            'post_type' => 'product',
            'posts_per_page' => '3',
            'fields' => 'ids',
        );

        if (!empty($_POST['search_term'])) {
            $args['tax_query'] = array(
                array(
                    'taxonomy' => 'product_cat',
                    'field' => 'id',
                    'terms' => $_POST['search_term'],
                )
            );
        }

        $ids_query = new WP_Query($args);
        $ids_query = $ids_query->posts;

        $query = new WC_Product_Query(array(
            'limit' => 3,
            'orderby' => 'date',
            'order' => 'DESC',
            'include' => $ids_query
        ));
        $products = $query->get_products();

    }

    $response = stockie_search_draw($products, '', $_POST['search_query'], $_POST['search_term']);

    echo wp_kses($response, $allowed_html);

    wp_die();
}

function stockie_search_draw($products = null, $response = '', $s = '', $search_term = '')
{

    if (!empty($products)) {

        $response .= "<div class='suggestions'>" . esc_html__("Search suggestions", "stockie") . "</div>";

        foreach ($products as $product) {

            $id = $product->get_id();
            $name = $product->get_name();
            $price = $product->get_price_html();
            $image = wp_get_attachment_image_src(get_post_thumbnail_id($id), 'thumbnail')[0];
            $url = get_the_permalink($id);
            $currency = get_woocommerce_currency_symbol();

            $response .= "
            <div id='product-$id' class='product_search'>
                <div class='product_search_img'>
                <a href='$url'>
                    <img src='$image' />
                </a>
                </div>
                    <div class='product_search_description '>
                        <a href='$url' class='product_search_name'>
                            <div>$name</div>
                        </a>
                        ";
            if (!empty($price)) {
                $response .= "<a href='$url' ><div class='product_search_price'>$price</div></a>";
            }
            $response .= "
                    </div>
                <div class='clear'></div>
            </div>
            ";
        }


        // count of found posts
        $count = 0;
        if ($search_term) {
            $term = get_term($search_term, 'product_cat');
            $url = get_term_link($term);
            $args = array(
                'post_type' => 'product',
                'posts_per_page' => -1,
                'fields' => 'ids',
                's' => $s,
                'tax_query' => array(
                    array(
                        'taxonomy' => 'product_cat',
                        'field' => 'id',
                        'terms' => $_POST['search_term'],
                    )
                )
            );
            $query = new WP_Query($args);
            $count = $query->post_count;
        } else {
            $url = get_permalink(wc_get_page_id('shop'));
            if ($s) {
                $args = array(
                    'post_type' => 'product',
                    'posts_per_page' => -1,
                    'fields' => 'ids',
                    's' => $s,
                );
                $query = new WP_Query($args);
                $count = $query->post_count;
            } else {
                $products_total = wp_count_posts('product');
                $count = $products_total->publish;
            }
        }

        $response .= '<div id="search_form_action" data-href="' . $url . '"></div>';

        // if count > 3 we showing btn
        if ($count > 3) {
            $response .= "<a href='$site/?s=$s&post_type=product&search_term=$search_term' class='btn search_results_btn btn-loading-disable'>";
            $response .= __('Show All', 'stockie');
            $response .= "<i class='ion ion-right ion-ios-arrow-forward'></i></a>";
        }
    } else {
        $response = '<div class="no-search-results">';
        $response .= esc_html__('No results for your search query', 'stockie');
        $response .= '</div>';
    }
    return wp_send_json($response);
}