<?php
if ( ! defined( 'ABSPATH' ) ) { exit; }

class KNSDD_Ajax_Tiers {
    public function __construct() {
        add_action( 'wp_ajax_knsdd_get_tier_table', [ $this, 'get_tier_table' ] );
        add_action( 'wp_ajax_nopriv_knsdd_get_tier_table', [ $this, 'get_tier_table' ] );
    }

    public function get_tier_table() {
        // No-cache headers (CDN/Proxy bypass)
        if ( ! headers_sent() ) {
            nocache_headers();
            header( 'Cache-Control: no-store, no-cache, must-revalidate, max-age=0' );
            header( 'Cache-Control: post-check=0, pre-check=0', false );
            header( 'Pragma: no-cache' );
            header( 'Expires: Wed, 11 Jan 1984 05:00:00 GMT' );
        }
        $nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
        if ( ! wp_verify_nonce( $nonce, 'knsdd_tier' ) ) {
            wp_send_json_error( [ 'code' => 'bad_nonce' ], 403 );
        }

        if ( class_exists('KNSDD_Data') && method_exists('KNSDD_Data','is_globally_enabled') ) {
            if ( ! KNSDD_Data::is_globally_enabled() ) {
                wp_send_json_success( [ 'html' => '' ] );
            }
        }

        $product_id = isset( $_POST['product_id'] ) ? absint( $_POST['product_id'] ) : 0;
        if ( $product_id <= 0 ) {
            wp_send_json_success( [ 'html' => '' ] );
        }

        if ( ! class_exists( 'KNSDD_Tier_Service' ) ) {
            wp_send_json_success( [ 'html' => '' ] );
        }

        $tiers = KNSDD_Tier_Service::get_quantity_tiers_for_product( $product_id );
        if ( empty( $tiers ) ) {
            wp_send_json_success( [ 'html' => '' ] );
        }

        ob_start();
        if ( class_exists( 'KNSDD_Tier_Table_Renderer' ) ) {
            $renderer = new KNSDD_Tier_Table_Renderer();
            $renderer->render( $tiers, [ 'product_id' => $product_id ] );
        } else {
            // Basit fallback
            echo '<div class="knsdd-tier-table-wrap">';
            echo '<div class="knsdd-tier-table__header">' . esc_html__( 'Kademe İndirimi', 'kns-dynamic-discounts-for-woocommerce' ) . '</div>';
            echo '<table class="knsdd-tier-table"><tbody>';
            foreach ( $tiers as $t ) {
                $min = (int) ($t['min'] ?? 0); $max = (int) ($t['max'] ?? 0); $type = $t['type'] ?? 'percent'; $val = (float) ($t['value'] ?? 0);
                $qty = ( $max > 0 ) ? ( ( $min === $max || $min === 0 ) ? (string)$max : ( $min . '–' . $max ) ) : ( max(1,$min) . '+' );
                $disc = ( $type === 'fixed' ) ? ( function_exists('wc_price') ? strip_tags( wc_price( $val ) ) : number_format_i18n( $val, 2 ) ) : ( '%' . rtrim( rtrim( sprintf('%.2f', $val ), '0' ), '.' ) );
                echo '<tr><td>' . esc_html( $qty ) . '</td><td>' . esc_html( $disc ) . '</td></tr>';
            }
            echo '</tbody></table></div>';
        }
        $html = ob_get_clean();

        wp_send_json_success( [ 'html' => $html ] );
    }
}
