<?php
class kavehWoo
{

    private $options;

    public function __construct()
    {

        add_filter('woocommerce_product_tabs', array($this, 'renameTabs'), 98);
        add_action('woocommerce_before_main_content', array($this, 'removeBreadcrumbs'));
        add_filter('woocommerce_get_price_html', array($this, 'add_unique_class_to_main_price'), 10, 2);

        $this->options = kaveh_get_options();
        if ($this->options['auto_register_guest_user'] === '1') {
            add_action('woocommerce_thankyou', array($this, 'registerGuests'), 9999);
        }

        add_filter('woocommerce_breadcrumb_defaults', array($this, 'customBreadcrumbs'));
        add_action('customstyleinprsingle', [$this, 'bbloomer_stock_for_variable_products']);

        add_action('woocommerce_before_quantity_input_field', array($this, 'bbloomer_display_quantity_kminustwo'));
        add_action('woocommerce_after_quantity_input_field', array($this, 'bbloomer_display_quantity_kplustwo'));
        if (class_exists('woocommerce')) {
            add_action('wp_footer', array($this, 'bbloomer_add_cart_quantity_kplustwo_kminustwo'));
            add_action('wp_footer', array($this, 'kaveh_single_quantityinput'));
            add_action('woocommerce_variable_add_to_cart', array($this,'bbloomer_update_price_with_variation_price'));
        }
        if ($this->options['fixed_checkout_submit'] !== '0') {
            add_action('wp_footer', array($this, 'fixed_checkout_button'));
        }
        add_filter('woocommerce_ship_to_different_address_checked', '__return_false');

        add_action('wp_enqueue_scripts', [$this, 'bbloomer_disable_woocommerce_cart_fragments'], 11);
        add_action('pre_get_posts', [$this, 'filter_woocommerce_out_of_stock_products']);

        add_filter('woocommerce_currency_symbol',  [$this, 'custom_currency_symbol'], 10, 2);

        add_filter('woocommerce_variable_price_html', [$this, 'custom_variable_price_format'], 10, 2);
        
        // Handle AJAX requests properly
        add_action('wp_ajax_nopriv_woocommerce_get_refreshed_fragments', [$this, 'handle_ajax_currency'], 1);
        add_action('wp_ajax_woocommerce_get_refreshed_fragments', [$this, 'handle_ajax_currency'], 1);
        if ($this->options['move_outofstock_to_end'] === '1') {
            add_filter('posts_clauses', [$this, 'order_by_stock_status'], 2000);
        }
        
        // Add registration number field to checkout if enabled
        if (isset($this->options['kaveh_enable_registration_number_field']) && $this->options['kaveh_enable_registration_number_field'] === '1') {
            add_filter('woocommerce_checkout_fields', [$this, 'add_registration_number_field']);
            add_action('woocommerce_checkout_process', [$this, 'validate_registration_number_field']);
            add_action('woocommerce_checkout_update_order_meta', [$this, 'save_registration_number_field']);
            add_action('woocommerce_admin_order_data_after_billing_address', [$this, 'display_registration_number_in_admin']);
            add_action('woocommerce_order_details_after_order_table', [$this, 'display_registration_number_in_customer_account']);
        }
    }



    public function bbloomer_update_price_with_variation_price()
    {
        if (!is_product()) {
            return;
        }
        global $product;
        $price = $product->get_price_html();
        
        // Escape the price HTML for JavaScript to handle SVG currency symbols properly
        $escaped_price = addslashes($price);
        
        wc_enqueue_js("     
      $(document).on('show_variation', 'form.cart', function( event, variation ) {   
         if(variation.price_html) {
             // Clean and update the price HTML properly
             var priceHtml = variation.price_html;
             $('.main-product-price').html(priceHtml);
         }
         $('.woocommerce-variation-price').hide();
      });
      $(document).on('hide_variation', 'form.cart', function( event, variation ) {   
         $('.main-product-price').html('" . $escaped_price . "');
      });
   ");
    }


    public function order_by_stock_status($posts_clauses)
    {
        global $wpdb;

        // Check if we're on any product archive page
        $is_product_archive = is_woocommerce() && (
            is_shop() || 
            is_product_category() || 
            is_product_tag() || 
            is_tax('brands') || 
            (is_tax() && get_queried_object() && get_queried_object()->taxonomy && 
             (strpos(get_queried_object()->taxonomy, 'pa_') === 0 || 
              in_array(get_queried_object()->taxonomy, ['product_cat', 'product_tag', 'brands'])))
        );

        if ($is_product_archive) {
            $posts_clauses['join'] .= " INNER JOIN $wpdb->postmeta istockstatus ON ($wpdb->posts.ID = istockstatus.post_id) ";
            $posts_clauses['orderby'] = " istockstatus.meta_value ASC, " . $posts_clauses['orderby'];
            $posts_clauses['where'] = " AND istockstatus.meta_key = '_stock_status' AND istockstatus.meta_value <> '' " . $posts_clauses['where'];
        }
        return $posts_clauses;
    }


    public function custom_currency_symbol($currency_symbol, $currency)
    {
        if ($currency === 'IRT') {
            $options = kaveh_get_options();
            $currency_symbol_switcher = $options['currency_new_svg'];
            $pricecolor = $options['pricecolor'];

            if ($currency_symbol_switcher === '1') {
                // Check if we're in admin area - use simple text symbol instead of SVG
                if (is_admin()) {
                    $currency_symbol = 'تومان';
                } else {
                    $currency_symbol = '<svg width="19.5" height="18" viewBox="0 0 13 12" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path
                                            d="M2.32002 6.11782C2.63548 5.96391 2.87208 5.81 3.10867 5.57913C3.2664 5.34826 3.42413 5.11739 3.58186 4.88652C3.66073 4.57869 3.73959 4.27087 3.73959 3.96304H11.2318C11.705 3.96304 12.0993 3.80913 12.4147 3.57826C12.6513 3.27043 12.8091 2.88565 12.8091 2.34696V0.5H11.7838V2.27C11.7838 2.65478 11.5472 2.88565 11.1529 2.88565H3.73959V2.50087C3.73959 2.11609 3.66073 1.88522 3.58186 1.57739C3.58186 1.34652 3.42413 1.11565 3.2664 0.961739C3.10867 0.807826 2.95094 0.730869 2.79321 0.653913C2.55662 0.576956 2.32002 0.5 2.16229 0.5C1.84683 0.5 1.61024 0.576956 1.37364 0.653913C1.21591 0.807826 0.979316 0.884782 0.900451 1.11565C0.742721 1.26956 0.584991 1.42348 0.584991 1.65435C0.506126 1.88522 0.427261 2.11609 0.427261 2.34696C0.427261 2.57782 0.427261 2.80869 0.506126 3.03956C0.584991 3.27043 0.663856 3.42435 0.742721 3.57826C0.900451 3.65521 1.05818 3.80913 1.29478 3.88608C1.53137 3.96304 1.76797 3.96304 2.16229 3.96304H2.79321C2.79321 4.11695 2.71435 4.27087 2.71435 4.42478C2.63548 4.57869 2.47775 4.7326 2.39889 4.88652C2.32002 4.96347 2.16229 5.04043 1.9257 5.11739C1.76797 5.19434 1.53137 5.2713 1.29478 5.2713H0.269531V6.34869H1.29478C1.6891 6.27173 2.00456 6.19478 2.32002 6.11782ZM2.16229 2.88565C1.84683 2.88565 1.6891 2.88565 1.53137 2.73174C1.45251 2.65478 1.37364 2.50087 1.37364 2.27C1.37364 2.03913 1.45251 1.80826 1.53137 1.7313C1.6891 1.65435 1.84683 1.57739 2.08343 1.57739C2.32002 1.57739 2.47775 1.65435 2.63548 1.80826C2.79321 1.96217 2.79321 2.19304 2.79321 2.50087V2.96261H2.16229V2.88565Z"
                                            fill="' . $pricecolor . '"></path>
                                        <path d="M10.4422 0.5H7.44531V1.42348H10.4422V0.5Z" fill="' . $pricecolor . '"></path>
                                        <path
                                            d="M12.7298 8.50383C12.6509 8.27296 12.5721 8.11905 12.4143 7.96514C12.2566 7.81122 12.0989 7.65731 11.8623 7.58035C11.7046 7.5034 11.468 7.42644 11.2314 7.42644C10.9948 7.42644 10.7582 7.5034 10.5216 7.58035C10.285 7.65731 10.1273 7.81122 9.96953 7.96514C9.8118 8.11905 9.73293 8.27296 9.65407 8.50383C9.5752 8.7347 9.5752 8.96557 9.5752 9.19644V9.42731C9.5752 9.65818 9.49634 9.73513 9.41747 9.88905C9.25974 9.966 9.10201 10.043 8.86542 10.043H8.54996C8.39223 10.043 8.2345 9.966 8.15563 9.88905C8.07677 9.73513 7.9979 9.58122 7.9979 9.42731V5.7334H6.97266V9.58122C6.97266 9.88905 6.97266 10.1199 7.05152 10.2738C7.13039 10.4277 7.20925 10.5817 7.36698 10.7356C7.52471 10.8125 7.60358 10.9664 7.84017 10.9664C7.9979 11.0434 8.15563 11.0434 8.39223 11.0434H8.94428C9.10201 11.0434 9.33861 10.9664 9.49634 10.8895C9.65407 10.8125 9.89066 10.6586 9.96953 10.4277C10.1273 10.6586 10.285 10.8125 10.5216 10.8895C10.7582 10.9664 10.9948 11.0434 11.3102 11.0434C11.7834 11.0434 12.2566 10.8895 12.4932 10.5817C12.8087 10.2738 12.9664 9.81209 12.9664 9.2734C12.8875 8.96557 12.8087 8.7347 12.7298 8.50383ZM11.2314 9.966C10.9948 9.966 10.837 9.88905 10.7582 9.81209C10.5216 9.65818 10.5216 9.50427 10.5216 9.2734C10.5216 9.04253 10.6004 8.88861 10.6793 8.7347C10.7582 8.58079 10.9948 8.50383 11.2314 8.50383C11.468 8.50383 11.7046 8.58079 11.7834 8.7347C11.8623 8.88861 11.9412 9.04253 11.9412 9.2734C11.8623 9.73513 11.6257 9.966 11.2314 9.966Z"
                                            fill="' . $pricecolor . '"></path>
                                        <path
                                            d="M4.92256 8.50364C4.92256 8.73451 4.92256 8.88842 4.8437 9.11929C4.76484 9.2732 4.68597 9.42712 4.60711 9.58103C4.44938 9.73494 4.29165 9.8119 4.13392 9.88886C3.97619 9.96581 3.73959 10.0428 3.42413 10.0428H2.71435C2.47775 10.0428 2.24116 10.0428 2.00456 9.96581C1.84683 9.8119 1.6891 9.73494 1.61024 9.58103C1.53137 9.42712 1.37364 9.2732 1.37364 9.11929C1.29478 8.96538 1.29478 8.73451 1.29478 8.50364V7.65712H0.269531V8.5806C0.269531 9.35016 0.506126 9.96581 0.900451 10.4276C1.29478 10.8893 1.84683 11.1202 2.63548 11.1202H3.42413C3.81846 11.1202 4.13392 11.0432 4.44938 10.8893C4.76484 10.7354 5.00143 10.5815 5.23803 10.3506C5.47462 10.1197 5.63235 9.8119 5.71122 9.50407C5.79008 9.19625 5.86894 8.88842 5.86894 8.50364V5.73321L4.8437 5.65625L4.92256 8.50364Z"
                                            fill="' . $pricecolor . '"></path>
                                        <path d="M3.73962 7.42578H2.55664V8.50317H3.73962V7.42578Z" fill="' . $pricecolor . '"></path>
                                    </svg>';
                }
            }
        }
        return $currency_symbol;
    }


    public function filter_woocommerce_out_of_stock_products($query)
    {
        if (!class_exists('woocommerce')) {
            return;
        }
        if ($query->is_main_query() && is_woocommerce()) {

            if ($this->options['hide_outofstock_products'] === '1') {
                $query->set('meta_query', array(
                    array(
                        'key' => '_stock_status',
                        'value' => 'outofstock',
                        'compare' => '!='
                    )
                ));
            }
        }
    }


    public function add_unique_class_to_main_price($price, $product)
    {
        if (is_product() && $product->is_type('variable')) {
            $price = '<span class="main-product-price">' . $price . '</span>';
        }
        return $price;
    }



    public function fixed_checkout_button()
    {
        if (!class_exists('woocommerce')) {
            return;
        }
        if (is_wc_endpoint_url('order-received')) {
            return;
        }

        if (class_exists('woocommerce') && wp_is_mobile()):
            if (is_checkout()):
?>
                <button class="proccedk" onclick="click_checkout()"><?php esc_html_e('Pay and Complete Order', 'kavehTheme'); ?></button>
                <script>
                    jQuery(document).ready(function($) {
                        jQuery(document).on('click', '.proccedk', function(e) {
                            jQuery('button#place_order').click();
                        })
                    })
                </script>
                <style>
                    .wc-proceed-to-checkout {
                        position: fixed !important;
                        bottom: 2px !important;
                        width: 94% !important;
                        z-index: 99999 !important;
                        margin-bottom: 0 !important;
                        padding-bottom: 0 !important;
                    }

                    .nav-bottom,
                    button#place_order {
                        display: none !important;
                    }
                </style>
            <?php
            endif;
            if (class_exists('woocommerce') && is_cart()) {
            ?>
                <style>
                    .wc-proceed-to-checkout {
                        position: fixed !important;
                        bottom: 2px !important;
                        width: 94% !important;
                        z-index: 99999 !important;
                        margin-bottom: 0 !important;
                        padding-bottom: 0 !important;
                    }

                    .nav-bottom,
                    button#place_order {
                        display: none !important;
                    }
                </style>
            <?php
            }
        endif;
    }



    public function bbloomer_disable_woocommerce_cart_fragments()
    {
        wp_dequeue_script('wc-cart-fragments');
    }


    public function kaveh_single_quantityinput()
    {

        if (!is_product()) {
            return;
        }

        global $product;
        if ($product->get_stock_quantity() === 1) {
            ?>
            <style>
                .detailfouradd .quantity::before {
                    display: none !important;
                }

                .detsimple form.cart::before {
                    display: none !important;
                }
            </style>
        <?php
        }
    }

    public function bbloomer_display_quantity_kminustwo()
    {
        if (class_exists('woocommerce') && !is_cart())
            return;
        echo '<button type="button" class="kminustwo" >-</button>';
    }

    public function bbloomer_display_quantity_kplustwo()
    {
        if (class_exists('woocommerce') && !is_cart())
            return;
        echo '<button type="button" class="kplustwo" >+</button>';
    }

    public function bbloomer_add_cart_quantity_kplustwo_kminustwo()
    {

        if (!class_exists('woocommerce')) {
            return;
        }
        if (!is_cart()) {
            return;
        }
        wc_enqueue_js("
            jQuery(document).on('click', 'button.kplustwo, button.kminustwo', function(emy) {
                document.querySelector('button.button[name=\"update_cart\"]').removeAttribute('disabled');
                var qty = jQuery( this ).closest( '.quantity' ).find( 'input[type=\"number\"]' );
                var val   = parseFloat(qty.val());
                var max = parseFloat(qty.attr( 'max' ));
                var min = parseFloat(qty.attr( 'min' ));
                var step = parseFloat(qty.attr( 'step' ));
                if ( jQuery( this ).is( '.kplustwo' ) ) {
                    if ( max && ( max <= val ) ) {
                    qty.val( max );
                    } else {
                    qty.val( val + step );
                    }
                } else {
                    if ( min && ( min >= val ) ) {
                    qty.val( min );
                    } else if ( val > 1 ) {
                    qty.val( val - step );
                    }
                }
            });
        ");
    }

    public function bbloomer_stock_for_variable_products()
    {
        global $product;
        $stock = $product->get_stock_status();
        $price = $product->get_price();
        if ($stock === 'outofstock' || $stock === 'onbackorder' || empty($price)) {
        ?>
            <style>
                .addtocart_footer {
                    display: none !important;
                }

                .detail-product .summary .price {
                    position: static;
                }

                .detail-product .summary .price::before {
                    content: "" !important;
                }
            </style>
<?php
        }
    }

    public function renameTabs($tabs)
    {
        $tabs['additional_information']['title'] = __('Specifications', 'kavehTheme');
        return $tabs;
    }

    public function removeBreadcrumbs()
    {
        remove_action('woocommerce_before_main_content', 'woocommerce_breadcrumb', 20, 0);
    }


    public function registerGuests($order_id)
    {
        if (is_user_logged_in()) {
            return;
        }
        // Get order info and get customer email for registering
        $order = wc_get_order($order_id);
        $email = $order->get_billing_email();
        $pass = wp_generate_password();
        $phone = $order->get_billing_phone();
        $user_phone = get_users(array('meta_key' => 'billing_phone', 'meta_value' => $phone));


        // Check if email is optional and phone is provided
        if (empty($email) && !empty($phone)) {
            // Create a unique username based on the phone number
            $username = 'guest_' . sanitize_user($phone);

            // Check if username exists
            if (!$user_phone) {
                $customer_id = wc_create_new_customer(
                    $username . '@test.com',
                    $phone,
                    $pass,
                    array(
                        'first_name' => $order->get_billing_first_name(),
                        'last_name' => $order->get_billing_last_name(),
                    )
                );
                if (is_wp_error($customer_id)) {
                    throw new Exception($customer_id->get_error_message());
                }

                // Auto set cookie for new user
                wc_update_new_customer_past_orders($customer_id);
                wc_set_customer_auth_cookie($customer_id);
                update_user_meta($customer_id, 'billing_phone', $phone);
                $order->set_customer_id($customer_id);
                $order->save();
            } else {
                // Auto set cookie for existing user
                $args = array(
                    'meta_key' => 'billing_phone',
                    'meta_value' => $phone,
                );
                $user_query = new WP_User_Query($args);
                $users = $user_query->get_results();
                $user = $users[0];

                wc_update_new_customer_past_orders($user->ID);
                wc_set_customer_auth_cookie($user->ID);
                update_user_meta($user->ID, 'billing_phone', $phone);
                $order->set_customer_id($user->ID);
                $order->save();
            }
        } elseif (!empty($email)) {
            if (!email_exists($email) && !username_exists($email)) {
                $customer_id = wc_create_new_customer(
                    $email,
                    '',
                    $pass,
                    array(
                        'first_name' => $order->get_billing_first_name(),
                        'last_name' => $order->get_billing_last_name(),
                    )
                );
                if (is_wp_error($customer_id)) {
                    throw new Exception($customer_id->get_error_message());
                }

                // Auto set cookie for new user
                wc_update_new_customer_past_orders($customer_id);
                wc_set_customer_auth_cookie($customer_id);
                update_user_meta($customer_id, 'billing_phone', $phone);
                $order->set_customer_id($customer_id);
                $order->save();
            } else {
                // Auto set cookie for existing user
                $user = get_user_by('email', $email);
                wc_update_new_customer_past_orders($user->ID);
                update_user_meta($user->ID, 'billing_phone', $phone);
                $order->set_customer_id($user->ID);
                $order->save();
            }
        }
    }

    public function customBreadcrumbs()
    {
        return array(
            'delimiter' => '&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;',
            'wrap_before' => '<ul class="breadcrumb" itemprop="breadcrumb">',
            'wrap_after' => '</ul>',
            'before' => '',
            'after' => '',
            'home' => _x('Home', 'breadcrumb', 'kavehTheme'),
        );
    }

    public static function showofferpercentage($product)
    {
        if (!$product->is_on_sale()) {
            return;
        }

        if ($product->is_type('simple')) {
            $max_percentage = (($product->get_regular_price() - $product->get_sale_price()) / $product->get_regular_price()) * 100;
        } elseif ($product->is_type('variable')) {
            $max_percentage = 0;

            foreach ($product->get_children() as $child_id) {
                $variation = wc_get_product($child_id);
                $price = $variation->get_regular_price();
                $sale = $variation->get_sale_price();
                $percentage = 0; // Initialize the variable

                if ($price != 0 && !empty($sale)) {
                    $percentage = ($price - $sale) / $price * 100;
                }

                if ($percentage > $max_percentage) {
                    $max_percentage = $percentage;
                }
            }
        }

        if ($max_percentage > 0) {
            return "%" . round($max_percentage);
        }

        return false;
    }



    public static function lowest_and_highest_variable_set_price($product)
    {

        $highest_price = 0;
        $highest_price_variation = null;
        $lowest_price = PHP_INT_MAX;
        $lowest_price_variation = null;
        foreach ($product->get_children() as $child_id) {
            $variation = wc_get_product($child_id);
            $normal_price = $variation->get_regular_price();
            $sale_price = $variation->get_sale_price();

            if ($normal_price > $highest_price) {
                if (!empty($sale_price)) {
                    $highest_price = $normal_price;
                    $highest_price_variation = $variation;
                }
            }
            if ($normal_price < $lowest_price) {
                if (!empty($sale_price)) {
                    $lowest_price = $normal_price;
                    $lowest_price_variation = $variation;
                }
            }
        }
        $prices = [
            'lowest' => [
                'normal_price' => $lowest_price_variation->get_regular_price(),
                'sale_price' => $lowest_price_variation->get_sale_price(),
            ],
            'highest' => [
                'normal_price' => $highest_price_variation->get_regular_price(),
                'sale_price' => $highest_price_variation->get_sale_price(),
            ],
        ];
        return $prices;
    }


    /**
     * Custom variable product price format
     */
    public function custom_variable_price_format($price, $product)
    {
        if (!$product->is_type('variable')) {
            return $price;
        }

        // Get the price format option
        $price_format = isset($this->options['variable_product_price_format']) ?
            $this->options['variable_product_price_format'] : 'range';

        $prices = $product->get_variation_prices(true);

        if (empty($prices['price'])) {
            return $price;
        }

        $min_price = current($prices['price']);
        $max_price = end($prices['price']);

        switch ($price_format) {
            case 'lowest':
                // Show "From [lowest price]"
                $price = wc_price($min_price);
                break;

            case 'highest':
                // Show "Up to [highest price]"
                $price = wc_price($max_price);
                break;

            case 'range':
            default:
                // Show price range (default WooCommerce behavior)
                if ($min_price !== $max_price) {
                    $price = wc_format_price_range($min_price, $max_price);
                } else {
                    $price = wc_price($min_price);
                }
                break;
        }

        return $price;
    }

    /**
     * Handle AJAX currency symbol properly
     */
    public function handle_ajax_currency()
    {
        // For AJAX requests, we want to ensure SVG currency symbols work properly
        // This is called before the AJAX response is generated
        if (wp_doing_ajax()) {
            // No special handling needed as our custom_currency_symbol method
            // already handles admin vs frontend properly
        }
    }

    /**
     * Add registration number field to checkout
     */
    public function add_registration_number_field($fields)
    {
        $fields['billing']['billing_registration_number'] = array(
            'label' => __('کد ملی / شناسه ملی', 'kavehTheme'),
            'placeholder' => __('کد ملی / شناسه ملی', 'kavehTheme'),
            'required' => false,
            'class' => array('form-row-wide'),
            'clear' => true,
            'priority' => 25
        );
        return $fields;
    }

    /**
     * Validate registration number field
     */
    public function validate_registration_number_field()
    {
        // Optional: Add validation logic here if needed
        // For now, we'll keep it simple and not require validation
    }

    /**
     * Save registration number field to order meta
     */
    public function save_registration_number_field($order_id)
    {
        if (!empty($_POST['billing_registration_number'])) {
            update_post_meta($order_id, 'billing_registration_number', sanitize_text_field($_POST['billing_registration_number']));
        }
    }

    /**
     * Display registration number in admin order details
     */
    public function display_registration_number_in_admin($order)
    {
        $registration_number = get_post_meta($order->get_id(), 'billing_registration_number', true);
        if (!empty($registration_number)) {
            echo '<p><strong>' . __('کد ملی / شناسه ملی:', 'kavehTheme') . '</strong> ' . esc_html($registration_number) . '</p>';
        }
    }

    /**
     * Display registration number in customer account order details
     */
    public function display_registration_number_in_customer_account($order)
    {
        $registration_number = get_post_meta($order->get_id(), 'billing_registration_number', true);
        if (!empty($registration_number)) {
            echo '<h2 class="woocommerce-order-details__title">' . __('کد ملی / شناسه ملی', 'kavehTheme') . '</h2>';
            echo '<p>' . esc_html($registration_number) . '</p>';
        }
    }
}
