<?php

// Comments
function stockie_comment($comment, $args, $depth)
{
    if ($args['style'] === 'div') {
        $tag = 'div';
        $add_below = 'comment';
    } else {
        $tag = 'li ';
        $add_below = 'div-comment';
    }
    ?>

    <<?php echo esc_attr($tag) ?><?php comment_class(empty($args['has_children']) ? '' : 'parent') ?> id="comment-<?php comment_ID() ?>">
    <?php if ('div' != $args['style']) : ?>
    <div id="div-comment-<?php comment_ID() ?>" class="comment-body">
<?php endif; ?>
    <div class="comment-author vcard">
        <?php if ($args['avatar_size'] != 0) {
            echo get_avatar($comment, 'thumbnail');
        } ?>
        <?php printf('<h4 class="title text-left">%s</h4>', get_comment_author_link()); ?>
    </div>
    <?php if ($comment->comment_approved == '0') : ?>
    <em class="comment-awaiting-moderation"><?php esc_html_e('Your comment is awaiting moderation.', 'stockie'); ?></em>
    <br/>
<?php endif; ?>

    <div class="comment-meta commentmetadata"><a
                href="<?php echo esc_url(htmlspecialchars(get_comment_link($comment->comment_ID))); ?>">
            <?php
            /* translators: 1: date, 2: time */
            printf(esc_html__('%1$s at %2$s', 'stockie'), get_comment_date(), get_comment_time()); ?></a><?php edit_comment_link(esc_html__('Edit', 'stockie'), '  ', '');
        ?>
        <div class="reply">
            <?php comment_reply_link(array_merge($args, array('add_below' => $add_below, 'reply_text' => esc_html__('Reply', 'stockie'), 'depth' => $depth, 'max_depth' => $args['max_depth']))); ?>
        </div>
    </div>
    <div class="comment-content">
        <?php comment_text(); ?>
    </div>

    <?php if ('div' != $args['style']) : ?>
    </div>
<?php endif;
}

// Posts count ( with woocommerce compability )
function stockie_post_queries($query)
{
    // not an admin page and it is the main query
    if (!is_admin() && $query->is_main_query()) {
        if (isset($query->query_vars['wc_query']) && $query->query_vars['wc_query'] == 'product_query') {
            if (function_exists('get_field')) {
                $posts_count = StockieSettings::get('woocommerce_products_on_page', 'global');
                $grid_type = StockieSettings::get('woocommerce_grid_type', 'global');
                if ($grid_type == 'type_4') {
                    $posts_count = -1;
                }
            } else {

                $posts_count = get_option('options_global_woocommerce_products_on_page');
                if (empty($posts_count)) {
                    $posts_count = false;
                }

            }
            if ($posts_count) {
                $query->set('posts_per_page', $posts_count);
            }
        } else {

            if (function_exists('get_field')) {
                $posts_count = StockieSettings::posts_per_page();
            } else {

                $posts_count = get_option('options_global_blog_posts_per_page');
                if (empty($posts_count)) {
                    $posts_count = false;
                }

            }
            if ($posts_count && $posts_count > 0 && $posts_count < 1000) {
                $query->set('posts_per_page', $posts_count);
            } else {
                $query->set('posts_per_page', 10);
            }
        }
    }
}

add_action('pre_get_posts', 'stockie_post_queries');

/**
 * Post gallery
 */
function stockie_post_gallery_override($output = '', $atts, $instance)
{
    $return = $output; // fallback
    $my_result = StockieHelper::parse_gallery_layout($atts);
    if (!empty($my_result)) {
        $return = $my_result;
    }
    return $return;
}

add_filter('post_gallery', 'stockie_post_gallery_override', 10, 3);

// Contact form 7 custom loading image
add_filter('wpcf7_ajax_loader', 'stockie_wpcf7_ajax_loader');

function stockie_wpcf7_ajax_loader()
{
    return get_template_directory_uri() . '/images/form_load.png';
}

// Fix wpautop shortcodes
function stockie_fix_wpautop_shortcodes($content)
{
    $array = array(
        '<p>[' => '[',
        ']</p>' => ']',
        ']<br />' => ']'
    );
    $content = strtr($content, $array);
    return $content;
}

add_filter('the_content', 'stockie_fix_wpautop_shortcodes');

// Hook for search widget
function stockie_override_search_form($text)
{
    $text = str_replace('type="search"', 'type="text"', $text);
    return $text;
}

add_filter('get_search_form', 'stockie_override_search_form');

// Custom arguments for cloud widget
function stockie_override_tag_cloud_widget($args)
{
    $args['smallest'] = 11;
    $args['largest'] = 11;
    $args['unit'] = 'px';

    return $args;
}

add_filter('widget_tag_cloud_args', 'stockie_override_tag_cloud_widget');

// Add content, except and feature image fields to portfolio posts
function stockie_override_save_portfolio_post($post_id, $post, $update)
{
    $post_type = get_post_type($post_id);

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if ($post_type != "stockie_portfolio" || $update == false) return;

    if (isset($_POST['acf']) && isset($_POST['acf']['field_5819a27ed1cb0']) && is_array($_POST['acf']['field_5819a27ed1cb0'])) {
        set_post_thumbnail($post, sanitize_text_field($_POST['acf']['field_5819a27ed1cb0'][0]));
    }

    if (isset($_POST['acf']) && isset($_POST['acf']['field_5818b9e99d327'])) {
        $post_update = array('ID' => $post_id);
        $post_update['post_excerpt'] = substr(sanitize_text_field($_POST['acf']['field_5818b9e99d327']), 0, 120) . '&hellip;';

        remove_action('save_post', 'stockie_override_save_portfolio_post');
        wp_update_post($post_update);
        add_action('save_post', 'stockie_override_save_portfolio_post');
    }
}

add_action('save_post', 'stockie_override_save_portfolio_post', 10, 3);

// AJAX sign in
add_action('wp_ajax_stockie_ajax_logout', 'stockie_ajax_login');
add_action('wp_ajax_nopriv_stockie_ajax_login', 'stockie_ajax_logout');
add_action('wp_ajax_nopriv_stockie_ajax_signup', 'stockie_ajax_signup');

function stockie_ajax_login()
{
    $info = array();
    $info['user_login'] = esc_attr($_POST['username']);
    $info['user_password'] = esc_attr($_POST['password']);
    $info['remember'] = esc_attr($_POST['remember']);

    $user_signon = wp_signon($info, false);
    if (is_wp_error($user_signon)) {
        echo json_encode(array(
            'loggedin' => false,
            'message' => $user_signon->get_error_message()
        ));
    } else {
        echo json_encode(array(
            'loggedin' => true,
            'message' => 'success',
            'username' => $user_signon->display_name
        ));
    }

    die();
}

function stockie_ajax_logout()
{
    wp_logout();
    echo json_encode(array('logout' => true));
    die();
}

function stockie_ajax_signup()
{
    $user_login = esc_attr($_POST['username']);
    $user_email = esc_attr($_POST['email']);

    $errors = register_new_user($user_login, $user_email);
    if (!is_wp_error($errors)) {
        echo json_encode(array(
            'success_reg' => true,
            'message' => esc_html__('Registration complete. Check your email.', 'stockie')
        ));
    } else {
        $first = key($errors->errors);
        echo json_encode(array(
            'success_reg' => false,
            'message' => $errors->errors[$first]
        ));
    }
    die();
}

// Body classes
function stockie_body_classes($classes)
{
    $classes[] = 'stockie-theme-1-0-0';

    if (StockieSettings::get_onepage_mode()) {
        $classes[] = 'stockie-anchor-onepage';
    }
    if (StockieSettings::header_menu_style() == 'style1') {
        $classes[] = 'stockie-with-header-1';
    }
    if (StockieSettings::header_menu_style() == 'style2') {
        $classes[] = 'stockie-with-header-2';
    }
    if (StockieSettings::header_menu_style() == 'style3') {
        $classes[] = 'stockie-with-header-3';
    }
    if (StockieSettings::header_menu_style() == 'style4') {
        $classes[] = 'stockie-with-header-4';
    }
    if (StockieSettings::header_menu_style() == 'style5') {
        $classes[] = 'stockie-with-header-5';
    }
    if (StockieSettings::header_menu_style() == 'style6') {
        $classes[] = 'stockie-with-header-6';
    }
    if (StockieSettings::header_menu_style() == 'style7') {
        $classes[] = 'stockie-with-header-7';
    }
    if (is_singular('post')) {
        if (StockieSettings::get('post_single_sidebar', 'global') != 'without') {
            $classes[] = 'single-post-sidebar';
        }
    }
    return $classes;
}

add_filter('body_class', 'stockie_body_classes');

//Custom cart
function stockie_remove_variation_cart_product_title($title, $cart_item, $cart_item_key)
{
    $_product = $cart_item['data'];
    $product_permalink = apply_filters('woocommerce_cart_item_permalink', $_product->is_visible() ? $_product->get_permalink($cart_item) : '', $cart_item, $cart_item_key);

    if ($_product->is_type('variation')) {
        if (!$product_permalink) {
            return $_product->get_title();
        } else {
            return sprintf('<a href="%s">%s</a>', esc_url($product_permalink), $_product->get_title());
        }
    }

    return $title;
}

add_filter('woocommerce_cart_item_name', 'stockie_remove_variation_cart_product_title', 10, 3);
add_filter('woocommerce_cart_item_name', 'stockie_add_cart_product_category', 99, 3);

function stockie_add_cart_product_category($name, $cart_item, $cart_item_key)
{
    $product_item = $cart_item['data'];
    if ($product_item->is_type('variation')) {
        $product_item = wc_get_product($product_item->get_parent_id());
    }

    $cat_ids = $product_item->get_category_ids();
    if ($cat_ids) $name .= '' . wc_get_product_category_list($product_item->get_id(), ', ', '<span class="woo-c_product_category">' . _n('', '', count($cat_ids), 'stockie') . ' ', '</span>');

    return $name;
}

// Checkout Form
remove_action('woocommerce_before_checkout_form', 'woocommerce_checkout_coupon_form');
add_action('woocommerce_after_checkout_form', 'woocommerce_checkout_coupon_form');


add_action('wp_ajax_stockie_product_modal', 'stockie_product_modal_callback');
add_action('wp_ajax_nopriv_stockie_product_modal', 'stockie_product_modal_callback');
function stockie_product_modal_callback()
{
    if (!isset($_POST['product_id'])) {
        die();
    }
    global $sitepress;
    $product_id = intval($_REQUEST['product_id']);
    wp('p=' . $product_id . '&post_type=product');
    ob_start();
    wc_get_template('product_popup.php');
    echo ob_get_clean();
    die();
}

add_action('wp_ajax_stockie_subscribe_modal', 'stockie_subscribe_modal');
add_action('wp_ajax_nopriv_stockie_subscribe_modal', 'stockie_subscribe_modal');
function stockie_subscribe_modal()
{
    ob_start();
    get_template_part('parts/elements/subscribe');
    echo ob_get_clean();
    die();
}

add_filter( 'excerpt_length', function(){
    return 14;
} );

add_filter('excerpt_more', function($more) {
    return '...';
});

function stockie_filter_the_content_more_link( $a_href_get_permalink_more_post_id_class_more_link_more_link_text_a, $more_link_text ) {

    return '';
};
add_filter( 'the_content_more_link', 'stockie_filter_the_content_more_link', 10, 2 );