<?php
class kavehajaxHandler
{
    private $options;

    public function __construct()
    {
        $this->options = kaveh_get_options();
        add_action('wp_enqueue_scripts', array($this, 'enqueueAjaxAssets'));
        add_action('save_post_product', array($this, 'clear_price_cache'));
        add_action('woocommerce_product_object_updated_props', array($this, 'clear_price_cache'));
    }

    public function clear_price_cache()
    {
        delete_transient('kaveh_price_range');
        delete_transient('kaveh_current_term_price_range');
    }

    private function get_price_range()
    {
        // Check if we're on a taxonomy page
        if (is_tax('product_cat') || is_tax('brand')) {
            $current_term = get_queried_object();
            $transient_key = 'kaveh_current_term_price_range_' . $current_term->term_id;
            
            if (false === ($price_range = get_transient($transient_key))) {
                $args = array(
                    'status' => 'publish',
                    'limit' => -1,
                    'tax_query' => array(
                        array(
                            'taxonomy' => $current_term->taxonomy,
                            'field' => 'term_id',
                            'terms' => $current_term->term_id,
                        )
                    )
                );
                
                $price_range = $this->calculate_price_range($args);
                set_transient($transient_key, $price_range, 12 * HOUR_IN_SECONDS);
            }
        } else {
            // For general cases
            if (false === ($price_range = get_transient('kaveh_price_range'))) {
                $args = array(
                    'status' => 'publish',
                    'limit' => 100, // Safety limit
                    'orderby' => 'price',
                    'order' => 'ASC'
                );
                
                $price_range = $this->calculate_price_range($args);
                set_transient('kaveh_price_range', $price_range, 12 * HOUR_IN_SECONDS);
            }
        }

        return $price_range;
    }

    private function calculate_price_range($args)
    {
        // Remove limit and order to get all products
        unset($args['limit']);
        unset($args['order']);
        unset($args['orderby']);
        
        $products = wc_get_products($args);
        
        if (empty($products)) {
            return array('min' => 1, 'max' => 1);
        }
        
        $prices = array();
        foreach ($products as $product) {
            $price = $product->get_price();
            if ($price && $price > 0) {
                $prices[] = floatval($price);
            }
        }
        
        if (empty($prices)) {
            return array('min' => 1, 'max' => 1);
        }
        
        $min_price = min($prices);
        $max_price = max($prices);
        
        // Add 10% buffer
        $result = array(
            'min' => $min_price > 0 ? $min_price - ($min_price * 0.1) : 1,
            'max' => $max_price > 0 ? $max_price + ($max_price * 0.1) : 1
        );
        
        
        return $result;
    }

    public function enqueueAjaxAssets()
    {
        // Only load these assets where needed
        if (!class_exists('woocommerce')) {
            return;
        }

        // Clear cache to get fresh price range
        $this->clear_price_cache();
        
        // Get price range (cached)
        $price_range = $this->get_price_range();
        $highest_price = $price_range['max'];
        $lowest_price = $price_range['min'];
        
      

        // Prepare WooCommerce data
        $woocommerce_cart_redirect_after_add = get_option('woocommerce_cart_redirect_after_add');
        $cart_url = wc_get_cart_url();
        $woo_currency = get_woocommerce_currency_symbol();

        // Prepare font data
        $fontkaveh = $this->options['kaveh_typoselect'];
        $rtl_fonts = array(
            'value-1' => 'kavehirsans.css',
            'value-2' => 'kavehiryekan.css',
            'value-3' => 'kavehyekanbakh.css',
            'value-4' => 'kavehdana.css',
            'value-5' => 'kavehmoraba.css',
            'value-6' => 'kavehabr.css',
            'value-7' => 'kavehdoran.css',
            'value-8' => 'kavehanjoman.css',
            'value-9' => 'kavehpeyda.css',
        );
        $fontlocalize = array($rtl_fonts[$fontkaveh]);

        // Main AJAX script (always loaded)
        wp_enqueue_script('kaveh-ajax-method', KAVEH_TEMPLATE_URI . '/inc/kaveh-ajax-method/kaveh-ajax-method.js', array('jquery'), null, true);
        wp_localize_script('kaveh-ajax-method', 'kfont', $fontlocalize);
        

        $shop_data = array(
            'ksiteurl' => admin_url('admin-ajax.php'),
            'highestPrice' => $highest_price,
            'lowestPrice' => $lowest_price,
            'ajaxnoinsingle' => $this->options['ajaxnosingle'],
            'opencartonaddtocart' => $this->options['opencartonaddtocart'],
            'woocommerce_cart_redirect_after_add' => $woocommerce_cart_redirect_after_add,
            'cart_url' => $cart_url,
            'search_error' => esc_html__('Search error, please try again', 'kavehTheme'),
            'nothing_found' => esc_html__('Nothing found', 'kavehTheme'),
            'in_category' => esc_html__('in category', 'kavehTheme'),
            'view_all' => esc_html__('View All', 'kavehTheme'),
            'view_category' => esc_html__('View', 'kavehTheme'),
            'product_added_to_cart' => esc_html__('Product successfully added to cart', 'kavehTheme'),
            'filter_error' => esc_html__('An error occurred while filtering products.', 'kavehTheme'),
            'invalid_response' => esc_html__('Invalid response from server.', 'kavehTheme'),
            'shop_filter_nonce' => wp_create_nonce('kaveh_shop_filter_nonce'),
        );

        wp_localize_script('kaveh-ajax-method', 'kavehShopData', $shop_data);

            wp_enqueue_script('kaveh-ajax-shop-method', KAVEH_TEMPLATE_URI . '/inc/kaveh-ajax-method/kaveh-ajax-shop-method.js', array('jquery'), null, true);
            wp_localize_script('kaveh-ajax-shop-method', 'kavehShopData', array_merge($shop_data, [
                'woo_currency' => $woo_currency,
                'currency_code' => get_woocommerce_currency(),
            ]));
            wp_localize_script('kaveh-ajax-shop-method', 'kfont', $fontlocalize);

        // Login scripts (only for non-logged in users)
        if (!is_user_logged_in()) {
            wp_enqueue_script('kaveh-login-ajax', KAVEH_TEMPLATE_URI . '/inc/kaveh-ajax-method/kaveh-login-ajax.js', array('jquery'), null, true);
            wp_localize_script('kaveh-login-ajax', 'ksiteurl', [
                'ajax_url' => admin_url('admin-ajax.php'),
                'contact_support' => esc_html__('A problem has occurred, contact support', 'kavehTheme'),
                'login_success_wait' => esc_html__('Successfully logged in, please wait...', 'kavehTheme'),
                'login_success' => esc_html__('Successfully logged in', 'kavehTheme'),
                'processing_request' => esc_html__('Processing your request', 'kavehTheme'),
                'please_wait' => esc_html__('Please wait', 'kavehTheme'),
                'wrong_verification_code' => esc_html__('Verification code is incorrect, try again', 'kavehTheme'),
                'wrong_credentials' => esc_html__('The entered credentials are incorrect, try again', 'kavehTheme'),
                'enter_verification_code' => esc_html__('Enter verification code', 'kavehTheme'),
                'back_and_edit' => esc_html__('Back and edit', 'kavehTheme'),
                'time_remaining' => esc_html__('Time remaining', 'kavehTheme'),
                'seconds' => esc_html__('seconds', 'kavehTheme'),
                'resend_sms' => esc_html__('Resend SMS', 'kavehTheme'),
                'first_name' => esc_html__('First name', 'kavehTheme'),
                'first_name_english' => esc_html__('First name (English)', 'kavehTheme'),
                'last_name' => esc_html__('Last name', 'kavehTheme'),
                'last_name_english' => esc_html__('Last name (English)', 'kavehTheme'),
                'password' => esc_html__('Password', 'kavehTheme'),
            'password_reset_sent' => esc_html__('Password reset link has been emailed to you', 'kavehTheme'),
            'email_not_found' => esc_html__('Such an email does not exist, please register first', 'kavehTheme'),
            'phone_not_found' => esc_html__('Such a number does not exist, please register first', 'kavehTheme'),
            'password_changed_success' => esc_html__('Your password changed successfully', 'kavehTheme'),
            'enter_new_password' => esc_html__('Enter new password', 'kavehTheme'),
            'valid_mobile_email' => esc_html__('Valid mobile or email', 'kavehTheme'),
            'password_recovery' => esc_html__('Password recovery', 'kavehTheme'),
                'submit_text' => esc_html__('Submit', 'kavehTheme'),
                'complete_registration' => esc_html__('Complete registration', 'kavehTheme'),
            ]);
            wp_localize_script('kaveh-login-ajax', 'kfont', $fontlocalize);
            wp_localize_script('kaveh-login-ajax', 'kinputslatin', $this->options['kaveh_login_latin_fields']);
            wp_localize_script('kaveh-login-ajax', 'kbksms', $this->options['kaveh_login_switchtobackup']);
            wp_localize_script('kaveh-login-ajax', 'kbksmstime', $this->options['kaveh_login_send_again']);
        }
    }
}