<?php
//namespace WprAddons\Classes;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * CRT_Count_Wishlist_Compare_Items setup
 *
 * @since 1.0
 */
class CRT_Count_Wishlist_Compare_Items { 

    /**
    ** Constructor
    */
    public function __construct() {
        add_action( 'wp_ajax_count_wishlist_items',[$this, 'count_wishlist_items'] );
        add_action( 'wp_ajax_nopriv_count_wishlist_items',[$this, 'count_wishlist_items'] );
        add_action( 'wp_ajax_count_compare_items',[$this, 'count_compare_items'] );
        add_action( 'wp_ajax_nopriv_count_compare_items',[$this, 'count_compare_items'] );
    }

	// Add two new functions for handling cookies
	public function get_wishlist_from_cookie() {
        if (isset($_COOKIE['crt_wishlist'])) {
            return json_decode(stripslashes($_COOKIE['crt_wishlist']), true);
        } else if ( isset($_COOKIE['crt_wishlist_'. get_current_blog_id() .'']) ) {
            return json_decode(stripslashes($_COOKIE['crt_wishlist_'. get_current_blog_id() .'']), true);
        }
        return array();
	}
    
    function get_compare_from_cookie() {
        if (isset($_COOKIE['crt_compare'])) {
            return json_decode(stripslashes($_COOKIE['crt_compare']), true);
        } else if ( isset($_COOKIE['crt_compare_'. get_current_blog_id() .'']) ) {
            return json_decode(stripslashes($_COOKIE['crt_compare_'. get_current_blog_id() .'']), true);
        }
        return array();
    }
    
    function count_wishlist_items() {
        $user_id = get_current_user_id();
        
        if ($user_id > 0) {
            $wishlist = get_user_meta($user_id, 'crt_wishlist', true);
            if (!$wishlist) {
                $wishlist = array();
            }
        } else {
            $wishlist = $this->get_wishlist_from_cookie();
        }

        $product_data = [];

       $product_data['wishlist_count'] = sizeof($wishlist);
       $wishlist_product_array = [];

        $settings = [
            'element_addcart_simple_txt' => isset($_POST['element_addcart_simple_txt']) ? $_POST['element_addcart_simple_txt'] : '', 
            'element_addcart_grouped_txt' => isset($_POST['element_addcart_grouped_txt']) ? $_POST['element_addcart_grouped_txt'] : '', 
            'element_addcart_variable_txt' => isset($_POST['element_addcart_variable_txt']) ? $_POST['element_addcart_grouped_txt'] : ''
        ];
            
        foreach ($wishlist as $product_id) {
            $product = wc_get_product($product_id);

            if ($product) {
                $wishlist_product_array[] = [
                    'product_id' => $product_id,
                    'product_image' => $product->get_image(),
                    'product_title' => $product->get_title(),
                    'product_url' => $product->get_permalink(),
                    'product_price' => $product->get_price_html(),
                    'product_stock' => $product->get_stock_status() == 'instock' ? esc_html__('In Stock', 'crt-manage') : esc_html__('Out of Stock', 'crt-manage'),
                    'product_atc' => $this->render_product_add_to_cart($settings, $product)
                ];
            }
        }

        $product_data['wishlist_items'] = $wishlist_product_array;

       wp_send_json($product_data);

       wp_die();
    }
    
    public function count_compare_items() {
        $user_id = get_current_user_id();
        
        if ($user_id > 0) {
            $compare = get_user_meta($user_id, 'crt_compare', true);
            if (!$compare) {
                $compare = array();
            }
        } else {
            $compare = $this->get_compare_from_cookie();
        }

        $product_data = [];

       $product_data['compare_count'] = sizeof($compare);
       $product_data['compare_table'] = $this->compare_table();

       wp_send_json($product_data);

       wp_die();
    }

    // Function to get the attribute taxonomy from the label
    public function get_taxonomy_from_label( $label ) {
        global $wpdb;
        $taxonomy = $wpdb->get_var( $wpdb->prepare("
            SELECT attribute_name
            FROM {$wpdb->prefix}woocommerce_attribute_taxonomies
            WHERE attribute_label = %s
            LIMIT 1
        ", $label) );

        return $taxonomy ? 'pa_' . $taxonomy : '';
    }

    public function compare_table() {
        $user_id = get_current_user_id();
		$notification_hidden = '';
		$table_hidden = '';

        $settings = [
            'compare_empty_text' => isset($_POST['compare_empty_text']) ? $_POST['compare_empty_text'] : '',
            'remove_from_compare_text' => isset($_POST['remove_text']) ? sanitize_text_field($_POST['remove_text']) : '',
            'element_addcart_simple_txt' => isset($_POST['element_addcart_simple_txt']) ? $_POST['element_addcart_simple_txt'] : '', 
            'element_addcart_grouped_txt' => isset($_POST['element_addcart_grouped_txt']) ? $_POST['element_addcart_grouped_txt'] : '', 
            'element_addcart_variable_txt' => isset($_POST['element_addcart_variable_txt']) ? $_POST['element_addcart_grouped_txt'] : ''
        ];

		if ($user_id > 0) {
			$compare = get_user_meta( get_current_user_id(), 'crt_compare', true );
		
			if ( ! $compare ) {
				$compare = array();
			}
		} else {
			$compare = $this->get_compare_from_cookie();
		}
		
        if ( ! $compare ) {
			$table_hidden = 'crt-hidden-element';
        } else {
			$notification_hidden = 'crt-hidden-element';
		}

        ob_start();

		echo '<p class="crt-compare-empty '. esc_attr( $notification_hidden ) .'">'. wp_kses_post( $settings['compare_empty_text'] ) .'</p>';
        
        // Start the table
		echo '<div class="crt-compare-products '. esc_attr( $table_hidden ) .'">';
        echo '<table class="crt-compare-table">';
        
            // Create the first row of table headers
            echo '<tr>';
            echo '<th></th>'; // Blank space for top-left corner
            foreach ( $compare as $product_id ) {
                $product = wc_get_product( $product_id );
                if ( ! $product ) {
                    continue;
                }
                
                $remove_text = $settings['remove_from_compare_text'];
                
                // Translators: %s will be replaced by the text for removing from compare
                $remove_text_tr = $remove_text;
                
                echo '<th data-product-id="' . esc_attr( $product->get_id() ) . '">
                        <button class="crt-compare-remove" data-product-id="' . esc_attr( $product->get_id() ) . '">' . esc_html( $remove_text_tr ) . '</button>
                      </th>';
                
            }
            echo '</tr>';
            
            // Create the remaining rows of the table
            $table_data = array(
                ['label' => esc_html__('Image', 'crt-manage'), 'type' => 'image'],
                ['label' => esc_html__('Name', 'crt-manage'), 'type' => 'text'],
                ['label' => esc_html__('Rating', 'crt-manage'), 'type' => 'text'],
                ['label' => esc_html__('Description', 'crt-manage'), 'type' => 'text'],
                ['label' => esc_html__('Price', 'crt-manage'), 'type' => 'text'],
                ['label' => esc_html__('SKU', 'crt-manage'), 'type' => 'text'],
                ['label' => esc_html__('Stock Status', 'crt-manage'), 'type' => 'text'],
                ['label' => esc_html__('Dimensions', 'crt-manage'), 'type' => 'text'],
                ['label' => esc_html__('Weight', 'crt-manage'), 'type' => 'text']
            );

            
            $all_attributes = array();
            
            foreach ( $compare as $product_id ) {
                $product = wc_get_product( $product_id );
                
                if ( ! $product ) {
                    continue;
                }

                $attributes = $product->get_attributes();

                foreach ( $attributes as $attribute ) {
                    $attribute_name = wc_attribute_label($attribute->get_name());
                    if ( !in_array($attribute_name, $all_attributes) ) {
                        $all_attributes[] = $attribute_name;
                    }
                }
            }

            foreach ( $all_attributes as $attribute_name ) {
                $table_data[] = array('label' => $attribute_name, 'type' => 'text');
            }

            foreach ( $table_data as $row ) {
                echo '<tr>';
                echo '<th>' . esc_html( $row['label'] ) . '</th>';
                foreach ( $compare as $key => $product_id ) {
                    $product = wc_get_product( $product_id );
                    if ( ! $product ) {
                        continue;
                    }
                    echo '<td data-product-id="' . esc_attr( $product->get_id() ) . '">';
                    switch ( $row['type'] ) {
                        case 'image':
                            echo '<a class="crt-compare-img-wrap" href="' . esc_url( $product->get_permalink() ) . '">' . wp_kses_post( $product->get_image() ) . '</a>';
							echo '<div class="crt-compare-product-atc">' . wp_kses_post( $this->render_product_add_to_cart( $settings, $product ) ) . '</div>';
                            break;
                        case 'text': 
                            if( in_array(strtolower($row['label']), [strtolower(__('Description', 'crt-manage')), strtolower(__('SKU', 'crt-manage')) ]) ) {
                                echo wp_kses_post( $product->get_data()[strtolower($row['label'])] );
                            } else if ( strtolower($row['label']) == strtolower(__('Name', 'crt-manage')) ) {
                                echo '<a class="crt-compare-product-name" href="' . esc_url( $product->get_permalink() ) . '">'. esc_html( $product->get_data()['name'] ) .'</a>';
							} else if ( strtolower($row['label']) == strtolower(__('Price', 'crt-manage')) ) {
                                echo wp_kses_post( $product->get_price_html() );
                            } else if ( strtolower($row['label']) ==strtolower(__('Rating', 'crt-manage')) ) {
                                echo wp_kses_post( $this->render_product_rating($product) );
                            } else if ( strtolower($row['label']) == strtolower(__('Stock Status', 'crt-manage')) ) {
					            $stock_status = $product->get_stock_status();
                                echo $stock_status == 'instock' ? esc_html__('In Stock', 'crt-manage') : esc_html__('Out of Stock', 'crt-manage');
                            } else if ( strtolower($row['label']) == strtolower(__('Dimensions', 'crt-manage')) ) {

								if ( $product->has_dimensions() ) {
									$dimensions = sprintf(
										'<span class="crt-dimensions">%s</span>',
										wc_format_dimensions( $product->get_dimensions( false ) )
									);
	
									echo wp_kses_post( $dimensions );
								}
								
							} else if ( strtolower($row['label']) == strtolower(__('Weight', 'crt-manage')) ) {

								if ( $product->get_weight() ) {
									$weight = sprintf(
										'<span class="crt-weight">%s %s</span>',
										$product->get_weight(),
										get_option( 'woocommerce_weight_unit' )
									);
	
									echo wp_kses_post( $weight );
								}

							} else {      
                                $attributes = $product->get_attributes();
                                $attribute_name = wc_attribute_label(strtolower($row['label']));

								foreach ($product->get_attributes($product_id) as $attr) {

									if ( strtolower($attr['name']) === strtolower($row['label']) ) {
										echo wp_kses_post( $attr['value'] );
									}
								}

								// Product Attributes
                                // $attribute_name = $this->format_variable($attribute_name);
                                $attribute_name = $this->get_taxonomy_from_label($attribute_name);

								if (isset($attributes[$attribute_name])) {
									// Get the value(s) of the 'dimensions' attribute for the product
									$attributes_value = $attributes[$attribute_name]->get_options();
									$attributes_value_array = [];

									// Loop through the values and output them
									foreach ($attributes_value as $value) {
										$term = get_term($value);
										$attributes_value_array[] = $term->name;
									}

									echo esc_html( implode(' | ', $attributes_value_array) );
								}
                            }
                            break;
                    }
                    echo '</td>';
                }
                echo '</tr>';
            }
        
        // Close the table
        echo '</table>';
		echo '</div>';

        return ob_get_clean();
    }

    public function format_variable($variable) {
        $variable = strtolower($variable); // Convert to lowercase
        $variable = str_replace(' ', '-', $variable); // Replace spaces with hyphens
        return $variable;
    }

    public function render_product_rating($product) {

        // $rating_count = $product->get_rating_count();
		// $rating_amount = floatval( $product->get_average_rating() );
		// $round_rating = (int)$rating_amount;
        // $rating_icon = '&#9734;';

		// echo '<div class="crt-woo-rating">';

		// 	for ( $i = 1; $i <= 5; $i++ ) {
		// 		if ( $i <= $rating_amount ) {
		// 			echo '<i class="crt-rating-icon-full">'. $rating_icon .'</i>';
		// 		} elseif ( $i === $round_rating + 1 && $rating_amount !== $round_rating ) {
		// 			echo '<i class="crt-rating-icon-'. ( $rating_amount - $round_rating ) * 10 .'">'. $rating_icon .'</i>';
		// 		} else {
		// 			echo '<i class="crt-rating-icon-empty">'. $rating_icon .'</i>';
		// 		}
	    //  	}

		// echo '</div>';

		// Another option
		$rating  = $product->get_average_rating();
		$count   = $product->get_rating_count();
		return wc_get_rating_html( $rating, $count );
	}
    	
	// Render Add To Cart
	public function render_product_add_to_cart( $settings, $product ) {

		// If NOT a Product
		if ( is_null( $product ) ) {
			return;
		}

		ob_start();

		// Get Button Class
		$button_class = implode( ' ', array_filter( [
			'product_type_'. $product->get_type(),
			$product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
			$product->supports( 'ajax_add_to_cart' ) ? 'ajax_add_to_cart' : '',
		] ) );

		$attributes = [
			'rel="nofollow"',
			'class="'. esc_attr($button_class) .' crt-button-effect '. (!$product->is_in_stock() && 'simple' === $product->get_type() ? 'crt-atc-not-clickable' : '').'"',
			'aria-label="'. esc_attr($product->add_to_cart_description()) .'"',
			'data-product_id="'. esc_attr($product->get_id()) .'"',
			'data-product_sku="'. esc_attr($product->get_sku()) .'"',
		];

		$button_HTML = '';
		$page_id = get_queried_object_id();

		// Button Text
		if ( 'simple' === $product->get_type() ) {
			$button_HTML .= $settings['element_addcart_simple_txt'];

			if ( 'yes' === get_option('woocommerce_enable_ajax_add_to_cart') ) {
				array_push( $attributes, 'href="'. esc_url( get_permalink( $page_id ) .'/?add-to-cart='. get_the_ID() ) .'"' );
			} else {
				array_push( $attributes, 'href="'. esc_url( get_permalink() ) .'"' );
			}
		} elseif ( 'grouped' === $product->get_type() ) {
			$button_HTML .= $settings['element_addcart_grouped_txt'];
			array_push( $attributes, 'href="'. esc_url( $product->get_permalink() ) .'"' );
		} elseif ( 'variable' === $product->get_type() ) {
			$button_HTML .= $settings['element_addcart_variable_txt'];
			array_push( $attributes, 'href="'. esc_url( $product->get_permalink() ) .'"' );
		} else {
			array_push( $attributes, 'href="'. esc_url( $product->get_product_url() ) .'"' );
			$button_HTML .= get_post_meta( get_the_ID(), '_button_text', true ) ? get_post_meta( get_the_ID(), '_button_text', true ) : 'Buy Product';
		}

			// Button HTML
		echo '<a '. implode( ' ', $attributes ) .'><span>'. $button_HTML .'</span></a>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

		return \ob_get_clean();
	} 
}

new CRT_Count_Wishlist_Compare_Items();