<?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_action('woocommerce_variable_add_to_cart', array($this, 'updatePriceWithVariationPrice'));

        $this->options = get_option('kaveh_frame');
        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'));
        add_action('wp_footer', array($this, 'bbloomer_add_cart_quantity_kplustwo_kminustwo'));
        add_action('wp_footer', array($this, 'kaveh_single_quantityinput'));
        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_filter('woocommerce_variable_sale_price_html',  [$this,'custom_variable_price_format'], 10, 2);
        add_filter('woocommerce_variable_price_html',  [$this,'custom_variable_price_format'], 10, 2);
    }



    public function custom_variable_price_format($price, $product) {
        if (wp_is_mobile() && is_product()) {
            $prices = $product->get_variation_prices(true);

            // Get all variation prices
            $regular_prices = $prices['regular_price'];

            if (!empty($regular_prices)) {
                $min_regular_price = min($regular_prices);
                $price = wc_price($min_regular_price) . ' ' . $product->get_price_suffix();
            }
        }
        return $price;
    }



    public function fixed_checkout_button()
    {
        if (class_exists('woocommerce') && wp_is_mobile()):
            if (is_checkout()):
                ?>
                <button class="proccedk" onclick="click_checkout()">پرداخت و تکمیل سفارش</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(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 (!is_cart())
            return;
        echo '<button type="button" class="kminustwo" >-</button>';
    }

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

    public function bbloomer_add_cart_quantity_kplustwo_kminustwo()
    {
        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'] = __('مشخصات');
        return $tabs;
    }

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

    public function updatePriceWithVariationPrice()
    {
        global $product;
        $price = $product->get_price_html();

        wc_enqueue_js("
            jQuery(document).on('found_variation', 'form.cart', function(event, variation) {
                if (variation.price_html) jQuery('.price').html(variation.price_html);
                jQuery('.woocommerce-variation-price').hide();
            });
            jQuery(document).on('hide_variation', 'form.cart', function(event, variation) {
                jQuery('.price').html('" . $price . "');
            });
        ");
    }

    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', 'woocommerce'),
        );
    }

    public static function showofferpercentage($product)
    {
        $stocka = $product->get_stock_status();
        if ("instock" === $stocka) {
            if ($product->is_on_sale()) {
                if ($product->is_type('simple')) {
                    $max_percentage = (((float) $product->get_regular_price() - (float) $product->get_sale_price()) / (float) $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 = (float) $variation->get_regular_price();
                        $sale = (float) $variation->get_sale_price();
                        if ($price != 0 && !empty($sale))
                            $percentage = ($price - $sale) / $price * 100;
                        if ($percentage > $max_percentage) {
                            $max_percentage = $percentage;
                        }
                    }
                }

                if ($max_percentage > 0) {
                    echo round($max_percentage) . '%';
                }
            }
        }
    }
}