<?php
/**
 * Related WooCommerce Products Widget
 *
 * Displays WooCommerce products related to the current repair issue
 *
 * @package Tech_Repair_Service
 */

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

/**
 * Tech_Repair_Related_Products_Widget Class
 */
class Tech_Repair_Related_Products_Widget extends WP_Widget {

    /**
     * Constructor
     */
    public function __construct() {
        parent::__construct(
            'tech_repair_related_products',
            esc_html__( 'Tech Repair: Related Products', 'tech-repair-service' ),
            array(
                'description' => esc_html__( 'Displays WooCommerce products related to the current repair issue', 'tech-repair-service' ),
                'classname'   => 'tech-repair-related-products-widget',
            )
        );
    }

    /**
     * Widget output
     *
     * @param array $args     Widget arguments.
     * @param array $instance Saved values from database.
     */
    public function widget( $args, $instance ) {
        // Check if WooCommerce is active
        if ( ! class_exists( 'WooCommerce' ) ) {
            return;
        }

        // Get widget settings
        $title = ! empty( $instance['title'] ) ? $instance['title'] : esc_html__( 'Recommended Products', 'tech-repair-service' );
        $number = ! empty( $instance['number'] ) ? absint( $instance['number'] ) : 3;
        $show_thumbnail = isset( $instance['show_thumbnail'] ) ? (bool) $instance['show_thumbnail'] : true;
        $show_price = isset( $instance['show_price'] ) ? (bool) $instance['show_price'] : true;
        $show_rating = isset( $instance['show_rating'] ) ? (bool) $instance['show_rating'] : true;
        $display_mode = ! empty( $instance['display_mode'] ) ? $instance['display_mode'] : 'relevant';
        $keywords = ! empty( $instance['keywords'] ) ? $instance['keywords'] : '';
        $product_category = ! empty( $instance['product_category'] ) ? $instance['product_category'] : '';

        // Apply widget arguments
        echo wp_kses_post( $args['before_widget'] );
        
        // Widget title
        echo wp_kses_post( $args['before_title'] . apply_filters( 'widget_title', $title ) . $args['after_title'] );

        // Get products based on display mode
        $products = null;
        
        switch ( $display_mode ) {
            case 'relevant':
                $products = $this->get_relevant_products( $number );
                break;
                
            case 'random':
                $products = $this->get_random_products( $number, $product_category );
                break;
                
            case 'keywords':
                $products = $this->get_products_by_keywords( $number, $keywords, $product_category );
                break;
                
            default:
                $products = $this->get_relevant_products( $number );
                break;
        }

        if ( $products && $products->have_posts() ) {
            echo '<ul class="tech-repair-products-list">';
            
            while ( $products->have_posts() ) {
                $products->the_post();
                global $product;
                
                if ( ! is_a( $product, 'WC_Product' ) ) {
                    continue;
                }
                
                echo '<li class="tech-repair-product-item">';
                
                // Product link start
                echo '<a href="' . esc_url( get_permalink() ) . '" class="tech-repair-product-link">';
                
                // Product thumbnail
                if ( $show_thumbnail && has_post_thumbnail() ) {
                    echo '<div class="tech-repair-product-thumb">';
                    echo get_the_post_thumbnail( get_the_ID(), 'thumbnail' );
                    echo '</div>';
                }
                
                echo '<div class="tech-repair-product-info">';
                
                // Product title
                echo '<h4 class="tech-repair-product-title">' . get_the_title() . '</h4>';
                
                // Product price
                if ( $show_price ) {
                    echo '<div class="tech-repair-product-price">';
                    echo $product->get_price_html();
                    echo '</div>';
                }
                
                // Product rating
                if ( $show_rating && $product->get_rating_count() > 0 ) {
                    echo '<div class="tech-repair-product-rating">';
                    echo wc_get_rating_html( $product->get_average_rating() );
                    echo '</div>';
                }
                
                echo '</div>'; // .tech-repair-product-info
                echo '</a>'; // .tech-repair-product-link
                echo '</li>';
            }
            
            echo '</ul>';
            
            // Add "View all" link
            echo '<div class="tech-repair-view-all-products">';
            echo '<a href="' . esc_url( wc_get_page_permalink( 'shop' ) ) . '" class="tech-repair-view-all-link">';
            echo esc_html__( 'View all products', 'tech-repair-service' );
            echo '</a>';
            echo '</div>';
            
            wp_reset_postdata();
        } else {
            echo '<p>' . esc_html__( 'No related products found.', 'tech-repair-service' ) . '</p>';
        }

        echo wp_kses_post( $args['after_widget'] );
    }

    /**
     * Get products relevant to the current repair issue
     *
     * @param int $number Number of products to display
     * @return WP_Query
     */
    private function get_relevant_products( $number ) {
        $search_terms = array();
        $issue_id = 0;
        
        // Get current post ID
        if ( is_singular( 'tech_repair_issue' ) ) {
            $issue_id = get_the_ID();
            
            // Get issue title
            $search_terms[] = get_the_title();
            
            // Get issue types
            $issue_types = get_the_terms( $issue_id, 'tech_repair_issue_type' );
            if ( ! empty( $issue_types ) && ! is_wp_error( $issue_types ) ) {
                foreach ( $issue_types as $type ) {
                    $search_terms[] = $type->name;
                }
            }
            
            // Get compatible devices
            $compatible_devices = get_post_meta( $issue_id, '_tech_repair_compatible_devices', true );
            if ( ! empty( $compatible_devices ) && is_array( $compatible_devices ) ) {
                foreach ( $compatible_devices as $device_id ) {
                    $device = get_post( $device_id );
                    if ( $device ) {
                        $search_terms[] = $device->post_title;
                    }
                }
            }
        } elseif ( is_tax( 'tech_repair_issue_type' ) ) {
            // On issue type archive
            $term = get_queried_object();
            if ( $term ) {
                $search_terms[] = $term->name;
            }
        } elseif ( is_singular( 'tech_repair_device' ) ) {
            // On device page
            $search_terms[] = get_the_title();
            
            // Get device category
            $device_cats = get_the_terms( get_the_ID(), 'tech_repair_device_cat' );
            if ( ! empty( $device_cats ) && ! is_wp_error( $device_cats ) ) {
                foreach ( $device_cats as $cat ) {
                    $search_terms[] = $cat->name;
                }
            }
        } elseif ( is_tax( 'tech_repair_device_cat' ) ) {
            // On device category archive
            $term = get_queried_object();
            if ( $term ) {
                $search_terms[] = $term->name;
            }
        }
        
        // If no search terms found, return empty query
        if ( empty( $search_terms ) ) {
            return new WP_Query();
        }
        
        // Prepare search query
        $search_query = implode( ' ', array_unique( $search_terms ) );
        
        // Query arguments
        $args = array(
            'post_type'      => 'product',
            'posts_per_page' => $number,
            'post_status'    => 'publish',
            's'              => $search_query,
            'orderby'        => 'relevance',
            'order'          => 'DESC',
        );
        
        // Add meta query to ensure products are in stock and exclude Tech Repair products
        $args['meta_query'] = array(
            'relation' => 'AND',
            array(
                'key'     => '_stock_status',
                'value'   => 'instock',
                'compare' => '=',
            ),
            array(
                'relation' => 'OR',
                array(
                    'key'     => '_tech_repair_product',
                    'compare' => 'NOT EXISTS',
                ),
                array(
                    'key'     => '_tech_repair_product',
                    'value'   => 'yes',
                    'compare' => '!=',
                ),
            ),
        );
        
        // Return products query
        return new WP_Query( $args );
    }
    
    /**
     * Get random products
     *
     * @param int $number Number of products to display
     * @param string $category Optional product category slug
     * @return WP_Query
     */
    private function get_random_products( $number, $category = '' ) {
        // Query arguments
        $args = array(
            'post_type'      => 'product',
            'posts_per_page' => $number,
            'post_status'    => 'publish',
            'orderby'        => 'rand',
        );
        
        // Add category filter if specified
        if ( ! empty( $category ) ) {
            $args['tax_query'] = array(
                array(
                    'taxonomy' => 'product_cat',
                    'field'    => 'slug',
                    'terms'    => $category,
                ),
            );
        }
        
        // Add meta query to ensure products are in stock and exclude Tech Repair products
        $args['meta_query'] = array(
            'relation' => 'AND',
            array(
                'key'     => '_stock_status',
                'value'   => 'instock',
                'compare' => '=',
            ),
            array(
                'relation' => 'OR',
                array(
                    'key'     => '_tech_repair_product',
                    'compare' => 'NOT EXISTS',
                ),
                array(
                    'key'     => '_tech_repair_product',
                    'value'   => 'yes',
                    'compare' => '!=',
                ),
            ),
        );
        
        // Return products query
        return new WP_Query( $args );
    }
    
    /**
     * Get products by keywords
     *
     * @param int $number Number of products to display
     * @param string $keywords Keywords to search for
     * @param string $category Optional product category slug
     * @return WP_Query
     */
    private function get_products_by_keywords( $number, $keywords, $category = '' ) {
        // If no keywords, return empty query
        if ( empty( $keywords ) ) {
            return new WP_Query();
        }
        
        // Query arguments
        $args = array(
            'post_type'      => 'product',
            'posts_per_page' => $number,
            'post_status'    => 'publish',
            's'              => $keywords,
            'orderby'        => 'relevance',
            'order'          => 'DESC',
        );
        
        // Add category filter if specified
        if ( ! empty( $category ) ) {
            $args['tax_query'] = array(
                array(
                    'taxonomy' => 'product_cat',
                    'field'    => 'slug',
                    'terms'    => $category,
                ),
            );
        }
        
        // Add meta query to ensure products are in stock and exclude Tech Repair products
        $args['meta_query'] = array(
            'relation' => 'AND',
            array(
                'key'     => '_stock_status',
                'value'   => 'instock',
                'compare' => '=',
            ),
            array(
                'relation' => 'OR',
                array(
                    'key'     => '_tech_repair_product',
                    'compare' => 'NOT EXISTS',
                ),
                array(
                    'key'     => '_tech_repair_product',
                    'value'   => 'yes',
                    'compare' => '!=',
                ),
            ),
        );
        
        // Return products query
        return new WP_Query( $args );
    }

    /**
     * Widget settings form
     *
     * @param array $instance Previously saved values from database.
     */
    public function form( $instance ) {
        $title = ! empty( $instance['title'] ) ? $instance['title'] : esc_html__( 'Recommended Products', 'tech-repair-service' );
        $number = ! empty( $instance['number'] ) ? absint( $instance['number'] ) : 3;
        $show_thumbnail = isset( $instance['show_thumbnail'] ) ? (bool) $instance['show_thumbnail'] : true;
        $show_price = isset( $instance['show_price'] ) ? (bool) $instance['show_price'] : true;
        $show_rating = isset( $instance['show_rating'] ) ? (bool) $instance['show_rating'] : true;
        $display_mode = ! empty( $instance['display_mode'] ) ? $instance['display_mode'] : 'relevant';
        $keywords = ! empty( $instance['keywords'] ) ? $instance['keywords'] : '';
        $product_category = ! empty( $instance['product_category'] ) ? $instance['product_category'] : '';
        
        // Get product categories for dropdown
        $product_categories = array();
        if ( taxonomy_exists( 'product_cat' ) ) {
            $product_categories = get_terms( array(
                'taxonomy'   => 'product_cat',
                'hide_empty' => false,
            ) );
        }
        ?>
        <p>
            <label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_html_e( 'Title:', 'tech-repair-service' ); ?></label>
            <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
        </p>
        
        <p>
            <label for="<?php echo esc_attr( $this->get_field_id( 'display_mode' ) ); ?>"><?php esc_html_e( 'Display mode:', 'tech-repair-service' ); ?></label>
            <select class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'display_mode' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'display_mode' ) ); ?>" onchange="techRepairToggleProductOptions(this)">
                <option value="relevant" <?php selected( $display_mode, 'relevant' ); ?>><?php esc_html_e( 'Relevant to current page', 'tech-repair-service' ); ?></option>
                <option value="random" <?php selected( $display_mode, 'random' ); ?>><?php esc_html_e( 'Random products', 'tech-repair-service' ); ?></option>
                <option value="keywords" <?php selected( $display_mode, 'keywords' ); ?>><?php esc_html_e( 'By keywords', 'tech-repair-service' ); ?></option>
            </select>
        </p>
        
        <div class="tech-repair-keywords-field" style="<?php echo $display_mode === 'keywords' ? '' : 'display: none;'; ?>">
            <p>
                <label for="<?php echo esc_attr( $this->get_field_id( 'keywords' ) ); ?>"><?php esc_html_e( 'Keywords:', 'tech-repair-service' ); ?></label>
                <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'keywords' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'keywords' ) ); ?>" type="text" value="<?php echo esc_attr( $keywords ); ?>" placeholder="<?php esc_attr_e( 'e.g. screen protector, charger', 'tech-repair-service' ); ?>">
                <small><?php esc_html_e( 'Enter keywords separated by commas or spaces', 'tech-repair-service' ); ?></small>
            </p>
        </div>
        
        <p>
            <label for="<?php echo esc_attr( $this->get_field_id( 'product_category' ) ); ?>"><?php esc_html_e( 'Product category (optional):', 'tech-repair-service' ); ?></label>
            <select class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'product_category' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'product_category' ) ); ?>">
                <option value=""><?php esc_html_e( '— Select category —', 'tech-repair-service' ); ?></option>
                <?php
                if ( ! empty( $product_categories ) && ! is_wp_error( $product_categories ) ) {
                    foreach ( $product_categories as $category ) {
                        echo '<option value="' . esc_attr( $category->slug ) . '" ' . selected( $product_category, $category->slug, false ) . '>' . esc_html( $category->name ) . '</option>';
                    }
                }
                ?>
            </select>
        </p>
        
        <p>
            <label for="<?php echo esc_attr( $this->get_field_id( 'number' ) ); ?>"><?php esc_html_e( 'Number of products to show:', 'tech-repair-service' ); ?></label>
            <input class="tiny-text" id="<?php echo esc_attr( $this->get_field_id( 'number' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'number' ) ); ?>" type="number" step="1" min="1" value="<?php echo esc_attr( $number ); ?>" size="3">
        </p>
        
        <p>
            <input class="checkbox" type="checkbox" <?php checked( $show_thumbnail ); ?> id="<?php echo esc_attr( $this->get_field_id( 'show_thumbnail' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'show_thumbnail' ) ); ?>">
            <label for="<?php echo esc_attr( $this->get_field_id( 'show_thumbnail' ) ); ?>"><?php esc_html_e( 'Display product thumbnail', 'tech-repair-service' ); ?></label>
        </p>
        
        <p>
            <input class="checkbox" type="checkbox" <?php checked( $show_price ); ?> id="<?php echo esc_attr( $this->get_field_id( 'show_price' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'show_price' ) ); ?>">
            <label for="<?php echo esc_attr( $this->get_field_id( 'show_price' ) ); ?>"><?php esc_html_e( 'Display product price', 'tech-repair-service' ); ?></label>
        </p>
        
        <p>
            <input class="checkbox" type="checkbox" <?php checked( $show_rating ); ?> id="<?php echo esc_attr( $this->get_field_id( 'show_rating' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'show_rating' ) ); ?>">
            <label for="<?php echo esc_attr( $this->get_field_id( 'show_rating' ) ); ?>"><?php esc_html_e( 'Display product rating', 'tech-repair-service' ); ?></label>
        </p>
        
        <script type="text/javascript">
        function techRepairToggleProductOptions(selectEl) {
            var keywordsField = document.querySelector('.tech-repair-keywords-field');
            if (selectEl.value === 'keywords') {
                keywordsField.style.display = 'block';
            } else {
                keywordsField.style.display = 'none';
            }
        }
        </script>
        <?php
    }

    /**
     * Sanitize widget form values as they are saved.
     *
     * @param array $new_instance Values just sent to be saved.
     * @param array $old_instance Previously saved values from database.
     *
     * @return array Updated safe values to be saved.
     */
    public function update( $new_instance, $old_instance ) {
        $instance = array();
        $instance['title'] = ! empty( $new_instance['title'] ) ? sanitize_text_field( $new_instance['title'] ) : '';
        $instance['number'] = ! empty( $new_instance['number'] ) ? absint( $new_instance['number'] ) : 3;
        $instance['show_thumbnail'] = isset( $new_instance['show_thumbnail'] ) ? (bool) $new_instance['show_thumbnail'] : false;
        $instance['show_price'] = isset( $new_instance['show_price'] ) ? (bool) $new_instance['show_price'] : false;
        $instance['show_rating'] = isset( $new_instance['show_rating'] ) ? (bool) $new_instance['show_rating'] : false;
        $instance['display_mode'] = ! empty( $new_instance['display_mode'] ) ? sanitize_text_field( $new_instance['display_mode'] ) : 'relevant';
        $instance['keywords'] = ! empty( $new_instance['keywords'] ) ? sanitize_text_field( $new_instance['keywords'] ) : '';
        $instance['product_category'] = ! empty( $new_instance['product_category'] ) ? sanitize_text_field( $new_instance['product_category'] ) : '';
        
        return $instance;
    }
}
