<?php

namespace TakeUrSeat;

defined('ABSPATH') or die('No script kiddies please!');

class SingleProduct {
    
    private static $_instance; // the single instance
    
    public static function getInstance() {
        
        if (!self::$_instance) { // if no instance then make one
            self::$_instance = new self();
        }

        return self::$_instance;
    }
    
    public function __construct() {
        
        /*
         * chcek if blocksy companion pro and woocommerce exist as dependencies
         *
         */
        
        if (!function_exists('is_plugin_active')) { // check if this function exist
            require_once ABSPATH . 'wp-admin/includes/plugin.php'; // include the plugin.php file if it's not
        }
            
        if ( !is_plugin_active('blocksy-companion-pro/blocksy-companion.php') || !is_plugin_active('woocommerce/woocommerce.php') ) {
                return; // if there's no blocksy companion pro active, return
        }
        
        
        // inline the style to single_product()
        add_action('wp_enqueue_scripts', array($this, 'extra_single_product_style'), 999);
        
        
        // enqueue related script
         add_action('wp_enqueue_scripts', [$this, 'enqueue_wc_single_product'], PHP_INT_MAX );
        
        // add product review form to blocksy SingleProduct
        add_action('blocksy:woocommerce:product-single:excerpt:after', [$this, 'add_product_review_form_to_single_product'] );
        
        
        // diplay the product reviews to blocksy SingleProduct
        add_action('woocommerce_after_single_product', [$this, 'display_product_reviews_to_single_product'] ); 
        
       // add_action( 'woocommerce_before_add_to_cart_form', 'comments_template', 50 );
       //add_action('blocksy:woocommerce:product-single:tabs:before', [$this, 'add_product_review_form_to_single_product'] );
        
        
        // Remove the social share box from the 'woocommerce_share' hook
        remove_action('woocommerce_share', 'blocksy_get_social_share_box' );
        add_action('blocksy:woocommerce:product-single:excerpt:before', [$this, 'custom_output_social_share_box'] );
        
        /* product gallery customization */
        /*
        add_filter('blocksy:woocommerce:product-view:use-default', function ($current_value) {
          // Use WooCommerce built in gallery
          return true;
        });
        */
        add_action('wp_print_footer_scripts', [$this, 'inline_extra_scripts'] );


    }
    
    public function custom_output_social_share_box() {
    
        echo blocksy_get_social_share_box([
            'html_atts' => [
                'data-type' => 'type-3',
            ],
            'links_wrapper_attr' => [
                'data-icons-type' => 'simple',
            ],
        ]);
    }
    
    public function add_product_review_form_to_single_product() {
        
        global $product;
        
        if ($product && comments_open()) {
    		
            echo '<div id="review_form_wrapper">';
            echo '<div id="review_form">';
    
            $comment_form = array(
                /* translators: %s is product title */
                'title_reply'         => esc_html__('Share your review', 'woocommerce'),
                /* translators: %s is product title */
                'title_reply_to'      => esc_html__('Leave a Reply to %s', 'woocommerce'),
                'title_reply_before'  => '<span id="reply-title" class="comment-reply-title">',
                'title_reply_after'   => '</span>',
                'comment_notes_after' => '',
                'label_submit'        => esc_html__('Submit', 'woocommerce'),
                'logged_in_as'        => '',
                'comment_field'       => '',
            );
    
            $name_email_required = (bool) get_option('require_name_email', 1);
            $fields              = array(
                'author' => array(
                    'label'    => __('Name', 'woocommerce'),
                    'type'     => 'text',
                    'required' => $name_email_required,
                ),
                'email'  => array(
                    'label'    => __('Email', 'woocommerce'),
                    'type'     => 'email',
                    'required' => $name_email_required,
                ),
            );
    
            $comment_form['fields'] = array();
    
            foreach ($fields as $key => $field) {
                $field_html  = '<p class="comment-form-' . esc_attr($key) . '">';
                $field_html .= '<label for="' . esc_attr($key) . '">' . esc_html($field['label']);
    
                if ($field['required']) {
                    $field_html .= '&nbsp;<span class="required">*</span>';
                }
    
                $field_html .= '</label><input id="' . esc_attr($key) . '" name="' . esc_attr($key) . '" type="' . esc_attr($field['type']) . '" value="" size="30" ' . ($field['required'] ? 'required' : '') . ' /></p>';
    
                $comment_form['fields'][$key] = $field_html;
            }
    
            if (wc_review_ratings_enabled()) {
                $comment_form['comment_field'] = '
                <div class="comment-form-rating"><label for="rating">' . esc_html__('Your rating', 'woocommerce') . (wc_review_ratings_required() ? '&nbsp;<span class="required">*</span>' : '') . '</label>
        			<select name="rating" id="rating">
                        <option value="">' . esc_html__('Rate&hellip;', 'woocommerce') . '</option>
                        <option value="5">' . esc_html__('Perfect', 'woocommerce') . '</option>
                        <option value="4">' . esc_html__('Good', 'woocommerce') . '</option>
                        <option value="3">' . esc_html__('Average', 'woocommerce') . '</option>
                        <option value="2">' . esc_html__('Not that bad', 'woocommerce') . '</option>
                        <option value="1">' . esc_html__('Very poor', 'woocommerce') . '</option>
                    </select>
                </div>';
            }
    
            $comment_form['comment_field'] .= '<p class="comment-form-comment"><label for="comment">' . esc_html__('Your review', 'woocommerce') . '&nbsp;<span class="required">*</span></label><textarea id="comment" name="comment" cols="45" rows="3" required></textarea></p>';
    
            comment_form(apply_filters('woocommerce_product_review_comment_form_args', $comment_form));
    
            echo '</div>';
            echo '</div>';
        }
        
    }
    
    public function display_product_reviews_to_single_product() {
    
        global $product;
    	$id = $product->get_id();
    	
		$args = array('post_type' => 'product', 'post_id' => $id);
			$comments = get_comments($args);
		
		if (count($comments) > 0) {
			
			echo '<div class="single-product-comment-wrapper">';

			$review_title = "What other people say";

			echo '<h3 class="single-product-comment-title">' . esc_html($review_title, 'woocommerce') . '</h3>';

			$args = array ('post_type' => 'product', 'post_id' => $id);
			$comments = get_comments( $args );
			echo '<ul class="single-product-comment-list">';
			wp_list_comments( array( 'callback' => 'woocommerce_comments' ), $comments);
			echo '</ul>';

			echo '</div>';
			
		}
       
    }
    
    public function extra_single_product_style() {
        
        if ( !is_product() ) {
            return;
        }
		
		wp_register_style( TURS_NAME .'-single-product', false);
		wp_enqueue_style( TURS_NAME.'-single-product' );
        
        $inline_style = '
            /**/
    		.entry-summary form.cart {
    			display: none
    		}
    		
            #review_form_wrapper {
		        margin-top: calc(11px + (14 - 11) * ((100vw - 300px) / (1680 - 300)))
    		}
    		
    		div.comment-form-rating {
    			font-size: calc(17px + (18 - 17) * ((100vw - 300px) / (1680 - 300)));
    		}
    		
    		span.comment-reply-title#reply-title {
    		    font-size: calc(18px + (19 - 18) * ((100vw - 300px) / (1680 - 300)));
    		    margin-bottom: calc(6px + (7 - 6) * ((100vw - 300px) / (1680 - 300)));
    		}
    		
    		form.comment-form {
    		    grid-row-gap: 1.05em;
    		}
    		
    		.comment-form p.comment-notes,
    		.comment-form-cookies-consent label {
    			font-size: calc(14.5px + (15.5 - 14.5) * ((100vw - 300px) / (1680 - 300)));
        		line-height: calc(20px + (22 - 20) * ((100vw - 300px) / (1680 - 300)));
    		}
    		
    		.comment-form-rating p.stars {
    			margin-top: -4px
    		}
    		
    		.single-product-modal.active form input,
    		.single-product-modal.active form textarea {
    			border-color: #aaa
    		}
    		.single-product-modal.active form p.form-submit {
    			margin-top: calc(10px + (12 - 10) * ((100vw - 300px) / (1680 - 300)));
    			margin-bottom: 30px;
    		}
    		#review_form_wrapper textarea {
    			height: unset
    		}
    		
    		#review_form_wrapper textarea,
    		#review_form_wrapper input {
    		    border-color: #aaa
    		}
    	
    		.single-product-comment-list .comment_container p.meta .woocommerce-review__awaiting-approval,
    		p.comment-notes {
    			opacity: .75
    		}
            
            .entry-summary .woocommerce-product-details__short-description {
                font-size: calc(17.25px + (18.5 - 17.25) * ((100vw - 300px) / (1680 - 300)));
                line-height: calc(27.5px + (29.5 - 27.5) * ((100vw - 300px) / (1680 - 300)));
            }
            .single-product-modal.active .entry-summary .woocommerce-product-rating {
            	margin-top: 5px;
            }
            
            .single-product-modal.active .entry-summary .product_title {
            	font-size: calc(24.25px + (28 - 24.25) * ((100vw - 300px) / (1680 - 300)));
            }
            
            .single-product-modal.active .entry-summary {
            	background-color: rgb(240 237 234 / 7%);
            	background-color: rgba(240, 237, 234, 0.46)
            }
            
            .entry-summary .price {
            	margin: 11px 0;
            }
            
            .single-product-modal.active .entry-summary .woocommerce-product-details__short-description,
            .comment-form label {
                opacity: .9;
            }
            
            div.single-product-comment-wrapper {
    			margin: 42px auto 22px;
                max-width: var(--normal-container-max-width);
    		}
    		
    		h3.single-product-comment-title {
    			font-size: calc(22px + (24.5 - 22) * ((100vw - 300px) / (1680 - 300)));
        		margin-bottom: calc(20.5px + (22.5 - 20.5) * ((100vw - 300px) / (1680 - 300)));
    		}
    		ul.single-product-comment-list {
    			list-style: none;
                padding-inline-start: 0;
                display: grid;
                row-gap: calc(32px + (36.5 - 32) * ((100vw - 300px) / (1680 - 300)));
                column-gap: calc(28px + (32.5 - 28) * ((100vw - 300px) / (1680 - 300)));
    		}
    		.single-product-comment-list .comment_container {
    			display: flex;
        		column-gap: 14px;
    		}
    		.single-product-comment-list .comment_container img.avatar {
    			aspect-ratio: 1/1;
    			object-fit: contain;
    			align-self: flex-start;
    			border-radius: 100px;
    			width: calc(48px + (56 - 48) * ((100vw - 300px) / (1680 - 300)));
    		}
    		.single-product-comment-list .comment_container p.meta {
    			margin: 8px 0 1px;
    			font-size: calc(16.5px + (17.5 - 16.5) * ((100vw - 300px) / (1680 - 300)));
    		}
    		.single-product-comment-list .comment_container p.meta .woocommerce-review__published-date {
    		    font-size: calc(15px + (16 - 15) * ((100vw - 300px) / (1680 - 300)));
    		}
    		.single-product-comment-list .comment_container p.meta .woocommerce-review__published-date {
    		    opacity: .8
    		}
    		
    		.single-product-comment-list .comment_container .description p {
    			font-size: calc(16px + (17 - 16) * ((100vw - 300px) / (1680 - 300)));
        		line-height: calc(23px + (24 - 23) * ((100vw - 300px) / (1680 - 300)));
    		}
    		
    		.single-product-comment-list .comment_container .description p {
    		    opacity: .85;
    		}
    		
    		.comment-text > .star-rating {
    			 font-size: calc(13.25px + (14.25 - 13.25) * ((100vw - 300px) / (1680 - 300)));
    		}
    		
    		.woocommerce-product-rating > .star-rating {
    			 font-size: calc(14.75px + (15.75 - 14.75) * ((100vw - 300px) / (1680 - 300)));
    		}
    		
            .woocommerce-product-rating .woocommerce-review-link {
                pointer-events: none;
            }
    		
    		ul.single-product-comment-list li {
    			min-width: 250px
    		}
    		ul.single-product-comment-list li p.meta {
    			
    		}
        
            .entry-summary .ct-share-box {
                border: 0;
                padding: 0;
                margin: 0;
                margin-bottom: 10px;
                display: none
            }
            
            @media (min-width: 768px) {
	
            	ul.single-product-comment-list {
            		grid-template-columns: repeat(4, 1fr);
            	}
            	
            	div.single-product-comment-wrapper {
                    max-width: var(--desktopMaxWidth);
    		    }
            	
            }
            @media (max-width: 767px) {
    		    
    		    div.single-product-comment-wrapper {
                    max-width: var(--mobileMaxWidth);
    		    }
    		    
    		}
        ';
        
        // minify the inline style before inject
        $inline_style = preg_replace(['#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')|\/\*(?!\!)(?>.*?\*\/)|^\s*|\s*$#s','#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\'|\/\*(?>.*?\*\/))|\s*+;\s*+(})\s*+|\s*+([*$~^|]?+=|[{};,>~]|\s(?![0-9\.])|!important\b)\s*+|([[(:])\s++|\s++([])])|\s++(:)\s*+(?!(?>[^{}"\']++|"(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')*+{)|^\s++|\s++\z|(\s)\s+#si','#(?<=[\s:])(0)(cm|em|ex|in|mm|pc|pt|px|vh|vw|%)#si','#(?<=[\s:,\-])0+\.(\d+)#s',],['$1','$1$2$3$4$5$6$7','$1','.$1',],$inline_style);
		
        //echo '<style>' . $inline_style . '</style>';
        
        /* inject above styles */
		wp_add_inline_style( TURS_NAME .'-single-product', esc_attr($inline_style) );
    }
    
    public function enqueue_wc_single_product() {
        
        if ( is_product() ) {
            wp_enqueue_style('ct-share-box-styles');
            
            
        }
        
    }
    
     public function inline_extra_scripts() {
		
        $inline_script = "
        const links = document.querySelectorAll('.ct-image-container');

        const videoRegex = /<video\b[^>]*>[\s\S]*<\/video>/;
        
        links.forEach(link => {
          const content = link.innerHTML;
        
          if (videoRegex.test(content)) {
            link.classList.add('video-container');
          }
        });
        
        
        const videoContainers = document.querySelectorAll('.video-container');

        videoContainers.forEach(videoContainer => {
          videoContainer.addEventListener('click', function() {
            const videoElement = this.querySelector('video');
        
            if (videoElement) {
              if (videoElement.paused) {
                videoElement.play();
                this.classList.add('video-playing');
              } else {
                videoElement.pause();
                this.classList.remove('video-playing');
              }
            }
          });
        });
        
        ";
    	
    	// minify the inline script before inject
		/**/
		$inline_script = preg_replace(['/(?:(?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:(?<!\:|\\\|\'|\")\/\/.*))/','/\>[^\S ]+/s','/[^\S ]+\</s','#("(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\'|\/\*(?>.*?\*\/))|\s*+;\s*+(})\s*+|\s*+([*$~^|]?+=|[{};,>~]|\s(?![0-9\.])|!important\b)\s*+|([[(:])\s++|\s++([])])|\s++(:)\s*+(?!(?>[^{}"\']++|"(?:[^"\\\]++|\\\.)*+"|\'(?:[^\'\\\\]++|\\\.)*+\')*+{)|^\s++|\s++\z|(\s)\s+#si'],['','>','<','$1$2$3$4$5$6$7'], $inline_script);
		
		
        $inline_script_handle = TURS_NAME.'-single-product-inline-script-js';
    
        $tus_inline_script =
            '<script id="%s">%s</script>' . PHP_EOL;
        if ( is_product() ) {
        printf(
            $tus_inline_script,
            $inline_script_handle,
            $inline_script
        );
        }
		
        
    }
    
}

// Init
SingleProduct::getInstance();