<?php
/**
 * The Template for displaying product archives, including the main shop page which is a post type archive
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/archive-product.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see 	    https://docs.woocommerce.com/document/template-structure/
 * @author 		WooThemes
 * @package 	WooCommerce/Templates
 * @version     2.0.0
 */

header("Location:".get_site_url()."/offer/");

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}
//if ($_GET && $_GET['p'] && !$loop->have_posts()) {.
if ($_GET && $_GET['p']) {
    $productName = $_GET['p'];
}
//if ($_GET && $_GET['cover'] && !$loop->have_posts()) {
if ($_GET && $_GET['cover']) {
    $coverName = $_GET['cover'];
}

$loop = new WP_Query(array('post_type' => array('product'), 'posts_per_page' => -1));

while ($loop->have_posts()) : $loop->the_post();
    $theid = get_the_ID();
    $productArray = new WC_Product($theid);

    if ($productArray) {
        if ($productArray->name == $productName)
            $preloadProductId = $theid;
        $image_url[$theid] = wp_get_attachment_image_src(get_post_thumbnail_id($theid), 'single-post-thumbnail');
    }

endwhile;

wp_reset_query();

global $product;
global $post;

get_header('shop');

$customerplugin = false;
if (is_plugin_active('customer-details/customer-details.php')) {
    $customerplugin = true;
}
?>

<header class="woocommerce-products-header">
    <?php if ($coverName) { ?>
        <input type="hidden" id="cover_name" value="<?= $coverName ?>">
    <?php } ?>

    <div class="banner-header">

        <img src="https://smart-sure.com/wp-content/themes/minus/images/q1.jpg" alt="Smart Sure">
    </div>
    <div class="cart-header"><?php if (is_active_sidebar('sidebar-woo')) : ?><?php dynamic_sidebar('sidebar-woo'); ?><?php endif; ?></div>
    <h1 class="woocommerce-products-header__title page-title">Select the items you want covered</h1>

</header>

<?php
/**
 * woocommerce_before_main_content hook.
 *
 * @hooked woocommerce_output_content_wrapper - 10 (outputs opening divs for the content)
 * @hooked woocommerce_breadcrumb - 20
 * @hooked WC_Structured_Data::generate_website_data() - 30
 */
do_action('woocommerce_before_main_content');
?>



<?php if ($loop->have_posts()) : ?>
    <style type="text/css">
        .box{
            display: none;
        }
        .table-custom {
            margin: 0;
            width : 50% !important;
        }
        .border-below-dashed {
            border-bottom: 1px dashed #ececec;
            margin-bottom: 10px;
        }
        .table-custom .wccpf-field.error {
            border: 1px solid #d70101 !important;
        }
    </style>
<!--    <script type="text/javascript" src="https://smart-sure.com/wp-content/themes/minus/js/jquery.min.js"></script>-->
     <!--<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>-->

    <script type="text/javascript">
        jQuery(document).ready(function ($) {
            $('.variations select').prop("required", true);
            $("select[name=age_of_item]").attr("required", true);

            if ($('#cover_name').length) {
                $('#choose-breakdown-cover').val($('#cover_name').val());
            }
            $('.addtocartlink').click(function (e) {
                var elem = $(this);
                var first_name_elem = elem.parent().find('input[name="first_name_custom_link"]');
                var first_name = first_name_elem.val();
                var contact_no_elem = elem.parent().find('input[name="contact_no_custom_link"]');
                var contact_no = contact_no_elem.val();
                var email_elem = elem.parent().find('input[name="email_custom_link"]');
                var email = email_elem.val();
                var product_id = $('.yab_pro').val();

                if ($.trim(first_name) == '' || !$.trim(first_name).match('^[a-zA-Z]+$'))
                {
                    fielderror(first_name_elem);
                } else if ($.trim(contact_no) == '' || isNaN($.trim(contact_no)))
                {
                    fielderror(contact_no_elem);
                } else if ($.trim(email) == '' || validateEmail($.trim(email)) == false)
                {
                    fielderror(email_elem);
                } else
                {
                    $.ajax({
                        method: "POST",
                        url: '<?php echo get_site_url(); ?>/wp-content/themes/minus/woocommerce/xhrrequest.php?action=addrequest',
                        data: {first_name: first_name, contact_no: contact_no, email: email, product_id: product_id}
                    })
                    .done(function (data) {
                        if (data)
                        {
                            window.location.href = '<?php echo get_site_url(); ?>/shop/?add-to-cart=' + (elem.attr('data-product_id'));
                        }
                    });
                }
            });
            
            $('.add_button').click(function (e) {
                var elem = $(this);
                var first_name_elem = elem.parents('form:first').find('input[name="first_name"]');
                var first_name = first_name_elem.val();
                var contact_no_elem = elem.parents('form:first').find('input[name="contact_no"]');
                var contact_no = contact_no_elem.val();
                var email_elem = elem.parents('form:first').find('input[name="email"]');
                var email = email_elem.val();
                var product_id = $('.yab_pro').val();

                if ($.trim(first_name) == '' || !$.trim(first_name).match('^[a-zA-Z]+$'))
                {
                    //fielderror(first_name_elem);
                } else if ($.trim(contact_no) == '' || isNaN($.trim(contact_no)))
                {
                    //fielderror(contact_no_elem);
                } else if ($.trim(email) == '' || validateEmail($.trim(email)) == false)
                {
                    //fielderror(email_elem);
                } else
                {
                    e.preventDefault();
                    $('.add_button').unbind('submit').submit();
                    $.ajax({
                        method: "POST",
                        url: '<?php echo get_site_url(); ?>/wp-content/themes/minus/woocommerce/xhrrequest.php?action=addrequest',
                        data: {first_name: first_name, contact_no: contact_no, email: email, product_id: product_id}
                    })
                    .done(function (data) {
                        if (data=='success')
                        {
                            elem.parents('form:first')[0].submit();
                        }
                    });
                }
            });
        });

        jQuery(document).ready(function ($) {
            $('input[wccpf-mandatory="yes"]').prop('required', true);
            ;
            $('.brand-text').closest("tr").hide();
            $('body').on('change', '#make', function () {
                $('.brand-text').closest("tr").hide();

                if (this.value == "Other") {
                    $('.brand-text').closest("tr").show();
                    $('.brand-text').prop("required", true);
                } else {
                    $('.brand-text').closest("tr").hide();
                    $('.brand-text').prop("required", false);
                }
            });
            $(".add-item").click(function () {
                $(this).hide();
                $('.product-selection').show();
            });
            $(".yab_pro").change(function () {
                $('select[data-attribute_name="attribute_make"]').val($("#make option:first").val());
                $('.brand-text').closest("tr").hide();
                $(".product_image_shop").hide();
                $(this).find("option:selected").each(function () {
                    var optionValue = $(this).attr("value");
                    $("#product_image_" + optionValue).show();
                    if (optionValue) {
                        $(".box").not("." + optionValue).hide();
                        $("." + optionValue).show();

                    } else {
                        $(".box").hide();
                    }
                });
                $('select[data-attribute_name="attribute_make"]').val($("#make option:first").val());
            }).change();
        });

        function validateEmail(sEmail)
        {
            var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
            if (filter.test(sEmail))
            {
                return true;
            } else
            {
                return false;
            }
        }

        function fielderror(elem)
        {
            elem.addClass('error');
            elem.focus();
            $('html, body').animate({scrollTop: elem.position().top + 200}, 'slow');
            setTimeout(function () {
                elem.removeClass('error');
            }, 5000);
        }

    </script>



    <?php
    wc_print_notices();

    woocommerce_product_subcategories();
    ?><p style="
       text-align: center;
       "><button <?php
           if ($preloadProductId) {
               echo 'style="display:none"';
           }
           ?> type="button" class="add-item button alt single_add_to_cart_button ">Add Item</button></p>
    <div <?php
           if (!$preloadProductId) {
               echo 'style="display:none"';
           }
           ?> class="product-selection ">
        <p class="product_image_wrap">

            <?php
            foreach ($image_url as $key => $images) {
                if ($images[0]) {
                    ?>
                    <img id="product_image_<?php echo $key ?>" class="product_image_shop" style="display:none"  src="<?php echo $images[0] ?>"/>
        <?php }
    }
    ?>
        </p>

        <table  cellspacing="0" class="widthhalf">

            <tr>
                <td class="label"> <label for="model">Your Item</label></td>
                <td >
                    <select class="yab_pro" value="">

    <?php while ($loop->have_posts()) : $loop->the_post(); ?>
                            <option <?php
        if ($preloadProductId && $preloadProductId == absint($product->get_id())) {
            echo 'selected="selected"';
        }
        ?> value="<?php echo absint($product->get_id()); ?>"><?php echo '<h2 class="woocommerce-loop-product__title">' . get_the_title() . '</h2>'; ?></option>	
    <?php endwhile; // end of the loop.   ?>	
                    </select>
                </td>
            </tr>

        </table> 

            <?php while ($loop->have_posts()) : $loop->the_post(); ?>
            <div class="<?php echo absint($product->get_id()); ?> box">

                <?php
                // Ensure visibility
                if (empty($product) || !$product->is_visible()) {
                    return;
                }
                ?>


                    <?php
                    ////////////////////Variation

                    if ($product->is_type('variable')) {

                        $attribute_keys = array_keys($product->get_variation_attributes());
                        ?>

                    <?php /* ?><form class="variations_form cart" method="post" enctype='multipart/form-data' data-product_id="<?php echo absint($product->id); ?>" data-product_variations="<?php echo htmlspecialchars(json_encode($product->get_available_variations())) ?>" action="https://smart-sure.com/shop">
                      <?php */ ?>
                    <?php ?><form class="variations_form cart" method="post" enctype='multipart/form-data' data-product_id="<?php echo absint($product->id); ?>" data-product_variations="<?php echo htmlspecialchars(json_encode($product->get_available_variations())) ?>" action="<?php echo get_site_url(); ?>/shop/">
                    <?php ?>

                    <?php do_action('woocommerce_before_variations_form'); ?>

            <?php if (empty($product->get_available_variations()) && false !== $product->get_available_variations()) : ?>
                            <p class="stock out-of-stock"><?php _e('This product is currently out of stock and unavailable.', 'woocommerce'); ?></p>
                                        <?php else : ?>
                            <table class="variations" cellspacing="0">
                                <tbody>
                                            <?php foreach ($product->get_variation_attributes() as $attribute_name => $options) :
                                                ?>
                                        <tr>
                                            <td class="label"><label for="<?php echo sanitize_title($attribute_name); ?>"><?php echo wc_attribute_label($attribute_name); ?></label></td>
                                            <td class="value" >
                    <?php
                    $selected = isset($_REQUEST['attribute_' . sanitize_title($attribute_name)]) ? wc_clean(urldecode($_REQUEST['attribute_' . sanitize_title($attribute_name)])) : $product->get_variation_default_attribute($attribute_name);

                    wc_dropdown_variation_attribute_options(array('options' => $options, 'attribute' => $attribute_name, 'product' => $product, 'selected' => $selected));
                    ?>
                                            </td>
                                        </tr>
                                <?php endforeach; ?>
                                </tbody>
                            </table>

                                    <?php
                                    if ($customerplugin == true) {
                                        //echo do_shortcode('[formoptionall]');
                                    }
                                    ?>

                            <?php do_action('woocommerce_before_add_to_cart_button'); ?>



                            <div class="single_variation_wrap">
                                <?php
                                /**
                                 * woocommerce_before_single_variation Hook.
                                 */
                                //do_action( 'woocommerce_before_single_variation' );

                                /**
                                 * woocommerce_single_variation hook. Used to output the cart button and placeholder for variation data.
                                 * @since 2.4.0
                                 * @hooked woocommerce_single_variation - 10 Empty div for variation data.
                                 * @hooked woocommerce_single_variation_add_to_cart_button - 20 Qty and cart button.
                                 */
                                ?>

                                <div class="woocommerce-variation-add-to-cart variations_button">


                                <?php
                                if (sizeof($woocommerce->cart->cart_contents) > 0) {
                                    echo '<button type="submit" class="single_add_to_cart_button button alt';
                                    if ($customerplugin == true)
                                        echo ' add_button';
                                    echo '">Get an Instant<br> Quote</button>';
                                    //echo '<a class="single_add_to_cart_button" href="' . $woocommerce->cart->get_checkout_url() . '" title="' . __( 'Get Quote' ) . '">' . __( 'Get Quote' ) . '</a>';
                                } else {
                                    echo '<button type="submit" class="single_add_to_cart_button button alt';
                                    if ($customerplugin == true)
                                        echo ' add_button';
                                    echo '">Get an Instant<br> Quote</button>';
                                    // echo  '<a class="single_add_to_cart_button" href="' . $cart_url . '?empty-cart=clearcart">Empty Cart</a>';
                                }
                                ?>
                                    <input type="hidden" name="quantity" value="1" />
                                    <input type="hidden" name="add-to-cart" value="<?php echo absint($product->get_id()); ?>" />
                                    <input type="hidden" name="product_id" value="<?php echo absint($product->get_id()); ?>" />
                                    <input type="hidden" name="variation_id" class="variation_id" value="0" />
                                </div>


                            </div>

                        <?php do_action('woocommerce_after_add_to_cart_button'); ?>

                    <?php endif; ?>
                    <?php do_action('woocommerce_after_variations_form'); ?>
                    </form>

                        <?php } else {
                        ?>
                <?php //do_action('woocommerce_before_add_to_cart_button'); ?>
                <div style="clear:both"></div>
            <?php
            
            if ($customerplugin == true) {
                echo do_shortcode('[formoptionnone]');
                echo sprintf('<a rel="nofollow" href="javascript:void(0)" data-href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s">%s</a>', esc_url($product->add_to_cart_url()), esc_attr(isset($quantity) ? $quantity : 1 ), esc_attr($product->id), esc_attr($product->get_sku()), esc_attr(isset($class) ? $class : 'button addtocartlink' ), esc_html($product->add_to_cart_text()));
            } else {
                echo sprintf('<a rel="nofollow" href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s">%s</a>', esc_url($product->add_to_cart_url()), esc_attr(isset($quantity) ? $quantity : 1 ), esc_attr($product->id), esc_attr($product->get_sku()), esc_attr(isset($class) ? $class : 'button addtocartlink' ), esc_html($product->add_to_cart_text()));
            }
        }
        ?>

            </div>	


        <?php endwhile; // end of the loop.  ?>


    <?php elseif (!woocommerce_product_subcategories(array('before' => woocommerce_product_loop_start(false), 'after' => woocommerce_product_loop_end(false)))) : ?>

        <?php
        /**
         * woocommerce_no_products_found hook.
         *
         * @hooked wc_no_products_found - 10
         */
        do_action('woocommerce_no_products_found');
        ?>

    <?php endif; ?>

    <?php
    /**
     * woocommerce_after_main_content hook.
     *
     * @hooked woocommerce_output_content_wrapper_end - 10 (outputs closing divs for the content)
     */
    do_action('woocommerce_after_main_content');
    ?>

    <?php
    /**
     * woocommerce_sidebar hook.
     *
     * @hooked woocommerce_get_sidebar - 10
     */
    //do_action( 'woocommerce_sidebar' );
    ?>

<?php echo '<hr class="tve_sep tve_sep1"><div style="display: inline-block; width:100%!important;"><h3 class="tve_p_center" style="text-align:center;">See what our customers are saying</h3><div class="thrv_wrapper"><hr class="tve_sep tve_sep1"></div></div>' ?>
</div>
<script src="https://widget.reviews.co.uk/carousel-inline/dist.js"></script>
<div id="carousel-inline-widget-360" style="width:100%;max-width:360px;margin:0 auto;"></div>
<script>
    carouselInlineWidget('carousel-inline-widget-360', {
        store: 'smart-sure-com',
        primaryClr: '#f47e27 ',
        neutralClr: '#f4f4f4 ',
        reviewTextClr: '#2f2f2f ',
        ratingTextClr: '#2f2f2f ',
        layout: 'fullWidth',
        numReviews: 21
    });
</script>

<?php //echo do_shortcode("[show-testimonials orderby='menu_order' order='ASC' layout='grid' options='theme:speech,info-position:info-below,text-alignment:left,columns:2,filter:none,rating:on,quote-content:short,charlimitextra: (...),display-image:on,image-size:ttshowcase_small,image-shape:circle,image-effect:none,image-link:on']");   ?>
<?php //echo'</div>'  ?>
<?php get_footer('shop'); ?>

