<?php

/**
 * Plugin Name: Bulk Wholsale Dynamic Pricing Buttons for WooCommerce
 * Description: Adds WooCommerce bulk and wholesale dynamic pricing per quantity.
 * Plugin URI: https://wpsaad.com/bulk-wholsale-dynamic-pricing-buttons-for-woocommerce/
 * Version: 1.1.0
 * Author: WPSAAD
 * Author URI: https://wpsaad.com/
 * License: GPLv2 or later
 * Requires Plugins: woocommerce
 * Text Domain: bulk-wholsale-dynamic-pricing-buttons-for-woocommerce
 * Domain Path: /languages
 */
// Load plugin text domain
function bwdpbfw_load_textdomain() {
    load_plugin_textdomain( 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
}

add_action( 'init', 'bwdpbfw_load_textdomain' );
defined( 'ABSPATH' ) or die;
if ( function_exists( 'bwdpbfw_fs' ) ) {
    bwdpbfw_fs()->set_basename( false, __FILE__ );
} else {
    if ( !function_exists( 'bwdpbfw_fs' ) ) {
        // Create a helper function for easy SDK access.
        function bwdpbfw_fs() {
            global $bwdpbfw_fs;
            if ( !isset( $bwdpbfw_fs ) ) {
                // Include Freemius SDK.
                require_once dirname( __FILE__ ) . '/vendor/freemius/start.php';
                $bwdpbfw_fs = fs_dynamic_init( array(
                    'id'               => '18092',
                    'slug'             => 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce',
                    'type'             => 'plugin',
                    'navigation'       => 'tabs',
                    'public_key'       => 'pk_5f9fcb4a137594266265fb594fa74',
                    'is_premium'       => false,
                    'is_org_compliant' => true,
                    'has_addons'       => false,
                    'has_paid_plans'   => true,
                    'menu'             => array(
                        'slug' => 'bwdpbwc_options',
                    ),
                    'is_live'          => true,
                ) );
            }
            return $bwdpbfw_fs;
        }

        // Init Freemius.
        bwdpbfw_fs();
        // Signal that SDK was initiated.
        do_action( 'bwdpbfw_fs_loaded' );
    }
    // Load Composer autoload
    require_once plugin_dir_path( __FILE__ ) . 'vendor/autoload.php';
    // Enqueue styles and scripts
    function bwdpbwc_enqueue_scripts() {
        if ( is_product() || is_cart() || is_checkout() ) {
            wp_enqueue_script(
                'bwdpbwc-script',
                plugin_dir_url( __FILE__ ) . 'assets/front_script.js',
                array('jquery'),
                '1.5.0' . wp_rand(),
                [
                    'strategy' => 'defer',
                ],
                true
            );
            wp_enqueue_style(
                'bwdpbwc-style',
                plugin_dir_url( __FILE__ ) . 'assets/front_style.css',
                array(),
                '1.5.0' . wp_rand()
            );
            // Get style options
            $button_color = bwdpbwc_get_option( 'button_color', '#ea7021' );
            $button_hover_color = bwdpbwc_get_option( 'button_hover_color', '#dd3333' );
            $button_text_color = bwdpbwc_get_option( 'button_text_color', '#ffffff' );
            // Add custom CSS
            $custom_css = "   \r\n    .bwdpbwc-container {\r\n   display: flex;\r\n   flex-wrap: wrap;\r\n   gap: 10px;\r\n   margin: 10px;\r\n   width: 100%;\r\n   align-content: center;\r\n   justify-content: center;\r\n}\r\n   .bwdpbwc-option {\r\n   background: {$button_color};\r\n   color: {$button_text_color};\r\n   font-weight: bold;\r\n   border: 1px solid #ccc;\r\n   padding: 10px;\r\n   border-radius: 5px;\r\n   cursor: pointer;\r\n   text-align: center;\r\nmin-width: 25%;\r\n}\r\n   .bwdpbwc-option:hover {\r\n    background: {$button_hover_color} !important; \r\n    }\r\n   .bwdpbwc-option.selected {\r\n   background: {$button_hover_color};\r\n   border: 2px solid black;\r\n}";
            wp_add_inline_style( 'bwdpbwc-style', esc_attr( $custom_css ) );
            wp_localize_script( 'bwdpbwc-script', 'bwdpbwc_ajax', array(
                'ajax_url' => admin_url( 'admin-ajax.php' ),
            ) );
        }
    }

    // Register CMB2 settings
    function bwdpbwc_register_settings() {
        $cmb = new_cmb2_box( array(
            'id'           => 'bwdpbwc_settings',
            'title'        => __( 'Dynamic Pricing', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' ),
            'object_types' => array('options-page'),
            'icon_url'     => 'dashicons-money-alt',
            'option_key'   => 'bwdpbwc_options',
            'tab_group'    => 'bwdpbwc_options',
            'tab_title'    => __( 'Settings', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' ),
            'display_cb'   => function ( $cmb_options ) {
                ?>
            <div class="wrap fs-section">
                <h2 class="nav-tab-wrapper">
                    <a href="#" class="nav-tab fs-tab nav-tab-active home"><?php 
                echo esc_html__( 'Settings', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' );
                ?></a>
                </h2>
                <h3><?php 
                echo esc_html__( 'Bulk Wholsale Dynamic Pricing Buttons for WooCommerce Settings', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' );
                ?></h3>
    
                <div class="cmb2-options-page">
                    <?php 
                cmb2_metabox_form( $cmb_options->cmb, $cmb_options->option_key );
                ?>
                </div>
            </div>
    <?php 
            },
        ) );
        $cmb->add_field( array(
            'name'    => __( 'Button Color', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' ),
            'id'      => 'button_color',
            'type'    => 'colorpicker',
            'default' => '#ea7021',
        ) );
        $cmb->add_field( array(
            'name'    => __( 'Button Hover Color', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' ),
            'id'      => 'button_hover_color',
            'type'    => 'colorpicker',
            'default' => '#dd3333',
        ) );
        $cmb->add_field( array(
            'name'    => __( 'Button Text Color', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' ),
            'id'      => 'button_text_color',
            'type'    => 'colorpicker',
            'default' => '#ffffff',
        ) );
        $cmb->add_field( array(
            'name'    => __( 'Pricing Method', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' ),
            'id'      => 'pricing_method',
            'type'    => 'select',
            'options' => array(
                'per_piece'    => __( 'Per Piece', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' ),
                'per_quantity' => __( 'Per Quantity', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' ),
            ),
            'default' => 'per_piece',
        ) );
    }

    add_action( 'cmb2_admin_init', 'bwdpbwc_register_settings' );
    // Get option values
    function bwdpbwc_get_option(  $key, $default = ''  ) {
        $options = get_option( 'bwdpbwc_options', array() );
        return ( isset( $options[$key] ) ? $options[$key] : $default );
    }

    add_action( 'wp_enqueue_scripts', 'bwdpbwc_enqueue_scripts' );
    // Add metabox with repeater field
    function bwdpbwc_register_metabox() {
        $cmb = new_cmb2_box( array(
            'id'           => 'bwdpbwc_metabox',
            'title'        => __( 'Bulk Pricing', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' ),
            'object_types' => array('product'),
        ) );
        $group_field_id = $cmb->add_field( array(
            'id'          => 'bwdpbwc_bulk_pricing',
            'type'        => 'group',
            'description' => __( 'Add bulk pricing options', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' ),
            'options'     => array(
                'group_title'    => __( 'Pricing Group {#}', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' ),
                'add_button'     => __( 'Add Pricing Group', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' ),
                'remove_button'  => __( 'Remove Pricing Group', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' ),
                'sortable'       => true,
                'closed'         => true,
                'remove_confirm' => esc_html__( 'Are you sure you want to remove?', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' ),
            ),
        ) );
        $cmb->add_group_field( $group_field_id, array(
            'name' => __( 'Quantity', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' ),
            'id'   => 'quantity',
            'type' => 'text_small',
        ) );
        $pricing_method = bwdpbwc_get_option( 'pricing_method', 'per_piece' );
        $cmb->add_group_field( $group_field_id, array(
            'name'         => __( 'Price', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' ) . '&nbsp' . ucwords( str_replace( '_', ' ', $pricing_method ) ),
            'id'           => 'price',
            'type'         => 'text_money',
            'before_field' => get_woocommerce_currency_symbol(),
        ) );
    }

    add_action( 'cmb2_admin_init', 'bwdpbwc_register_metabox' );
    // Display quantity selection on product page
    function bwdpbwc_add_custom_quantity_buttons() {
        global $product;
        if ( !$product ) {
            return;
        }
        $bulk_pricing = get_post_meta( $product->get_id(), 'bwdpbwc_bulk_pricing', true );
        if ( empty( $bulk_pricing ) ) {
            return;
        }
        echo '<div class="bwdpbwc-container">';
        foreach ( $bulk_pricing as $index => $option ) {
            $comparison_operator = $option["comparison_operator"];
            $pricing_method = bwdpbwc_get_option( 'pricing_method', 'per_piece' );
            if ( $pricing_method == 'per_piece' ) {
                if ( is_array( $option ) && !empty( $option['quantity'] ) && !empty( $option['price'] ) ) {
                    echo sprintf(
                        '<div class="bwdpbwc-option" data-qty="%s" data-price="%s">%s %s %s </br>%s %s %s</div>',
                        esc_attr( $option['quantity'] ),
                        esc_attr( $option['price'] ),
                        esc_html__( 'Get', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' ),
                        esc_html( $option['quantity'] ),
                        esc_html__( 'pcs', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' ),
                        esc_html__( 'for', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' ),
                        esc_html( $option['price'] ),
                        esc_html__( ucwords( str_replace( '_', ' ', $pricing_method ) ), 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' )
                    );
                }
            } else {
                if ( is_array( $option ) && !empty( $option['quantity'] ) && !empty( $option['price'] ) ) {
                    echo sprintf(
                        '<div class="bwdpbwc-option" data-qty="%s" data-price="%s">%s %s %s </br>%s %s</div>',
                        esc_attr( $option['quantity'] ),
                        esc_attr( $option['price'] ),
                        esc_html__( 'Get', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' ),
                        esc_html( $option['quantity'] ),
                        esc_html__( 'pcs', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' ),
                        esc_html__( 'for', 'bulk-wholsale-dynamic-pricing-buttons-for-woocommerce' ),
                        esc_html( $option['price'] )
                    );
                }
            }
        }
        echo '</div>';
    }

    add_action( 'woocommerce_before_add_to_cart_button', 'bwdpbwc_add_custom_quantity_buttons' );
    // Update cart price dynamically
    function bwdpbwc_update_cart_price(  $cart  ) {
        if ( is_admin() && !defined( 'DOING_AJAX' ) ) {
            return;
        }
        foreach ( $cart->get_cart() as $cart_item ) {
            if ( isset( $cart_item['product_id'] ) ) {
                $product_id = $cart_item['product_id'];
                $bulk_pricing = get_post_meta( $product_id, 'bwdpbwc_bulk_pricing', true );
                $quantity = $cart_item['quantity'];
                $pricing_method = bwdpbwc_get_option( 'pricing_method', 'per_piece' );
                if ( !is_array( $bulk_pricing ) ) {
                    continue;
                }
                // Sort bulk pricing by quantity in descending order
                usort( $bulk_pricing, function ( $a, $b ) {
                    return (int) $b['quantity'] - (int) $a['quantity'];
                } );
                foreach ( $bulk_pricing as $option ) {
                    if ( empty( $option['quantity'] ) || empty( $option['price'] ) ) {
                        continue;
                    }
                    $clean_price = (float) str_replace( ['٬', ','], '', $option['price'] );
                    $bulk_quantity = (int) $option['quantity'];
                    if ( $pricing_method == 'per_piece' ) {
                        if ( $quantity == $bulk_quantity ) {
                            // For per-piece pricing, divide total price by quantity to get per-piece price
                            $cart_item['data']->set_price( $clean_price / $quantity );
                            break;
                        }
                    } else {
                        // per_quantity
                        // Apply price when quantity matches or exceeds the bulk quantity
                        if ( $quantity >= $bulk_quantity ) {
                            $cart_item['data']->set_price( $clean_price / $bulk_quantity );
                            break;
                        }
                    }
                }
            }
        }
    }

    function bwdpbwc_compare_quantity(  $operator, $quantity, $option_quantity  ) {
        switch ( $operator ) {
            case 'gte':
                return $quantity >= (int) $option_quantity;
            case 'lte':
                return $quantity <= (int) $option_quantity;
            case 'eq':
                return $quantity == (int) $option_quantity;
            case 'gt':
                return $quantity > (int) $option_quantity;
            case 'lt':
                return $quantity < (int) $option_quantity;
            default:
                return false;
        }
    }

    add_action( 'woocommerce_before_calculate_totals', 'bwdpbwc_update_cart_price' );
}