<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class Dspilot_Pricing_View_Single_Product extends Dspilot_Plugin {

    public $plugin_options = array();
    public $discounts = array();

    public function __construct() {

        $this->plugin_options = Dspilot_Plugin::get_plugin_options();
        $this->discounts = Dspilot_Plugin::get_discounts('pricing_discounts');


        // Display discount message and pricing
        add_action( 'woocommerce_single_product_summary', [$this, 'show_discount_message_and_price'], 25 );
        add_action( 'woocommerce_single_product_summary', [$this, 'bulk_pricing_discount_table'], 25 );

        add_action( 'wp_ajax_dspilot_get_bulk_pricing_discount_table', [$this, 'dspilot_get_bulk_pricing_discount_table'] );
        add_action( 'wp_ajax_nopriv_dspilot_get_bulk_pricing_discount_table', [$this, 'dspilot_get_bulk_pricing_discount_table'] );

        
    }
    function show_discount_message_and_price() {

        $show_discount_message = isset( $this->plugin_options['show_discount_message'] ) ? $this->plugin_options['show_discount_message'] : true;
        if ( ! $show_discount_message ) return;

        // Example: get discounted products and their messages
        $Dspilot_Pricing_Discount = new Dspilot_Pricing_Discount();

        $discounted_product_ids = $Dspilot_Pricing_Discount->get_discounted_products(); // your function

        $discounts = $this->discounts;

        global $product;

        if ( ! in_array( $product->get_id(), $discounted_product_ids ) ) return;

        // Find applicable discount
        foreach ( $discounts as $discount ) {
            if ( in_array( $product->get_id(), $discounted_product_ids ) ) {
                $message = isset( $discount['message'] ) ? $discount['message'] : '';
                $amount = isset( $discount['amount'] ) ? floatval( $discount['amount'] ) : 0;
                $type = isset( $discount['type'] ) ? $discount['type'] : 'fixed';

                // Output message and prices
                if ( $message ) {
                    echo '<div class="discount-message" style="background:#0a7f4a;color:#fff;padding:10px;margin:15px 0;">' . esc_html( $message ) . '</div>';
                }

                break; // stop after first matching discount
            }
        }
    }

    public function bulk_pricing_discount_table($product_id = null, $variation_id = null) {
        $show_discount_table = isset( $this->plugin_options['show_discount_table'] ) ? $this->plugin_options['show_discount_table'] : true;
        if ( ! $show_discount_table ) return;

        if($product_id || !empty($product_id)) {
            $product = wc_get_product( $product_id );
        }else{
            global $product;
        }
        
         // Ensure $product is a WC_Product object
        if ( ! $product instanceof WC_Product ) return;

        // Get the product ID
        $Dspilot_Pricing_Discount = new Dspilot_Pricing_Discount();
        $discounted_product_ids = $Dspilot_Pricing_Discount->get_discounted_products();
        $discounts = $this->discounts;

        if ( ! in_array( $product->get_id(), $discounted_product_ids ) ) return;

        $product_type = $product->get_type();

        // Detect default variation if variable product
        if ( $product_type === 'variable' ) {
            if(!$variation_id || empty($variation_id)) {
                $available_variations = $product->get_available_variations();
                
                // If there are variations, render tables for all of them so JS can toggle
                if ( ! empty( $available_variations ) ) {
                    foreach ( $available_variations as $variation ) {
                        $var_id = $variation['variation_id'];
                        // This will render a div with ID #discountpilot-dynamic-pricing-table-container-{variation_id}
                        // public.js will hide all and show the relevant one on change
                        $this->render_discount_table_html($Dspilot_Pricing_Discount, $discounts, $discounted_product_ids, $product, $product_type, $var_id);
                    }
                }
            }else{
                // render empty container for bulk pricing discount table
                $this->render_discount_table_wrapper();
            }
        }else{
            
            $this->render_discount_table_html($Dspilot_Pricing_Discount, $discounts, $discounted_product_ids, $product, $product_type, null);
        }
    }

    public function dspilot_get_bulk_pricing_discount_table() {

        $show_discount_table = isset( $this->plugin_options['show_discount_table'] ) ? $this->plugin_options['show_discount_table'] : true;
        if ( ! $show_discount_table ) return;

        // Check nonce for security
        if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'dspilot_public_nonce' ) ) {
            wp_send_json_error( 'Invalid nonce' );
            wp_die();
        }
        
        // Handle AJAX request for bulk pricing discount table
        $product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
        $variation_id = isset($_POST['variation_id']) ? intval($_POST['variation_id']) : null;

        $table_html = '';

         // Validate product ID
        if ( $product_id > 0 ) {
            ob_start();
            $this->bulk_pricing_discount_table($product_id, $variation_id);
            $table_html = ob_get_clean();
            wp_send_json_success( $table_html );
        } else {
            wp_send_json_error( 'Invalid product ID' );
        }

        wp_die(); // this is required to terminate immediately and return a proper response
    }

    // render discount table
    public function render_discount_table_html ($Dspilot_Pricing_Discount, $discounts, $discounted_product_ids, $product, $product_type, $variation_id) {
        foreach ( $discounts as $discount ) {
            if ( in_array( $product->get_id(), $discounted_product_ids ) ) {
                $discount_mode = isset( $discount['mode'] ) ? $discount['mode'] : 'simple';
             
                if ( in_array( $discount_mode, [ 'bulk' ] ) ) {
                    $bulk_discounts = isset( $discount['bulk_amounts'] ) ? $discount['bulk_amounts'] : '';
                    if ( ! empty( $bulk_discounts ) && is_array( $bulk_discounts ) ) {
                        echo '<div id="discountpilot-dynamic-pricing-table-container-'.esc_attr($variation_id).'" class="discountpilot-dynamic-pricing-table-container">';
                        echo '<h3 class="discountpilot-dynamic-pricing-table-caption">Bulk Pricing Discounts</h3>';
                        echo '<table class="bulk-discount-table">';
                        echo '<thead>';
                        echo '<tr>';
                        echo '<th>Quantity</th>';
                        echo '<th>Discount</th>';
                        echo '<th>Price</th>';
                        echo '</tr>';
                        echo '</thead>';
                        echo '<tbody>';

                        // ✅ Base price without hooks (always raw/original price)
                        if ( $product_type === 'variable' ) {
                            $variation_obj =  wc_get_product( $variation_id );
                            $sale_price = $variation_obj->get_sale_price();
                            $regular_price = $variation_obj->get_regular_price();
                            $base_price    = $sale_price ? $sale_price : $regular_price;
                        } else {
                            $sale_price = $product->get_sale_price();
                            $regular_price = $product->get_regular_price();
                            $base_price = $sale_price ? $sale_price : $regular_price;
                        }

                        foreach ( $bulk_discounts as $bulk_discount ) {
                            $min_qty = isset( $bulk_discount['minimum_quantity'] ) ? intval( $bulk_discount['minimum_quantity'] ) : 0;
                            $max_qty = isset( $bulk_discount['maximum_quantity'] ) ? intval( $bulk_discount['maximum_quantity'] ) : 0;
                            $amount  = isset( $bulk_discount['amount'] ) ? floatval( $bulk_discount['amount'] ) : 0;
                            $type    = isset( $bulk_discount['type'] ) ? $bulk_discount['type'] : 'fixed';

                            // Quantity range
                            $qty_range = $max_qty > 0 ? $min_qty . ' - ' . $max_qty : $min_qty . '+';

                            // Discount label
                            $discount_label = ( $type === 'percentage' ) ? $amount . '%' : wc_price( $amount );

                            // ✅ Calculate discounted price from raw base price
                            $discounted_price = $Dspilot_Pricing_Discount->calculate_discounted_price_from_base( $base_price, $product, $min_qty );

                            

                            echo '<tr>';
                            echo '<td style="border:1px solid #ddd;padding:8px;">' . esc_html( $qty_range ) . '</td>';
                            echo '<td style="border:1px solid #ddd;padding:8px;">' . wp_kses_post( $discount_label ) . '</td>';
                            echo '<td style="border:1px solid #ddd;padding:8px;">' . wp_kses_post( wc_price( $discounted_price ) ) . '</td>';
                            echo '</tr>';
                        }

                        echo '</tbody>';
                        echo '</table>';
                        echo '</div>'; // Close table container
                    }
                }

                break; // stop after first matching discount
            }
        }
    }

    // render discount table wrapper onyl for ajax
    public function render_discount_table_wrapper() {
        ?>
         <div id="discountpilot-dynamic-pricing-table-container-" class="discountpilot-dynamic-pricing-table-container">
            <!-- contents will come from ajax -->
         </div>
        <?php
    }

}

// if(!is_admin()) {
    new Dspilot_Pricing_View_Single_Product();
// }