<?php

/**
 * DRBU_Settings — admin podešavanja (Settings API).
 *
 * Stranica pod WooCommerce → Discount Rules Box. Čuva sva podesavanja u jednoj
 * opciji (drbu_options) uz sanitizaciju, capability i nonce provere.
 *
 * @package discount-rules-box-upsell
 */
defined( 'ABSPATH' ) || exit;
class DRBU_Settings {
    const OPTION = 'drbu_options';

    const MENU_SLUG = 'drbu-tiered-buy-box';

    const ANALYTICS_SLUG = 'discount-rules-box-upsell-analytics';

    const CAPABILITY = 'manage_woocommerce';

    const SETTINGS_GROUP = 'drbu_options_group';

    /**
     * Singleton instanca.
     *
     * @var DRBU_Settings|null
     */
    private static $instance = null;

    /**
     * Keširane opcije (saved + defaults).
     *
     * @var array|null
     */
    private $all = null;

    /**
     * Vraća jedinu instancu.
     *
     * @return DRBU_Settings
     */
    public static function instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Privatan konstruktor.
     */
    private function __construct() {
        add_action( 'admin_menu', array($this, 'add_menu_page') );
        add_action( 'admin_init', array($this, 'register_settings') );
        add_filter( 'plugin_action_links_' . plugin_basename( DRBU_PLUGIN_DIR . 'discount-rules-box-upsell.php' ), array($this, 'action_links') );
        add_action( 'wp_ajax_drbu_search_products', array($this, 'ajax_search_products') );
        add_action( 'admin_notices', array($this, 'checkout_result_notice') );
        add_action( 'wp_ajax_drbu_sync_freemius_license', array($this, 'ajax_sync_freemius_license') );
    }

    /**
     * Veza ka podešavanjima na listi plugina.
     *
     * @param array $links Postojeće akcije.
     * @return array
     */
    public function action_links( $links ) {
        $url = admin_url( 'admin.php?page=' . self::MENU_SLUG );
        array_unshift( $links, sprintf( '<a href="%s">%s</a>', esc_url( $url ), esc_html__( 'Settings', 'drbu-discount-rules-box-for-woocommerce' ) ) );
        if ( !drbu_is_pro_active() ) {
            $upgrade = $this->get_pro_url( __( 'Start Free Trial', 'drbu-discount-rules-box-for-woocommerce' ) );
            $links[] = sprintf( '<a href="%s" style="color:#2563eb;font-weight:700;">%s</a>', esc_url( $upgrade['url'] ), esc_html( $upgrade['label'] ) );
        }
        return $links;
    }

    /**
     * Registruje "Discount Rules Box" kao sopstveni top-level admin alat
     * (van WooCommerce menija), sa 2 podstavke: Discount Rules Box (glavna
     * tabla) i DRBU Analytics. Account/Upgrade (Freemius) se otvaraju
     * direktno iz License taba na glavnoj tabli, nema posebne menu stavke.
     */
    public function add_menu_page() {
        add_menu_page(
            __( 'Discount Rules Box', 'drbu-discount-rules-box-for-woocommerce' ),
            __( 'Discount Rules Box', 'drbu-discount-rules-box-for-woocommerce' ),
            self::CAPABILITY,
            self::MENU_SLUG,
            array($this, 'render_page'),
            $this->get_menu_icon_data_uri()
        );
        add_submenu_page(
            self::MENU_SLUG,
            __( 'Discount Rules Box', 'drbu-discount-rules-box-for-woocommerce' ),
            __( 'Discount Rules Box', 'drbu-discount-rules-box-for-woocommerce' ),
            self::CAPABILITY,
            self::MENU_SLUG,
            array($this, 'render_page')
        );
        add_submenu_page(
            self::MENU_SLUG,
            __( 'DRBU Analytics', 'drbu-discount-rules-box-for-woocommerce' ),
            __( 'DRBU Analytics', 'drbu-discount-rules-box-for-woocommerce' ),
            self::CAPABILITY,
            self::ANALYTICS_SLUG,
            array($this, 'render_analytics_page')
        );
    }

    /**
     * Vraća base64 SVG data-URI za top-level menu ikonicu.
     *
     * VAŽNO: običan URL ka slici (npr. DRBU_PLUGIN_URL . '...menu-icon.svg')
     * ne garantuje ispravno skaliranje na standardnih 20x20px u WP admin
     * meniju — SVG bez eksplicitnih width/height atributa (samo viewBox,
     * kao naš menu-icon.svg) može da se renderuje u svojoj "prirodnoj"
     * veličini umesto da poštuje CSS background-size. WordPress core
     * (wp-admin/menu-header.php) posebno prepoznaje 'data:image/svg+xml;base64,'
     * prefiks i tada primenjuje sopstveni CSS koji garantuje tačnih 20x20px
     * (i automatski oboji ikonicu u skladu sa admin color scheme-om) — zato
     * se SVG ovde učitava i base64-enkoduje umesto da se samo prosledi URL.
     *
     * @return string
     */
    private function get_menu_icon_data_uri() {
        $icon_path = DRBU_PLUGIN_DIR . 'assets/images/menu-icon.svg';
        if ( !file_exists( $icon_path ) ) {
            return 'dashicons-tag';
        }
        $svg = file_get_contents( $icon_path );
        if ( false === $svg ) {
            return 'dashicons-tag';
        }
        return 'data:image/svg+xml;base64,' . base64_encode( $svg );
    }

    /**
     * Registruje opciju, sekcije i polja.
     */
    public function register_settings() {
        register_setting( self::SETTINGS_GROUP, self::OPTION, array(
            'type'              => 'array',
            'default'           => $this->defaults(),
            'sanitize_callback' => array($this, 'sanitize'),
        ) );
        // Nivoi pakovanja.
        add_settings_section(
            'drbu_tiers_section',
            __( 'Packaging (tiers)', 'drbu-discount-rules-box-for-woocommerce' ),
            array($this, 'render_tiers_intro'),
            self::MENU_SLUG
        );
        $this->add_field(
            'drbu_tier_count',
            __( 'Number of packaging tiers', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_tier_count',
            'drbu_tiers_section'
        );
        $this->add_field(
            'drbu_tier_rows',
            __( 'Tier details', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_tier_rows',
            'drbu_tiers_section'
        );
        // Opcije prikaza buy box-a (toggle prekidači).
        add_settings_section(
            'drbu_display_options_section',
            __( 'Display options', 'drbu-discount-rules-box-for-woocommerce' ),
            array($this, 'render_display_options_intro'),
            self::MENU_SLUG
        );
        $this->add_field(
            'drbu_enable_free_shipping',
            __( 'Show free shipping', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_toggle',
            'drbu_display_options_section',
            array(
                'key'         => 'drbu_enable_free_shipping',
                'description' => __( 'Displays the shipping status line and free-shipping badge on the selected pack.', 'drbu-discount-rules-box-for-woocommerce' ),
            )
        );
        if ( 'yes' === $this->get( 'drbu_enable_free_shipping', 'yes' ) ) {
            $this->add_field(
                'drbu_free_ship_threshold',
                __( 'Free shipping threshold', 'drbu-discount-rules-box-for-woocommerce' ),
                'render_free_ship_threshold',
                'drbu_display_options_section'
            );
        }
        $this->add_field(
            'drbu_enable_footer_badges',
            __( 'Show footer badges', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_toggle',
            'drbu_display_options_section',
            array(
                'key'         => 'drbu_enable_footer_badges',
                'description' => __( 'Displays trust badges (e.g. shipping, cash on delivery, guarantee) below the CTA button.', 'drbu-discount-rules-box-for-woocommerce' ),
            )
        );
        if ( 'yes' === $this->get( 'drbu_enable_footer_badges', 'yes' ) ) {
            $this->add_field(
                'drbu_footer_badges',
                __( 'Badges below the button', 'drbu-discount-rules-box-for-woocommerce' ),
                'render_string_field',
                'drbu_display_options_section',
                array(
                    'key' => 'footer_badges',
                )
            );
        }
        $this->add_field(
            'drbu_enable_savings',
            __( 'Show savings', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_toggle',
            'drbu_display_options_section',
            array(
                'key'         => 'drbu_enable_savings',
                'description' => __( 'Displays the saved amount on each pack and in the cart line item.', 'drbu-discount-rules-box-for-woocommerce' ),
            )
        );
        $this->add_field(
            'drbu_enable_best_value',
            __( 'Show best value badge', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_toggle',
            'drbu_display_options_section',
            array(
                'key'         => 'drbu_enable_best_value',
                'description' => __( 'Highlights the recommended tier with a "best value" badge.', 'drbu-discount-rules-box-for-woocommerce' ),
            )
        );
        if ( 'yes' === $this->get( 'drbu_enable_best_value', 'yes' ) ) {
            $this->add_field(
                'drbu_best_label',
                __( 'Best value badge text', 'drbu-discount-rules-box-for-woocommerce' ),
                'render_string_field',
                'drbu_display_options_section',
                array(
                    'key' => 'best_label',
                )
            );
            $this->add_field(
                'drbu_best_value_index',
                __( 'Tier with the "best value" badge', 'drbu-discount-rules-box-for-woocommerce' ),
                'render_best_value_index',
                'drbu_display_options_section'
            );
        }
        $this->add_field(
            'drbu_enable_per_unit',
            __( 'Show per-unit price', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_toggle',
            'drbu_display_options_section',
            array(
                'key'         => 'drbu_enable_per_unit',
                'description' => __( 'Displays the unit price label next to the headline price.', 'drbu-discount-rules-box-for-woocommerce' ),
            )
        );
        if ( 'yes' === $this->get( 'drbu_enable_per_unit', 'yes' ) ) {
            $this->add_field(
                'drbu_per_unit_label',
                __( '"Per unit" label', 'drbu-discount-rules-box-for-woocommerce' ),
                'render_string_field',
                'drbu_display_options_section',
                array(
                    'key' => 'per_unit_label',
                )
            );
        }
        $this->add_field(
            'drbu_enable_was_price',
            __( 'Show strikeout price', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_toggle',
            'drbu_display_options_section',
            array(
                'key'         => 'drbu_enable_was_price',
                'description' => __( 'Displays the original price struck through next to the discounted price.', 'drbu-discount-rules-box-for-woocommerce' ),
            )
        );
        // Cene i popusti.
        add_settings_section(
            'drbu_pricing_section',
            __( 'Pricing & discounts', 'drbu-discount-rules-box-for-woocommerce' ),
            '__return_false',
            self::MENU_SLUG
        );
        $this->add_field(
            'drbu_discount_type',
            __( 'Discount model', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_discount_type',
            'drbu_pricing_section'
        );
        $this->add_field(
            'drbu_currency_display',
            __( 'Currency display', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_currency_display',
            'drbu_pricing_section'
        );
        // Prikaz na strani proizvoda.
        add_settings_section(
            'drbu_display_section',
            __( 'Product page display', 'drbu-discount-rules-box-for-woocommerce' ),
            array($this, 'render_display_intro'),
            self::MENU_SLUG
        );
        $this->add_field(
            'drbu_auto_insert_product',
            __( 'Automatic display', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_auto_insert_product',
            'drbu_display_section'
        );
        $this->add_field(
            'drbu_auto_insert_product_ids',
            __( 'Product restriction', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_auto_insert_product_ids',
            'drbu_display_section'
        );
        $this->add_field(
            'drbu_replace_add_to_cart',
            __( 'Replace default "Add to cart"', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_replace_add_to_cart',
            'drbu_display_section'
        );
        $this->add_field(
            'drbu_hide_default_price',
            __( 'Hide default product price', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_hide_default_price',
            'drbu_display_section'
        );
        // Izgled.
        add_settings_section(
            'drbu_appearance_section',
            __( 'Appearance', 'drbu-discount-rules-box-for-woocommerce' ),
            array($this, 'render_appearance_intro'),
            self::MENU_SLUG
        );
        $this->add_field(
            'drbu_primary_color',
            __( 'Primary color', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_color_field',
            'drbu_appearance_section',
            array(
                'key' => 'drbu_primary_color',
            )
        );
        $this->add_field(
            'drbu_cta_text_color',
            __( 'Button text color', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_color_field',
            'drbu_appearance_section',
            array(
                'key' => 'drbu_cta_text_color',
            )
        );
        $this->add_field(
            'drbu_best_value_color',
            __( '"Best value" badge color', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_color_field',
            'drbu_appearance_section',
            array(
                'key' => 'drbu_best_value_color',
            )
        );
        $this->add_field(
            'drbu_card_bg_color',
            __( 'Card background', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_color_field',
            'drbu_appearance_section',
            array(
                'key' => 'drbu_card_bg_color',
            )
        );
        // Tekstovi.
        add_settings_section(
            'drbu_strings_section',
            __( 'Texts / Labels', 'drbu-discount-rules-box-for-woocommerce' ),
            array($this, 'render_strings_intro'),
            self::MENU_SLUG
        );
        $this->add_field(
            'drbu_in_stock_label',
            __( '"In stock" label', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_string_field',
            'drbu_strings_section',
            array(
                'key' => 'in_stock_label',
            )
        );
        $this->add_field(
            'drbu_total_label',
            __( 'Word for "total"', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_string_field',
            'drbu_strings_section',
            array(
                'key' => 'total_label',
            )
        );
        $this->add_field(
            'drbu_pack_total_label',
            __( 'Pack total price sentence', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_string_field',
            'drbu_strings_section',
            array(
                'key' => 'pack_total_label',
            )
        );
        $this->add_field(
            'drbu_savings_label',
            __( 'Word for "savings"', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_string_field',
            'drbu_strings_section',
            array(
                'key' => 'savings_label',
            )
        );
        $this->add_field(
            'drbu_ship_free_text',
            __( 'Free shipping text', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_string_field',
            'drbu_strings_section',
            array(
                'key' => 'ship_free_text',
            )
        );
        $this->add_field(
            'drbu_ship_paid_prefix',
            __( 'Text before the shipping threshold', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_string_field',
            'drbu_strings_section',
            array(
                'key' => 'ship_paid_prefix',
            )
        );
        $this->add_field(
            'drbu_free_ship_flag',
            __( 'Free shipping badge on pack', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_string_field',
            'drbu_strings_section',
            array(
                'key' => 'free_ship_flag',
            )
        );
        $this->add_field(
            'drbu_cta1',
            __( 'CTA button — 1 piece', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_string_field',
            'drbu_strings_section',
            array(
                'key' => 'cta1',
            )
        );
        $this->add_field(
            'drbu_cta2',
            __( 'CTA button — 2 pieces', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_string_field',
            'drbu_strings_section',
            array(
                'key' => 'cta2',
            )
        );
        $this->add_field(
            'drbu_cta3',
            __( 'CTA button — 3 pieces', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_string_field',
            'drbu_strings_section',
            array(
                'key' => 'cta3',
            )
        );
        $this->add_field(
            'drbu_cart_pack_label',
            __( 'Pack label in cart', 'drbu-discount-rules-box-for-woocommerce' ),
            'render_string_field',
            'drbu_strings_section',
            array(
                'key' => 'cart_pack_label',
            )
        );
    }

    /**
     * Pomoćnik za add_settings_field sa našim renderer-ima.
     *
     * @param string $id      ID polja.
     * @param string $title   Naslov polja.
     * @param string $method  Metod renderera.
     * @param string $section Sekcija.
     * @param array  $args    Dodatni argumenti.
     */
    private function add_field(
        $id,
        $title,
        $method,
        $section,
        $args = array()
    ) {
        add_settings_field(
            $id,
            $title,
            array($this, $method),
            self::MENU_SLUG,
            $section,
            $args
        );
    }

    /**
     * Renderuje stranicu podešavanja.
     */
    /**
     * Renderuje stranicu podešavanja.
     */
    /**
     * Renderuje stranicu podešavanja.
     */
    public function render_page() {
        if ( !current_user_can( self::CAPABILITY ) ) {
            wp_die( esc_html__( 'You do not have permission to access this page.', 'drbu-discount-rules-box-for-woocommerce' ) );
        }
        $current_tab = ( isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : 'tiers' );
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        ?>
		<div class="wrap drbu-wrap drbu-dashboard">
			<header class="drbu-dashboard-header">
				<div class="drbu-header-brand">
					<div class="drbu-logo-badge">
						<img src="<?php 
        echo esc_url( DRBU_PLUGIN_URL . 'assets/images/DRBlogo.svg' );
        ?>" alt="<?php 
        esc_attr_e( 'Discount Rules Box', 'drbu-discount-rules-box-for-woocommerce' );
        ?>" class="drbu-header-logo">
					</div>
					<div>
						<h1><span class="screen-reader-text"><?php 
        echo esc_html__( 'Discount Rules Box', 'drbu-discount-rules-box-for-woocommerce' );
        ?></span><span class="drbu-version-tag">v<?php 
        echo esc_html( DRBU_VERSION );
        ?></span></h1>
						<p class="drbu-subtitle"><?php 
        echo esc_html__( 'Configure packaging, discounts, appearance & live real-time preview builder', 'drbu-discount-rules-box-for-woocommerce' );
        ?></p>
					</div>
				</div>
				<div class="drbu-header-actions">
					<?php 
        if ( $this->is_pro_active() ) {
            ?>
						<?php 
            $status_label = ( DRBU_License::instance()->is_trial() ? __( 'Pro Trial Active', 'drbu-discount-rules-box-for-woocommerce' ) : __( 'Pro Active', 'drbu-discount-rules-box-for-woocommerce' ) );
            ?>
						<span class="drbu-status-pill drbu-status-pro"><span class="drbu-status-dot"></span> <?php 
            echo esc_html( $status_label );
            ?></span>
					<?php 
        } else {
            ?>
						<?php 
            $trial_cta = $this->get_pro_url( __( 'Start 30-Day Free Pro Trial', 'drbu-discount-rules-box-for-woocommerce' ) );
            ?>
						<a href="<?php 
            echo esc_url( $trial_cta['url'] );
            ?>" class="button button-primary drbu-open-trial" style="background:#2563eb;border-color:#1d4ed8;font-weight:700;border-radius:100px;padding:4px 16px;text-decoration:none;"><?php 
            echo esc_html( $trial_cta['label'] );
            ?></a>
						<span class="drbu-status-pill"><span class="drbu-status-dot"></span> <?php 
            echo esc_html__( 'Free Version', 'drbu-discount-rules-box-for-woocommerce' );
            ?></span>
					<?php 
        }
        ?>
				</div>
			</header>
			<hr class="wp-header-end">

			<?php 
        settings_errors();
        ?>

			<form method="post" action="options.php" id="drbu-settings-form">
				<?php 
        settings_fields( self::SETTINGS_GROUP );
        ?>

				<!-- FULL-WIDTH TOP TABS NAVIGATION -->
				<nav class="drbu-tabs-nav" role="tablist">
					<button type="button" class="drbu-tab-btn active" data-tab="tiers">
						<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"></path></svg>
						<span><?php 
        echo esc_html__( '1. Tiers & Pricing', 'drbu-discount-rules-box-for-woocommerce' );
        ?></span>
					</button>
					<button type="button" class="drbu-tab-btn" data-tab="appearance">
						<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><path d="m4.93 4.93 4.24 4.24"></path><path d="m14.83 9.17 4.24-4.24"></path><path d="m14.83 14.83 4.24 4.24"></path><path d="m9.17 14.83-4.24 4.24"></path></svg>
						<span><?php 
        echo esc_html__( '2. Appearance & Styles', 'drbu-discount-rules-box-for-woocommerce' );
        ?></span>
					</button>
					<button type="button" class="drbu-tab-btn" data-tab="display">
						<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"></path><circle cx="12" cy="12" r="3"></circle></svg>
						<span><?php 
        echo esc_html__( '3. Display Options', 'drbu-discount-rules-box-for-woocommerce' );
        ?></span>
					</button>
					<button type="button" class="drbu-tab-btn" data-tab="texts">
						<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="4 7 4 4 20 4 20 7"></polyline><line x1="9" y1="20" x2="15" y2="20"></line><line x1="12" y1="4" x2="12" y2="20"></line></svg>
						<span><?php 
        echo esc_html__( '4. Texts & Badges', 'drbu-discount-rules-box-for-woocommerce' );
        ?></span>
					</button>
					<button type="button" class="drbu-tab-btn" data-tab="integration">
						<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="18" height="18" x="3" y="3" rx="2"></rect><path d="M3 9h18"></path><path d="M9 21V9"></path></svg>
						<span><?php 
        echo esc_html__( '5. Integration', 'drbu-discount-rules-box-for-woocommerce' );
        ?></span>
					</button>
					<button type="button" class="drbu-tab-btn" data-tab="license">
						<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="18" height="11" x="3" y="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>
						<span><?php 
        echo esc_html__( '6. License', 'drbu-discount-rules-box-for-woocommerce' );
        ?></span>
					</button>
					<button type="button" class="drbu-tab-btn" data-tab="account">
						<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>
						<span><?php 
        echo esc_html__( 'Account', 'drbu-discount-rules-box-for-woocommerce' );
        ?></span>
					</button>
					<button type="button" class="drbu-tab-btn drbu-tab-btn-pro" data-tab="upgrade">
						<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 12V8a6 6 0 0 0-8-5.3A6 6 0 0 0 4 8v4a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a2 2 0 0 0-2-2Z"></path><path d="M4 12v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"></path></svg>
						<span><?php 
        echo esc_html__( 'Upgrade', 'drbu-discount-rules-box-for-woocommerce' );
        ?></span>
					</button>
				</nav>

				<div class="drbu-dashboard-grid">
					<!-- LEFT SIDE: TABS & SETTINGS -->
					<div class="drbu-dashboard-main">
						<div class="drbu-tab-panels">
						<!-- TAB 1: TIERS & PRICING -->
						<div class="drbu-tab-panel active" id="drbu-tab-tiers">
							<div class="drbu-card">
								<div class="drbu-card-header">
									<h3><?php 
        echo esc_html__( 'Buy Box Setup & Pricing Strategy', 'drbu-discount-rules-box-for-woocommerce' );
        ?></h3>
									<p><?php 
        echo esc_html__( 'Choose how your buy box tiers calculate prices and discounts to maximize Average Order Value (AOV).', 'drbu-discount-rules-box-for-woocommerce' );
        ?></p>
								</div>
								<div class="drbu-card-body">
									<div class="drbu-form-row" style="margin-bottom: 22px;">
										<label class="drbu-label" style="font-size: 14px; font-weight: 700; color: #0f172a;">
											<?php 
        echo esc_html__( '1. Number of Tiers in Buy Box', 'drbu-discount-rules-box-for-woocommerce' );
        ?>
										</label>
										<div class="drbu-radio-group" id="drbu-tier-count-selector">
											<?php 
        $tc = (int) $this->get( 'drbu_tier_count', 3 );
        ?>
											<label class="drbu-radio-btn <?php 
        echo ( 2 === $tc ? 'selected' : '' );
        ?>">
												<input type="radio" name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_tier_count]" value="2" <?php 
        checked( $tc, 2 );
        ?>>
												<span><?php 
        echo esc_html__( '2 Tiers (1 & 2 pieces)', 'drbu-discount-rules-box-for-woocommerce' );
        ?></span>
											</label>
											<label class="drbu-radio-btn <?php 
        echo ( 3 === $tc ? 'selected' : '' );
        ?>" <?php 
        echo ( $this->is_pro_active() ? '' : 'style="opacity:.55;"' );
        ?>>
												<input type="radio" name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_tier_count]" value="3" <?php 
        checked( $tc, 3 );
        echo ( $this->is_pro_active() ? '' : ' disabled' );
        ?>>
												<span><?php 
        echo esc_html__( '3 Tiers (1, 2 & 3 pieces)', 'drbu-discount-rules-box-for-woocommerce' );
        ?></span>
												<?php 
        if ( !$this->is_pro_active() ) {
            ?>
													<span class="drbu-pro-chip" style="margin-left:8px;"><?php 
            echo esc_html__( 'Pro', 'drbu-discount-rules-box-for-woocommerce' );
            ?></span>
												<?php 
        }
        ?>
											</label>
										</div>
										<?php 
        if ( !$this->is_pro_active() ) {
            ?>
											<p class="description" style="margin-top:8px;">
												🔒 <?php 
            echo esc_html__( 'The 3-tier buy box is a Pro feature. Upgrade to unlock 3 packs (1, 2 & 3 pieces).', 'drbu-discount-rules-box-for-woocommerce' );
            ?>
												<?php 
            $t3_cta = $this->get_pro_url( __( 'Start Free Trial', 'drbu-discount-rules-box-for-woocommerce' ) );
            ?>
												<a href="<?php 
            echo esc_url( $t3_cta['url'] );
            ?>" target="_blank" rel="noopener noreferrer"><?php 
            echo esc_html( $t3_cta['label'] );
            ?></a>
											</p>
										<?php 
        }
        ?>
									</div>

									<div class="drbu-form-row" style="margin-bottom: 24px;">
										<label class="drbu-label" style="font-size: 14px; font-weight: 700; color: #0f172a; margin-bottom: 8px; display: block;">
											<?php 
        echo esc_html__( '2. How Discounts & Bundle Prices Are Calculated', 'drbu-discount-rules-box-for-woocommerce' );
        ?>
										</label>
										<?php 
        $pm = $this->get( 'drbu_pricing_model', 'model_a' );
        ?>
										<div class="drbu-radio-group drbu-pricing-model-group" style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px;">
											<label class="drbu-radio-btn drbu-pm-btn <?php 
        echo ( 'model_a' === $pm ? 'selected' : '' );
        ?>" style="flex-direction: column; align-items: flex-start; padding: 14px 16px; gap: 6px; text-align: left;">
												<div style="display:flex; align-items:center; justify-content:space-between; width:100%;">
													<div style="font-weight: 800; font-size: 13.5px; color: #1e40af;">
														<input type="radio" name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_pricing_model]" value="model_a" <?php 
        checked( $pm, 'model_a' );
        ?>>
														🎯 <?php 
        echo esc_html__( 'Discount on 2nd & 3rd Item', 'drbu-discount-rules-box-for-woocommerce' );
        ?>
													</div>
													<span style="font-size:10.5px; font-weight:800; background:#dbeafe; color:#1e40af; padding:2px 8px; border-radius:100px; text-transform:uppercase; letter-spacing:0.04em; flex-shrink:0;">⭐ <?php 
        echo esc_html__( 'Recommended', 'drbu-discount-rules-box-for-woocommerce' );
        ?></span>
												</div>
												<div style="font-size: 12px; color: #475569; line-height: 1.4; margin-top:2px;">
													<?php 
        echo esc_html__( 'Discount applies ONLY to the additional item(s). E.g. 1st item = full price ($18), 2nd item = 40% off ($10.80) → $28.80 total ($14.40/unit). Drives over 80% of buyers to 2+ pieces!', 'drbu-discount-rules-box-for-woocommerce' );
        ?>
												</div>
											</label>

											<label class="drbu-radio-btn drbu-pm-btn <?php 
        echo ( 'model_b' === $pm ? 'selected' : '' );
        ?>" style="flex-direction: column; align-items: flex-start; padding: 14px 16px; gap: 6px; text-align: left;">
												<div style="font-weight: 800; font-size: 13.5px; color: #047857;">
													<input type="radio" name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_pricing_model]" value="model_b" <?php 
        checked( $pm, 'model_b' );
        ?>>
													🏷️ <?php 
        echo esc_html__( 'Discount on Entire Quantity', 'drbu-discount-rules-box-for-woocommerce' );
        ?>
												</div>
												<div style="font-size: 12px; color: #475569; line-height: 1.4; margin-top:2px;">
													<?php 
        echo esc_html__( 'Discount % or $ applies across ALL items in the bundle pack. E.g. 40% off both items = $21.60 total ($10.80/unit).', 'drbu-discount-rules-box-for-woocommerce' );
        ?>
												</div>
											</label>

											<label class="drbu-radio-btn drbu-pm-btn <?php 
        echo ( 'model_c' === $pm ? 'selected' : '' );
        ?>" style="flex-direction: column; align-items: flex-start; padding: 14px 16px; gap: 6px; text-align: left;">
												<div style="font-weight: 800; font-size: 13.5px; color: #7c3aed;">
													<input type="radio" name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_pricing_model]" value="model_c" <?php 
        checked( $pm, 'model_c' );
        ?>>
													💵 <?php 
        echo esc_html__( 'Fixed Total Package Price', 'drbu-discount-rules-box-for-woocommerce' );
        ?>
												</div>
												<div style="font-size: 12px; color: #475569; line-height: 1.4; margin-top:2px;">
													<?php 
        echo esc_html__( 'Set exact fixed total price for each pack tier. E.g. Tier 1 = $18.00 total, Tier 2 = $28.80 total, Tier 3 = $39.99 total.', 'drbu-discount-rules-box-for-woocommerce' );
        ?>
												</div>
											</label>

											<label class="drbu-radio-btn drbu-pm-btn <?php 
        echo ( 'model_d' === $pm ? 'selected' : '' );
        ?>" style="flex-direction: column; align-items: flex-start; padding: 14px 16px; gap: 6px; text-align: left;">
												<div style="font-weight: 800; font-size: 13.5px; color: #d97706;">
													<input type="radio" name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_pricing_model]" value="model_d" <?php 
        checked( $pm, 'model_d' );
        ?>>
													🏷️ <?php 
        echo esc_html__( 'Fixed Price Per Unit', 'drbu-discount-rules-box-for-woocommerce' );
        ?>
												</div>
												<div style="font-size: 12px; color: #475569; line-height: 1.4; margin-top:2px;">
													<?php 
        echo esc_html__( 'Set exact fixed price per single item for each pack tier. E.g. Tier 2 = $14.40/unit → $28.80 total.', 'drbu-discount-rules-box-for-woocommerce' );
        ?>
												</div>
											</label>
										</div>
									</div>

									<div class="drbu-form-row" style="margin-bottom: 22px;">
										<label class="drbu-label" style="font-size: 14px; font-weight: 700; color: #0f172a; margin-bottom: 6px; display: block;">
											<?php 
        echo esc_html__( '3. Discount Unit', 'drbu-discount-rules-box-for-woocommerce' );
        ?>
										</label>
										<?php 
        $this->render_discount_type();
        ?>
									</div>

									<div class="drbu-form-row">
										<label class="drbu-label" style="font-size: 14px; font-weight: 700; color: #0f172a; margin-bottom: 8px; display: block;">
											<?php 
        echo esc_html__( '4. Configure Tier Amounts & Quantities', 'drbu-discount-rules-box-for-woocommerce' );
        ?>
										</label>
										<?php 
        $this->render_tier_rows();
        ?>
									</div>
								</div>
							</div>
						</div>

						<!-- TAB 2: APPEARANCE & STYLES -->
						<div class="drbu-tab-panel" id="drbu-tab-appearance">
							<?php 
        if ( function_exists( 'drbu_fs' ) && drbu_fs() && drbu_fs()->is__premium_only() ) {
            ?>
								<?php 
            $this->render_appearance_panel__premium_only();
            ?>
							<?php 
        } else {
            ?>
								<div class="drbu-card">
									<div class="drbu-card-header">
										<h3>🔒 <?php 
            echo esc_html__( 'Appearance & Styles — Pro Feature', 'drbu-discount-rules-box-for-woocommerce' );
            ?></h3>
										<p><?php 
            echo esc_html__( 'Customize brand colors, CTA/card corner radius, and apply 1-click curated style presets.', 'drbu-discount-rules-box-for-woocommerce' );
            ?></p>
									</div>
									<div class="drbu-card-body">
										<ul style="margin:0 0 16px 20px; list-style-type:disc; color:#475569; line-height:2;">
											<li><?php 
            echo esc_html__( 'Primary, button text, "Best Value" badge & card background colors', 'drbu-discount-rules-box-for-woocommerce' );
            ?></li>
											<li><?php 
            echo esc_html__( 'Pill / rounded / sharp CTA button radius', 'drbu-discount-rules-box-for-woocommerce' );
            ?></li>
											<li><?php 
            echo esc_html__( 'Curated style presets (Warm Rose Gold, Amazon Orange, Modern Blue…)', 'drbu-discount-rules-box-for-woocommerce' );
            ?></li>
										</ul>
										<?php 
            $app_cta = $this->get_pro_url( __( 'Unlock with 30-Day Free Trial', 'drbu-discount-rules-box-for-woocommerce' ) );
            ?>
										<a href="<?php 
            echo esc_url( $app_cta['url'] );
            ?>" class="button button-primary drbu-open-trial" style="background:#2563eb;border-color:#1d4ed8;font-weight:700;border-radius:100px;padding:6px 18px;text-decoration:none;"><?php 
            echo esc_html( $app_cta['label'] );
            ?></a>
									</div>
								</div>
							<?php 
        }
        ?>
						</div>

						<!-- TAB 3: DISPLAY OPTIONS -->
						<div class="drbu-tab-panel" id="drbu-tab-display">
							<div class="drbu-card">
								<div class="drbu-card-header">
									<h3><?php 
        echo esc_html__( 'Display Elements & Callouts', 'drbu-discount-rules-box-for-woocommerce' );
        ?></h3>
									<p><?php 
        echo esc_html__( 'Toggle individual visual elements of the buy box on and off.', 'drbu-discount-rules-box-for-woocommerce' );
        ?></p>
								</div>
								<div class="drbu-card-body">
									<!-- DEMO PRODUCT BASE PRICE FIELD (LIVE PREVIEW CALCULATION) -->
									<div class="drbu-form-row drbu-demo-price-row" style="margin-bottom:24px; padding:16px 18px; background:#eff6ff; border:1px solid #bfdbfe; border-radius:12px;">
										<label class="drbu-label" for="drbu-test-price" style="font-size:14px; font-weight:800; color:#1e40af; display:block; margin-bottom:4px;">
											🏷️ <?php 
        echo esc_html__( 'Demo Product Base Price (Live Preview Calculation)', 'drbu-discount-rules-box-for-woocommerce' );
        ?>
										</label>
										<p style="font-size:12.5px; color:#3b82f6; margin-bottom:10px; line-height:1.4;">
											<?php 
        echo esc_html__( 'Set the single-item base price to test how tier discounts and savings calculate in real-time in the Live Preview.', 'drbu-discount-rules-box-for-woocommerce' );
        ?>
										</p>
										<div class="drbu-test-price-input-wrap" style="display:inline-flex; align-items:center; gap:8px;">
											<input type="number" id="drbu-test-price" value="18" step="1" min="1" class="small-text" style="font-size:15px; font-weight:800; padding:6px 12px; border-radius:8px; border:1.5px solid #2563eb; color:#0f172a; width:110px;">
											<span style="font-size:14px; font-weight:700; color:#1e40af;"><?php 
        echo esc_html( ( function_exists( 'get_woocommerce_currency_symbol' ) ? html_entity_decode( get_woocommerce_currency_symbol() ) : '$' ) );
        ?></span>
										</div>
									</div>

									<div class="drbu-toggles-list">
										<div class="drbu-toggle-item">
											<div class="drbu-toggle-info">
												<strong><?php 
        echo esc_html__( 'Show free shipping', 'drbu-discount-rules-box-for-woocommerce' );
        ?></strong>
												<p><?php 
        echo esc_html__( 'Displays the shipping status callout and free shipping badge on qualifying packs.', 'drbu-discount-rules-box-for-woocommerce' );
        ?></p>
											</div>
											<label class="drbu-switch">
												<input type="checkbox" name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_enable_free_shipping]" value="yes" <?php 
        checked( $this->get( 'drbu_enable_free_shipping', 'yes' ), 'yes' );
        ?>>
												<span class="drbu-slider"></span>
											</label>
										</div>

										<div class="drbu-subfield <?php 
        echo ( 'yes' === $this->get( 'drbu_enable_free_shipping', 'yes' ) ? '' : 'hidden' );
        ?>" id="drbu-subfield-free-ship-threshold">
											<label class="drbu-label"><?php 
        echo esc_html__( 'Free shipping threshold amount', 'drbu-discount-rules-box-for-woocommerce' );
        ?></label>
											<?php 
        $this->render_free_ship_threshold();
        ?>
										</div>

										<div class="drbu-toggle-item">
											<div class="drbu-toggle-info">
												<strong><?php 
        echo esc_html__( 'Show badges below the button', 'drbu-discount-rules-box-for-woocommerce' );
        ?></strong>
												<p><?php 
        echo esc_html__( 'Displays guarantee, shipping, and payment trust badges below the CTA button.', 'drbu-discount-rules-box-for-woocommerce' );
        ?></p>
											</div>
											<label class="drbu-switch">
												<input type="checkbox" name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_enable_footer_badges]" value="yes" <?php 
        checked( $this->get( 'drbu_enable_footer_badges', 'yes' ), 'yes' );
        ?>>
												<span class="drbu-slider"></span>
											</label>
										</div>

										<div class="drbu-toggle-item">
											<div class="drbu-toggle-info">
												<strong><?php 
        echo esc_html__( 'Show savings callout', 'drbu-discount-rules-box-for-woocommerce' );
        ?></strong>
												<p><?php 
        echo esc_html__( 'Displays the exact saved amount on each pack card and in the cart.', 'drbu-discount-rules-box-for-woocommerce' );
        ?></p>
											</div>
											<label class="drbu-switch">
												<input type="checkbox" name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_enable_savings]" value="yes" <?php 
        checked( $this->get( 'drbu_enable_savings', 'yes' ), 'yes' );
        ?>>
												<span class="drbu-slider"></span>
											</label>
										</div>

										<div class="drbu-toggle-item">
											<div class="drbu-toggle-info">
												<strong><?php 
        echo esc_html__( 'Show "Best Value" badge', 'drbu-discount-rules-box-for-woocommerce' );
        ?></strong>
												<p><?php 
        echo esc_html__( 'Highlights the recommended packaging tier with a highlighted badge.', 'drbu-discount-rules-box-for-woocommerce' );
        ?></p>
											</div>
											<label class="drbu-switch">
												<input type="checkbox" name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_enable_best_value]" value="yes" <?php 
        checked( $this->get( 'drbu_enable_best_value', 'yes' ), 'yes' );
        ?>>
												<span class="drbu-slider"></span>
											</label>
										</div>

										<div class="drbu-subfield <?php 
        echo ( 'yes' === $this->get( 'drbu_enable_best_value', 'yes' ) ? '' : 'hidden' );
        ?>" id="drbu-subfield-best-value-index">
											<label class="drbu-label"><?php 
        echo esc_html__( 'Tier with "Best Value" badge', 'drbu-discount-rules-box-for-woocommerce' );
        ?></label>
											<?php 
        $this->render_best_value_index();
        ?>
										</div>

										<div class="drbu-toggle-item">
											<div class="drbu-toggle-info">
												<strong><?php 
        echo esc_html__( 'Show per-unit price', 'drbu-discount-rules-box-for-woocommerce' );
        ?></strong>
												<p><?php 
        echo esc_html__( 'Displays the price calculated per individual piece in header and tier card.', 'drbu-discount-rules-box-for-woocommerce' );
        ?></p>
											</div>
											<label class="drbu-switch">
												<input type="checkbox" name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_enable_per_unit]" value="yes" <?php 
        checked( $this->get( 'drbu_enable_per_unit', 'yes' ), 'yes' );
        ?>>
												<span class="drbu-slider"></span>
											</label>
										</div>

										<div class="drbu-toggle-item">
											<div class="drbu-toggle-info">
												<strong><?php 
        echo esc_html__( 'Show strikeout price', 'drbu-discount-rules-box-for-woocommerce' );
        ?></strong>
												<p><?php 
        echo esc_html__( 'Displays the original price struck through next to the discounted price.', 'drbu-discount-rules-box-for-woocommerce' );
        ?></p>
											</div>
											<label class="drbu-switch">
												<input type="checkbox" name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_enable_was_price]" value="yes" <?php 
        checked( $this->get( 'drbu_enable_was_price', 'yes' ), 'yes' );
        ?>>
												<span class="drbu-slider"></span>
											</label>
										</div>
									</div>
								</div>
							</div>
						</div>

						<!-- TAB 4: TEXTS & BADGES -->
						<div class="drbu-tab-panel" id="drbu-tab-texts">
							<!-- 1-CLICK QUICK LANGUAGE PRESETS -->
							<div class="drbu-card drbu-lang-preset-card" style="background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%); border: 1.5px solid #93c5fd; border-radius: 14px; padding: 20px; margin-bottom: 20px;">
								<div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 16px;">
									<div>
										<div style="display: flex; align-items: center; gap: 8px; font-weight: 800; font-size: 15.5px; color: #1e40af;">
											<span style="font-size: 22px;">🌐</span> <?php 
        echo esc_html__( '1-Click Quick Language Presets', 'drbu-discount-rules-box-for-woocommerce' );
        ?>
										</div>
										<p style="margin: 4px 0 0 0; font-size: 13px; color: #1d4ed8; line-height: 1.4;">
											<?php 
        echo esc_html__( 'Choose your store language to instantly fill all text, badge, button, and cart fields with high-converting translations. Every field remains 100% customizable!', 'drbu-discount-rules-box-for-woocommerce' );
        ?>
										</p>
									</div>
									<div style="display: flex; align-items: center; gap: 10px;">
										<?php 
        if ( !$this->is_pro_active() ) {
            ?>
											<span class="drbu-pro-chip" style="background:#2563eb;color:#fff;padding:4px 10px;border-radius:100px;font-size:11px;font-weight:800;letter-spacing:0.04em;text-transform:uppercase;">🔒 <?php 
            echo esc_html__( 'Pro', 'drbu-discount-rules-box-for-woocommerce' );
            ?></span>
										<?php 
        }
        ?>
										<select id="drbu-quick-lang-select" <?php 
        echo ( $this->is_pro_active() ? '' : 'disabled title="' . esc_attr__( 'Pro feature — start your 30-day free trial to unlock 1-click language presets', 'drbu-discount-rules-box-for-woocommerce' ) . '"' );
        ?> style="padding: 10px 16px; border: 1.5px solid #2563eb; border-radius: 10px; font-size: 14px; font-weight: 700; color: #1e3a8a; background: #ffffff; cursor: pointer; box-shadow: 0 4px 14px rgba(37, 99, 235, 0.15);">
											<option value=""><?php 
        echo esc_html__( '— Select Language Preset —', 'drbu-discount-rules-box-for-woocommerce' );
        ?></option>
											<option value="en">🇬🇧 English (Global)</option>
											<option value="es">🇪🇸 Español (Spanish)</option>
											<option value="de">🇩🇪 Deutsch (German)</option>
											<option value="fr">🇫🇷 Français (French)</option>
											<option value="it">🇮🇹 Italiano (Italian)</option>
											<option value="pt">🇧🇷 Português (Portuguese / Brazil)</option>
											<option value="ru">🇷🇺 Русский (Russian)</option>
											<option value="hi">🇮🇳 हिन्दी (Hindi / India)</option>
											<option value="nl">🇳🇱 Nederlands (Dutch)</option>
											<option value="pl">🇵🇱 Polski (Polish)</option>
											<option value="ro">🇷🇴 Română (Romanian)</option>
											<option value="hu">🇭🇺 Magyar (Hungarian)</option>
											<option value="sr">🇷🇸 Srpski / Hrvatski / Bosanski</option>
										</select>
									</div>
								</div>
							</div>

							<?php 
        if ( !$this->is_pro_active() ) {
            ?>
								<p class="description" style="margin:-8px 0 20px 0;">
									🔒 <?php 
            echo esc_html__( '1-Click Quick Language Presets are a Pro feature. You can still edit every text manually below.', 'drbu-discount-rules-box-for-woocommerce' );
            ?>
									<?php 
            $lang_cta = $this->get_pro_url( __( 'Start Free Trial', 'drbu-discount-rules-box-for-woocommerce' ) );
            ?>
									<a href="<?php 
            echo esc_url( $lang_cta['url'] );
            ?>"><?php 
            echo esc_html( $lang_cta['label'] );
            ?></a>
								</p>
							<?php 
        }
        ?>

							<!-- PACKAGE TITLES & NOTES TRANSLATION -->
							<div class="drbu-card">
								<div class="drbu-card-header">
									<h3><?php 
        echo esc_html__( 'Package Titles & Notes Translation', 'drbu-discount-rules-box-for-woocommerce' );
        ?></h3>
									<p><?php 
        echo esc_html__( 'Translate or customize the main titles and subtitles/notes rendered on each tier card. Placeholders: {d2}, {d3}, {save}, {qty}, {price}', 'drbu-discount-rules-box-for-woocommerce' );
        ?></p>
								</div>
								<div class="drbu-card-body">
									<?php 
        $tiers_data = $this->tiers();
        ?>
									<div class="drbu-form-grid-2">
										<div class="drbu-form-row">
											<label class="drbu-label"><?php 
        echo esc_html__( 'Tier 1 — Package Title', 'drbu-discount-rules-box-for-woocommerce' );
        ?></label>
											<input type="text" class="regular-text drbu-tier-input-label" data-tier="1"
												name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_tiers][0][label]"
												value="<?php 
        echo esc_attr( ( isset( $tiers_data[0]['label'] ) ? $tiers_data[0]['label'] : '1 piece' ) );
        ?>">
										</div>
										<div class="drbu-form-row">
											<label class="drbu-label"><?php 
        echo esc_html__( 'Tier 1 — Description / Note', 'drbu-discount-rules-box-for-woocommerce' );
        ?></label>
											<input type="text" class="regular-text drbu-tier-input-note" data-tier="1"
												name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_tiers][0][note]"
												value="<?php 
        echo esc_attr( ( isset( $tiers_data[0]['note'] ) ? $tiers_data[0]['note'] : 'Basic packaging' ) );
        ?>">
										</div>

										<div class="drbu-form-row">
											<label class="drbu-label"><?php 
        echo esc_html__( 'Tier 2 — Package Title', 'drbu-discount-rules-box-for-woocommerce' );
        ?></label>
											<input type="text" class="regular-text drbu-tier-input-label" data-tier="2"
												name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_tiers][1][label]"
												value="<?php 
        echo esc_attr( ( isset( $tiers_data[1]['label'] ) ? $tiers_data[1]['label'] : '2 pieces' ) );
        ?>">
										</div>
										<div class="drbu-form-row">
											<label class="drbu-label"><?php 
        echo esc_html__( 'Tier 2 — Description / Note', 'drbu-discount-rules-box-for-woocommerce' );
        ?></label>
											<input type="text" class="regular-text drbu-tier-input-note" data-tier="2"
												name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_tiers][1][note]"
												value="<?php 
        echo esc_attr( ( isset( $tiers_data[1]['note'] ) ? $tiers_data[1]['note'] : 'Second item − {d2} · {save}' ) );
        ?>">
										</div>

										<div class="drbu-form-row">
											<label class="drbu-label"><?php 
        echo esc_html__( 'Tier 3 — Package Title', 'drbu-discount-rules-box-for-woocommerce' );
        ?></label>
											<input type="text" class="regular-text drbu-tier-input-label" data-tier="3"
												name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_tiers][2][label]"
												value="<?php 
        echo esc_attr( ( isset( $tiers_data[2]['label'] ) ? $tiers_data[2]['label'] : '3 pieces' ) );
        ?>">
										</div>
										<div class="drbu-form-row">
											<label class="drbu-label"><?php 
        echo esc_html__( 'Tier 3 — Description / Note', 'drbu-discount-rules-box-for-woocommerce' );
        ?></label>
											<input type="text" class="regular-text drbu-tier-input-note" data-tier="3"
												name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_tiers][2][note]"
												value="<?php 
        echo esc_attr( ( isset( $tiers_data[2]['note'] ) ? $tiers_data[2]['note'] : 'Third item − {d3} · {save}' ) );
        ?>">
										</div>
									</div>
								</div>
							</div>

							<div class="drbu-card">
								<div class="drbu-card-header">
									<h3><?php 
        echo esc_html__( 'Trust Badges below the button', 'drbu-discount-rules-box-for-woocommerce' );
        ?></h3>
									<p><?php 
        echo esc_html__( 'Enter one trust badge line per row. Each line will render with a checkmark icon below the CTA button.', 'drbu-discount-rules-box-for-woocommerce' );
        ?></p>
								</div>
								<div class="drbu-card-body">
									<div class="drbu-form-row">
										<?php 
        $this->render_string_field( array(
            'key' => 'footer_badges',
        ) );
        ?>
									</div>
								</div>
							</div>

							<div class="drbu-card">
								<div class="drbu-card-header">
									<h3><?php 
        echo esc_html__( 'Buttons & Labels (CTA & Texts)', 'drbu-discount-rules-box-for-woocommerce' );
        ?></h3>
									<p><?php 
        echo esc_html__( 'Available placeholders: {price}, {save}, {qty}, {unit_price}', 'drbu-discount-rules-box-for-woocommerce' );
        ?></p>
								</div>
								<div class="drbu-card-body">
									<div class="drbu-form-grid-2">
										<div class="drbu-form-row">
											<label class="drbu-label"><?php 
        echo esc_html__( 'CTA Button — 1 piece', 'drbu-discount-rules-box-for-woocommerce' );
        ?></label>
											<?php 
        $this->render_string_field( array(
            'key' => 'cta1',
        ) );
        ?>
										</div>
										<div class="drbu-form-row">
											<label class="drbu-label"><?php 
        echo esc_html__( 'CTA Button — 2 pieces', 'drbu-discount-rules-box-for-woocommerce' );
        ?></label>
											<?php 
        $this->render_string_field( array(
            'key' => 'cta2',
        ) );
        ?>
										</div>
										<div class="drbu-form-row">
											<label class="drbu-label"><?php 
        echo esc_html__( 'CTA Button — 3 pieces', 'drbu-discount-rules-box-for-woocommerce' );
        ?></label>
											<?php 
        $this->render_string_field( array(
            'key' => 'cta3',
        ) );
        ?>
										</div>
										<div class="drbu-form-row">
											<label class="drbu-label"><?php 
        echo esc_html__( '"Best Value" badge text', 'drbu-discount-rules-box-for-woocommerce' );
        ?></label>
											<?php 
        $this->render_string_field( array(
            'key' => 'best_label',
        ) );
        ?>
										</div>
										<div class="drbu-form-row">
											<label class="drbu-label"><?php 
        echo esc_html__( '"In stock" / Urgency badge text', 'drbu-discount-rules-box-for-woocommerce' );
        ?></label>
											<?php 
        $this->render_string_field( array(
            'key'         => 'in_stock_label',
            'description' => __( 'Custom stock or urgency text. E.g: "In stock", "Only 7 left in stock", "Još 7 na stanju", "Hurry, 3 items remaining".', 'drbu-discount-rules-box-for-woocommerce' ),
        ) );
        ?>
										</div>
										<div class="drbu-form-row">
											<label class="drbu-label"><?php 
        echo esc_html__( 'Word for "savings"', 'drbu-discount-rules-box-for-woocommerce' );
        ?></label>
											<?php 
        $this->render_string_field( array(
            'key' => 'savings_label',
        ) );
        ?>
										</div>
										<div class="drbu-form-row">
											<label class="drbu-label"><?php 
        echo esc_html__( 'Free shipping included text', 'drbu-discount-rules-box-for-woocommerce' );
        ?></label>
											<?php 
        $this->render_string_field( array(
            'key' => 'ship_free_text',
        ) );
        ?>
										</div>
										<div class="drbu-form-row">
											<label class="drbu-label"><?php 
        echo esc_html__( 'Free shipping prefix text', 'drbu-discount-rules-box-for-woocommerce' );
        ?></label>
											<?php 
        $this->render_string_field( array(
            'key' => 'ship_paid_prefix',
        ) );
        ?>
										</div>
										<div class="drbu-form-row">
											<label class="drbu-label"><?php 
        echo esc_html__( 'Free shipping badge text', 'drbu-discount-rules-box-for-woocommerce' );
        ?></label>
											<?php 
        $this->render_string_field( array(
            'key' => 'free_ship_flag',
        ) );
        ?>
										</div>
										<div class="drbu-form-row">
											<label class="drbu-label"><?php 
        echo esc_html__( 'Label for "per unit"', 'drbu-discount-rules-box-for-woocommerce' );
        ?></label>
											<?php 
        $this->render_string_field( array(
            'key' => 'per_unit_label',
        ) );
        ?>
										</div>
										<div class="drbu-form-row">
											<label class="drbu-label"><?php 
        echo esc_html__( 'Label for "total"', 'drbu-discount-rules-box-for-woocommerce' );
        ?></label>
											<?php 
        $this->render_string_field( array(
            'key' => 'total_label',
        ) );
        ?>
										</div>
										<div class="drbu-form-row">
											<label class="drbu-label"><?php 
        echo esc_html__( 'Pack total text in summary', 'drbu-discount-rules-box-for-woocommerce' );
        ?></label>
											<?php 
        $this->render_string_field( array(
            'key' => 'pack_total_label',
        ) );
        ?>
										</div>
										<div class="drbu-form-row">
											<label class="drbu-label"><?php 
        echo esc_html__( 'Pack label in Cart & Checkout', 'drbu-discount-rules-box-for-woocommerce' );
        ?></label>
											<?php 
        $this->render_string_field( array(
            'key'         => 'cart_pack_label',
            'description' => __( 'Text displayed under product title on Cart & Checkout pages. Use placeholder {qty}. E.g: "Pack of {qty} pieces", "Paket od {qty} komada".', 'drbu-discount-rules-box-for-woocommerce' ),
        ) );
        ?>
										</div>
									</div>
								</div>
							</div>
						</div>

						<!-- TAB 5: INTEGRATION -->
						<div class="drbu-tab-panel" id="drbu-tab-integration">
							<div class="drbu-card">
								<div class="drbu-card-header">
									<h3><?php 
        echo esc_html__( 'Product Page Display & Overrides', 'drbu-discount-rules-box-for-woocommerce' );
        ?></h3>
								</div>
								<div class="drbu-card-body">
									<div class="drbu-toggles-list">
										<div class="drbu-toggle-item">
											<div class="drbu-toggle-info">
												<strong><?php 
        echo esc_html__( 'Automatic display', 'drbu-discount-rules-box-for-woocommerce' );
        ?></strong>
												<p><?php 
        echo esc_html__( 'Automatically insert the buy box on simple WooCommerce product pages.', 'drbu-discount-rules-box-for-woocommerce' );
        ?></p>
											</div>
											<label class="drbu-switch">
												<input type="checkbox" name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_auto_insert_product]" value="yes" <?php 
        checked( $this->get( 'drbu_auto_insert_product', 'yes' ), 'yes' );
        ?>>
												<span class="drbu-slider"></span>
											</label>
										</div>

										<div class="drbu-toggle-item">
											<div class="drbu-toggle-info">
												<strong><?php 
        echo esc_html__( 'Replace default "Add to cart" button & price header', 'drbu-discount-rules-box-for-woocommerce' );
        ?></strong>
												<p><?php 
        echo esc_html__( 'Removes standard WooCommerce add-to-cart form and price header, displaying only the Discount Rules Box.', 'drbu-discount-rules-box-for-woocommerce' );
        ?></p>
											</div>
											<label class="drbu-switch">
												<input type="checkbox" name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_replace_add_to_cart]" value="yes" <?php 
        checked( $this->get( 'drbu_replace_add_to_cart', 'yes' ), 'yes' );
        ?>>
												<span class="drbu-slider"></span>
											</label>
										</div>
									</div>

									<hr class="drbu-divider">

									<div class="drbu-form-row">
										<label class="drbu-label">
											<?php 
        echo esc_html__( 'Specific Product Restrictions', 'drbu-discount-rules-box-for-woocommerce' );
        ?>
											<?php 
        if ( !$this->is_pro_active() ) {
            ?>
												<span class="drbu-pro-chip" style="background:#2563eb;color:#fff;padding:2px 8px;border-radius:100px;font-size:10px;font-weight:800;letter-spacing:0.04em;text-transform:uppercase;vertical-align:middle;margin-left:6px;">🔒 <?php 
            echo esc_html__( 'Pro', 'drbu-discount-rules-box-for-woocommerce' );
            ?></span>
											<?php 
        }
        ?>
										</label>
										<?php 
        $this->render_auto_insert_product_ids();
        ?>
									</div>

									<div class="drbu-form-row" style="margin-top: 20px;">
										<label class="drbu-label">
											<?php 
        echo esc_html__( 'Category Restrictions', 'drbu-discount-rules-box-for-woocommerce' );
        ?>
											<?php 
        if ( !$this->is_pro_active() ) {
            ?>
												<span class="drbu-pro-chip" style="background:#2563eb;color:#fff;padding:2px 8px;border-radius:100px;font-size:10px;font-weight:800;letter-spacing:0.04em;text-transform:uppercase;vertical-align:middle;margin-left:6px;">🔒 <?php 
            echo esc_html__( 'Pro', 'drbu-discount-rules-box-for-woocommerce' );
            ?></span>
											<?php 
        }
        ?>
										</label>
										<?php 
        $this->render_auto_insert_category_ids();
        ?>
									</div>
								</div>
							</div>
						</div>

						<!-- TAB 6: LICENSE -->
						<div class="drbu-tab-panel" id="drbu-tab-license">
							<div class="drbu-card">
								<div class="drbu-card-header">
									<h3><?php 
        echo esc_html__( 'License Status', 'drbu-discount-rules-box-for-woocommerce' );
        ?></h3>
									<p><?php 
        echo esc_html__( 'Your Freemius license status, current plan and quick access to account management.', 'drbu-discount-rules-box-for-woocommerce' );
        ?></p>
								</div>
								<div class="drbu-card-body">
									<?php 
        $this->render_license_status();
        ?>
								</div>
							</div>
						</div>

						<!-- TAB 7: ACCOUNT -->
						<div class="drbu-tab-panel" id="drbu-tab-account">
							<div class="drbu-card">
								<div class="drbu-card-header">
									<h3><?php 
        echo esc_html__( 'Your Account', 'drbu-discount-rules-box-for-woocommerce' );
        ?></h3>
									<p><?php 
        echo esc_html__( 'Billing, payment method, invoices and site management for your Freemius account.', 'drbu-discount-rules-box-for-woocommerce' );
        ?></p>
								</div>
								<div class="drbu-card-body">
									<?php 
        $this->render_account_tab();
        ?>
								</div>
							</div>
						</div>

						<!-- TAB 8: UPGRADE -->
						<div class="drbu-tab-panel" id="drbu-tab-upgrade">
							<div class="drbu-card">
								<div class="drbu-card-header">
									<h3><?php 
        echo esc_html__( 'Unlock the full Pro feature set', 'drbu-discount-rules-box-for-woocommerce' );
        ?></h3>
									<p>
										<?php 
        if ( $this->is_pro_active() ) {
            $license_status = DRBU_License::instance()->get_status();
            if ( 'trial' === $license_status ) {
                echo esc_html__( "You're on the 30-day free Pro trial — every Pro feature below is already unlocked.", 'drbu-discount-rules-box-for-woocommerce' );
            } else {
                echo esc_html__( 'Your Pro license is active. Thank you for supporting the plugin!', 'drbu-discount-rules-box-for-woocommerce' );
            }
        } else {
            echo esc_html__( 'Pick a plan below, complete secure checkout, and your license key arrives by email in seconds — no separate download step needed.', 'drbu-discount-rules-box-for-woocommerce' );
        }
        ?>
									</p>
								</div>
								<div class="drbu-card-body">
									<?php 
        $this->render_upgrade_tab();
        ?>
								</div>
							</div>
						</div>
					</div>

					<div class="drbu-footer-bar">
						<?php 
        submit_button(
            __( 'Save Settings', 'drbu-discount-rules-box-for-woocommerce' ),
            'primary drbu-save-btn',
            'submit',
            false
        );
        ?>
						<span class="drbu-save-hint"><?php 
        echo esc_html__( 'All changes take effect immediately on frontend and shortcode [drbu_tiered_buy_box].', 'drbu-discount-rules-box-for-woocommerce' );
        ?></span>
					</div>
				</div>

				<!-- RIGHT SIDE: STICKY REAL-TIME LIVE PREVIEW -->
				<div class="drbu-dashboard-preview">
					<div class="drbu-preview-sticky">
						<div class="drbu-preview-header">
							<div class="drbu-preview-title">
								<span class="drbu-live-dot"></span>
								<strong><?php 
        echo esc_html__( 'Live Preview', 'drbu-discount-rules-box-for-woocommerce' );
        ?></strong>
							</div>
							<div class="drbu-preview-controls">
								<div class="drbu-view-toggle">
									<button type="button" class="active" data-view="desktop" title="Desktop View">
										<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="3" width="20" height="14" rx="2"></rect><line x1="8" y1="21" x2="16" y2="21"></line><line x1="12" y1="17" x2="12" y2="21"></line></svg>
									</button>
									<button type="button" data-view="mobile" title="Mobile View">
										<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="5" y="2" width="14" height="20" rx="2"></rect><line x1="12" y1="18" x2="12.01" y2="18"></line></svg>
									</button>
								</div>
							</div>
						</div>

						<div class="drbu-preview-viewport" id="drbu-preview-viewport">
							<div class="drbu-mock-product-card">
								<div class="drbu-mock-badge"><?php 
        echo esc_html__( 'Product Page Preview', 'drbu-discount-rules-box-for-woocommerce' );
        ?></div>
								
								<!-- DRBU LIVE PREVIEW CONTAINER -->
								<div id="drbu-live-preview-box">
									<!-- Rendered in real-time by discount-rules-box-upsell-admin.js -->
								</div>
							</div>
						</div>

						<div class="drbu-preview-footer">
							<button type="button" id="drbu-reset-defaults-btn" class="drbu-reset-btn" title="<?php 
        echo esc_attr__( 'Reset all parameters and styles to factory default settings', 'drbu-discount-rules-box-for-woocommerce' );
        ?>">
								<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"></path><path d="M3 3v5h5"></path></svg>
								<span><?php 
        echo esc_html__( 'Reset All Parameters to Default', 'drbu-discount-rules-box-for-woocommerce' );
        ?></span>
							</button>
						</div>
					</div>
				</div>
			</form>
		</div>
		<?php 
    }

    /**
     * Renderuje uvodni tekst za sekciju nivoa.
     */
    public function render_tiers_intro() {
        echo '<p class="drbu-section-intro">' . esc_html__( 'Choose 2 or 3 packaging tiers, then set the quantity, name, note and discount for each tier.', 'drbu-discount-rules-box-for-woocommerce' ) . '</p>';
    }

    /**
     * Renderuje uvodni tekst za sekciju opcija prikaza.
     */
    public function render_display_options_intro() {
        echo '<p class="drbu-section-intro">' . esc_html__( 'Choose which elements of the buy box are visible on the product page.', 'drbu-discount-rules-box-for-woocommerce' ) . '</p>';
    }

    /**
     * Renderuje uvodni tekst za sekciju tekstova.
     */
    public function render_strings_intro() {
        echo '<p class="drbu-section-intro">' . esc_html__( 'Available placeholders: {price}, {save}, {qty}, {unit_price}, {d2}, {d3}.', 'drbu-discount-rules-box-for-woocommerce' ) . '</p>';
    }

    /**
     * Renderuje uvodni tekst za sekciju prikaza na strani proizvoda.
     */
    public function render_display_intro() {
        echo '<p class="drbu-section-intro">' . esc_html__( 'The buy box is automatically inserted on simple product pages.', 'drbu-discount-rules-box-for-woocommerce' ) . '</p>';
    }

    /**
     * Renderuje uvodni tekst za sekciju izgleda.
     */
    public function render_appearance_intro() {
        echo '<p class="drbu-section-intro">' . esc_html__( 'Colors apply to the buy box on the frontend.', 'drbu-discount-rules-box-for-woocommerce' ) . '</p>';
    }

    /**
     * Renderuje izbor broja nivoa pakovanja (2 ili 3).
     */
    /**
     * Renderuje izbor broja nivoa pakovanja (2 ili 3).
     */
    public function render_tier_count() {
        $current = (int) $this->get( 'drbu_tier_count', 3 );
        ?>
		<select name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_tier_count]" id="drbu_tier_count_select">
			<option value="2" <?php 
        selected( $current, 2 );
        ?>><?php 
        echo esc_html__( '2 Tiers', 'drbu-discount-rules-box-for-woocommerce' );
        ?></option>
			<option value="3" <?php 
        selected( $current, 3 );
        ?>><?php 
        echo esc_html__( '3 Tiers', 'drbu-discount-rules-box-for-woocommerce' );
        ?></option>
		</select>
		<?php 
    }

    /**
     * Renderuje redove nivoa pakovanja. Renderujemo sva 3 nivoa tako da se 3. po potrebi sakriva/prikazuje.
     */
    public function render_tier_rows() {
        $tiers = $this->tiers();
        $show_best = 'yes' === $this->get( 'drbu_enable_best_value', 'yes' );
        $pricing_model = $this->get( 'drbu_pricing_model', 'model_a' );
        ?>
		<div class="drbu-discount-logic-box" style="background:#eff6ff; border:1px solid #bfdbfe; border-left:4px solid #0070ba; border-radius:8px; padding:14px 18px; margin-bottom:16px; font-size:13.5px; line-height:1.5; color:#1e3a8a;">
			<div style="display:flex; align-items:center; gap:8px; margin-bottom:6px; font-weight:700; font-size:14.5px; color:#1e40af;">
				<span style="font-size:18px;">💡</span> <span id="drbu-logic-title"><?php 
        echo esc_html__( 'How Pricing Strategy & Calculation Works:', 'drbu-discount-rules-box-for-woocommerce' );
        ?></span>
			</div>
			<ul id="drbu-logic-list" style="margin:4px 0 0 20px; padding:0; list-style-type:disc; color:#1e3a8a;">
				<?php 
        if ( 'model_b' === $pricing_model ) {
            ?>
					<li><strong><?php 
            echo esc_html__( 'Model B — Discount on Entire Quantity:', 'drbu-discount-rules-box-for-woocommerce' );
            ?></strong> <?php 
            echo esc_html__( 'Discount entered applies across ALL items in the bundle (e.g. 2 pcs at 40% off = $21.60 total).', 'drbu-discount-rules-box-for-woocommerce' );
            ?></li>
				<?php 
        } elseif ( 'model_c' === $pricing_model ) {
            ?>
					<li><strong><?php 
            echo esc_html__( 'Model C — Fixed Total Bundle Price:', 'drbu-discount-rules-box-for-woocommerce' );
            ?></strong> <?php 
            echo esc_html__( 'The value entered is the exact fixed total price for the entire pack (e.g. Tier 1 = $18.00, Tier 2 = $28.80, Tier 3 = $39.99).', 'drbu-discount-rules-box-for-woocommerce' );
            ?></li>
				<?php 
        } elseif ( 'model_d' === $pricing_model ) {
            ?>
					<li><strong><?php 
            echo esc_html__( 'Model D — Fixed Price Per Unit:', 'drbu-discount-rules-box-for-woocommerce' );
            ?></strong> <?php 
            echo esc_html__( 'The value entered is the exact fixed price per single item for each tier (e.g. Tier 2 = $14.40/unit -> $28.80 total).', 'drbu-discount-rules-box-for-woocommerce' );
            ?></li>
				<?php 
        } else {
            ?>
					<li><strong><?php 
            echo esc_html__( 'Tier 1 (1 piece):', 'drbu-discount-rules-box-for-woocommerce' );
            ?></strong> <?php 
            echo esc_html__( 'Customer pays full regular price (0% discount).', 'drbu-discount-rules-box-for-woocommerce' );
            ?></li>
					<li><strong><?php 
            echo esc_html__( 'Tier 2 (2 pieces):', 'drbu-discount-rules-box-for-woocommerce' );
            ?></strong> <?php 
            echo esc_html__( 'The discount entered (e.g. 40%) applies to the SECOND item in the pack.', 'drbu-discount-rules-box-for-woocommerce' );
            ?></li>
					<li><strong><?php 
            echo esc_html__( 'Tier 3 (3 pieces):', 'drbu-discount-rules-box-for-woocommerce' );
            ?></strong> <?php 
            echo esc_html__( 'The discount entered (e.g. 25%) applies to the THIRD item in the pack.', 'drbu-discount-rules-box-for-woocommerce' );
            ?></li>
				<?php 
        }
        ?>
			</ul>
		</div>

		<div class="drbu-tiers-table-wrapper">
			<table class="widefat drbu-tiers-table" role="presentation">
				<thead>
					<tr>
						<th><?php 
        echo esc_html__( 'Tier', 'drbu-discount-rules-box-for-woocommerce' );
        ?></th>
						<th><?php 
        echo esc_html__( 'Quantity (pcs)', 'drbu-discount-rules-box-for-woocommerce' );
        ?></th>
						<th id="drbu-discount-col-header">
							<?php 
        if ( 'model_b' === $pricing_model ) {
            echo esc_html__( 'Discount on ALL Items (% or $)', 'drbu-discount-rules-box-for-woocommerce' );
        } elseif ( 'model_c' === $pricing_model ) {
            echo esc_html__( 'Fixed Package Price ($ / RSD)', 'drbu-discount-rules-box-for-woocommerce' );
        } elseif ( 'model_d' === $pricing_model ) {
            echo esc_html__( 'Fixed Price Per Unit ($ / RSD)', 'drbu-discount-rules-box-for-woocommerce' );
        } else {
            echo esc_html__( 'Discount on Additional Item (% or $)', 'drbu-discount-rules-box-for-woocommerce' );
        }
        ?>
						</th>
					</tr>
				</thead>
				<tbody>
					<?php 
        for ($i = 0; $i < 2; $i++) {
            ?>
						<?php 
            $this->render_tier_row( $i, $tiers, $show_best );
            ?>
					<?php 
        }
        ?>
					<?php 
        if ( function_exists( 'drbu_fs' ) && drbu_fs() && drbu_fs()->is__premium_only() ) {
            ?>
						<?php 
            $this->render_tier_row__premium_only( $tiers, $show_best );
            ?>
					<?php 
        }
        ?>
				</tbody>
			</table>
		</div>
		<p class="description" style="margin-top:10px;"><?php 
        echo esc_html__( '💡 Note: Package Titles and Notes are configured in Step 4 (Texts & Badges) for easy translation.', 'drbu-discount-rules-box-for-woocommerce' );
        ?></p>
		<?php 
    }

    /**
     * Renderuje jedan red tabele nivoa (qty + popust unos).
     *
     * @param int   $i         Indeks nivoa (0-based).
     * @param array $tiers     Svi nivoi.
     * @param bool  $show_best Da li se prikazuje "best value" bedž.
     */
    private function render_tier_row( $i, $tiers, $show_best ) {
        $tier = ( isset( $tiers[$i] ) ? $tiers[$i] : array() );
        $tqty = ( isset( $tier['qty'] ) ? (int) $tier['qty'] : $i + 1 );
        $disc = ( isset( $tier['discount'] ) ? $tier['discount'] : 0 );
        $is_best = (int) $this->get( 'drbu_best_value_index' ) === $i + 1;
        ?>
		<tr class="drbu-tier-row drbu-tier-row-<?php 
        echo esc_attr( $i + 1 );
        ?>" data-tier-index="<?php 
        echo esc_attr( $i + 1 );
        ?>">
			<td>
				<strong><?php 
        echo esc_html( $i + 1 );
        ?></strong>
				<?php 
        if ( $is_best && $show_best ) {
            ?>
					<span class="drbu-badge"><?php 
            echo esc_html__( 'Best value', 'drbu-discount-rules-box-for-woocommerce' );
            ?></span>
				<?php 
        }
        ?>
			</td>
			<td>
				<input type="number" min="1" step="1" class="small-text drbu-tier-input-qty"
					name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_tiers][<?php 
        echo esc_attr( $i );
        ?>][qty]"
					value="<?php 
        echo esc_attr( $tqty );
        ?>">
			</td>
			<td>
				<input type="number" min="0" step="any" class="small-text drbu-tier-input-discount"
					name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_tiers][<?php 
        echo esc_attr( $i );
        ?>][discount]"
					value="<?php 
        echo esc_attr( $disc );
        ?>">
			</td>
		</tr>
		<?php 
    }

    /**
     * Renderuje select za model popusta.
     */
    public function render_discount_type() {
        $current = $this->get( 'drbu_discount_type', 'percentage' );
        ?>
		<select name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_discount_type]" id="drbu_discount_type" class="drbu-select">
			<option value="percentage" <?php 
        selected( $current, 'percentage' );
        ?>><?php 
        echo esc_html__( 'Percentage (%) on additional pieces', 'drbu-discount-rules-box-for-woocommerce' );
        ?></option>
			<option value="fixed" <?php 
        selected( $current, 'fixed' );
        ?>><?php 
        echo esc_html__( 'Fixed discount per piece', 'drbu-discount-rules-box-for-woocommerce' );
        ?></option>
		</select>
		<?php 
    }

    /**
     * Renderuje broj nivoa sa oznakom "najbolja vrednost".
     */
    public function render_best_value_index() {
        $count = max( 2, min( 3, (int) $this->get( 'drbu_tier_count', 3 ) ) );
        $current = max( 1, min( $count, (int) $this->get( 'drbu_best_value_index', 2 ) ) );
        ?>
		<input type="number" min="1" max="3" step="1" class="small-text" id="drbu_best_value_index"
			name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_best_value_index]"
			value="<?php 
        echo esc_attr( $current );
        ?>">
		<?php 
    }

    /**
     * Renderuje toggle prekidač (checkbox) sa opisom.
     */
    public function render_toggle( $args ) {
        $key = ( isset( $args['key'] ) ? $args['key'] : '' );
        $description = ( isset( $args['description'] ) ? $args['description'] : '' );
        $current = $this->get( $key, 'yes' );
        ?>
		<label class="drbu-switch">
			<input type="checkbox" name="<?php 
        echo esc_attr( self::OPTION );
        ?>[<?php 
        echo esc_attr( $key );
        ?>]" value="yes" <?php 
        checked( $current, 'yes' );
        ?>>
			<span class="drbu-slider"></span>
		</label>
		<?php 
        if ( $description ) {
            ?>
			<p class="description"><?php 
            echo esc_html( $description );
            ?></p>
		<?php 
        }
        ?>
		<?php 
    }

    /**
     * Renderuje prag za besplatnu dostavu.
     */
    public function render_free_ship_threshold() {
        $current = $this->get( 'drbu_free_ship_threshold', 0 );
        ?>
		<input type="number" min="0" step="any" class="regular-text" id="drbu_free_ship_threshold"
			name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_free_ship_threshold]"
			value="<?php 
        echo esc_attr( $current );
        ?>">
		<p class="description"><?php 
        echo esc_html__( 'Threshold amount for free shipping callout in the buy box. If 0, free shipping is always shown. (Note: Also configure Free Shipping in WooCommerce > Settings > Shipping to enable free shipping at checkout).', 'drbu-discount-rules-box-for-woocommerce' );
        ?></p>
		<?php 
    }

    /**
     * Renderuje način prikaza valute.
     */
    public function render_currency_display() {
        $current = $this->get( 'drbu_currency_display', 'default' );
        ?>
		<select name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_currency_display]" class="drbu-select">
			<option value="default" <?php 
        selected( $current, 'default' );
        ?>><?php 
        echo esc_html__( 'Default (e.g. $1,200.00)', 'drbu-discount-rules-box-for-woocommerce' );
        ?></option>
			<option value="hide_zeros" <?php 
        selected( $current, 'hide_zeros' );
        ?>><?php 
        echo esc_html__( 'No decimals (e.g. $1,200)', 'drbu-discount-rules-box-for-woocommerce' );
        ?></option>
		</select>
		<?php 
    }

    /**
     * Renderuje checkbox za automatski prikaz.
     */
    public function render_auto_insert_product() {
        $current = $this->get( 'drbu_auto_insert_product', 'yes' );
        ?>
		<label>
			<input type="checkbox" name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_auto_insert_product]" value="yes" <?php 
        checked( $current, 'yes' );
        ?>>
			<?php 
        echo esc_html__( 'Automatically display the buy box on simple product pages.', 'drbu-discount-rules-box-for-woocommerce' );
        ?>
		</label>
		<?php 
    }

    /**
     * Renderuje pretragu i izbor proizvoda za ograničenje prikaza. Free: samo
     * statički upsell (bez funkcionalnog input/pretraga markupa). Pro: prava
     * implementacija u render_auto_insert_product_ids__premium_only().
     */
    public function render_auto_insert_product_ids() {
        if ( !(function_exists( 'drbu_fs' ) && drbu_fs() && drbu_fs()->is__premium_only()) ) {
            ?>
			<p class="description" style="margin-top:0;">
				🔒 <?php 
            echo esc_html__( 'Product restrictions are a Pro feature. Upgrade or start the 30-day Free Trial to target specific products.', 'drbu-discount-rules-box-for-woocommerce' );
            ?>
				<?php 
            $prod_cta = $this->get_pro_url( __( 'Start Free Trial', 'drbu-discount-rules-box-for-woocommerce' ) );
            ?>
				<a href="<?php 
            echo esc_url( $prod_cta['url'] );
            ?>" style="font-weight:700; text-decoration:underline; margin-left:4px;"><?php 
            echo esc_html( $prod_cta['label'] );
            ?></a>
			</p>
			<?php 
            return;
        }
        $this->render_auto_insert_product_ids__premium_only();
    }

    /**
     * Renderuje izbor kategorija proizvoda za ograničenje prikaza. Free: samo
     * statički upsell. Pro: prava implementacija u
     * render_auto_insert_category_ids__premium_only().
     */
    public function render_auto_insert_category_ids() {
        if ( !(function_exists( 'drbu_fs' ) && drbu_fs() && drbu_fs()->is__premium_only()) ) {
            ?>
			<p class="description" style="margin-top:0;">
				🔒 <?php 
            echo esc_html__( 'Category restrictions are a Pro feature. Upgrade or start the 30-day Free Trial to target specific product categories.', 'drbu-discount-rules-box-for-woocommerce' );
            ?>
				<?php 
            $cat_cta = $this->get_pro_url( __( 'Start Free Trial', 'drbu-discount-rules-box-for-woocommerce' ) );
            ?>
				<a href="<?php 
            echo esc_url( $cat_cta['url'] );
            ?>" style="font-weight:700; text-decoration:underline; margin-left:4px;"><?php 
            echo esc_html( $cat_cta['label'] );
            ?></a>
			</p>
			<?php 
            return;
        }
        $this->render_auto_insert_category_ids__premium_only();
    }

    /**
     * AJAX pretraga proizvoda po nazivu i ID-ju (backend za restriction
     * picker, Pro-only). Registracija akcije ostaje u Free build-u (mora,
     * jer add_action() sam po sebi ne "curi" nikakvu logiku), ali stvarna
     * pretraga je izdvojena u ajax_search_products__premium_only() koju
     * Freemius Deployment izbacuje iz Free ZIP-a.
     */
    public function ajax_search_products() {
        check_ajax_referer( 'drbu_admin_nonce', 'security' );
        if ( !current_user_can( self::CAPABILITY ) ) {
            wp_send_json_error( 'Permission denied' );
        }
        if ( !(function_exists( 'drbu_fs' ) && drbu_fs() && drbu_fs()->is__premium_only()) ) {
            wp_send_json_error( 'Pro feature' );
        }
        $this->ajax_search_products__premium_only();
    }

    /**
     * AJAX: forsira PRAVU Freemius sinhronizaciju za ovaj sajt i osvežava
     * lokalni keš. Koristi je i syncAndReload() posle trial/checkout-a i
     * (ako je pozvan direktno) dugme "Sync License Now" na License tabu.
     *
     * VAŽNA NAPOMENA (ispravljen bug): Freemius SDK nema javnu metodu
     * `sync_license()` — samo `_sync_license()` (private, ne može se pozvati
     * spolja bez fatalne greške). Prethodna verzija ovog handlera je pozivala
     * nepostojeću `sync_license()` iza `method_exists()` provere koja je
     * uvek bila false, pa se stvarna sinhronizacija NIKAD nije dešavala —
     * samo se ovaj lokalni keš (i "Last sync" prikaz) kozmetički osvežavao,
     * dok je Freemius status ostajao "Free" i posle uspešnog trial-a/kupovine.
     *
     * Stvarni javni ulaz je `Freemius::_sync_cron()` — ista sinhrona logika
     * koju SDK inače sam pokreće preko svog ~24h wp-cron job-a (interno zove
     * privatnu `_sync_license()`), pa je bezbedna za direktan poziv i van
     * admin konteksta. Ranije se stvarna sinhronizacija oslanjala isključivo
     * na to da JS (initFreemiusCheckout → syncAndReload) prvo odradi fetch
     * na `drbuAdminData.fs_sync_license_url` PRE ovog poziva — sad ovaj
     * endpoint sam radi pravi sync, pa je samodovoljan i za pozive koji tu
     * fetch putanju ne prolaze (npr. ručno dugme).
     */
    public function ajax_sync_freemius_license() {
        check_ajax_referer( 'drbu_admin_nonce', 'security' );
        if ( !current_user_can( self::CAPABILITY ) ) {
            wp_send_json_error();
        }
        if ( function_exists( 'drbu_fs' ) && drbu_fs() && method_exists( drbu_fs(), '_sync_cron' ) ) {
            drbu_fs()->_sync_cron();
        }
        if ( function_exists( 'drbu_license' ) ) {
            drbu_license()->refresh_cache();
        }
        $is_pro_active = ( function_exists( 'drbu_is_pro_active' ) ? drbu_is_pro_active() : false );
        // Ova AJAX komanda se poziva ISKLJUČIVO iz initFreemiusCheckout() →
        // syncAndReload(), tik pre window.location.reload() posle uspešnog
        // trial-a/kupovine kroz Freemius Checkout overlay. Overlay se sam
        // zatvara i reload odmah briše svaku poruku koju je korisnik mogao
        // da vidi, pa ovde upisujemo tranzijent koji checkout_result_notice()
        // čita i prikazuje na SLEDEĆEM (već reload-ovanom) učitavanju stranice.
        $user_id = get_current_user_id();
        if ( $user_id ) {
            set_transient( 'drbu_checkout_result_' . $user_id, ( $is_pro_active ? 'active' : 'pending' ), 5 * MINUTE_IN_SECONDS );
        }
        wp_send_json_success( array(
            'is_pro_active' => $is_pro_active,
        ) );
    }

    /**
     * Admin notifikacija posle Freemius Checkout trial/kupovine (vidi
     * ajax_sync_freemius_license() iznad) — pokazuje se JEDNOM, na prvom
     * učitavanju stranice posle syncAndReload() reload-a, pa se tranzijent
     * briše.
     */
    public function checkout_result_notice() {
        $user_id = get_current_user_id();
        if ( !$user_id || !current_user_can( self::CAPABILITY ) ) {
            return;
        }
        $result = get_transient( 'drbu_checkout_result_' . $user_id );
        if ( !$result ) {
            return;
        }
        delete_transient( 'drbu_checkout_result_' . $user_id );
        if ( 'active' === $result ) {
            ?>
			<div class="notice notice-success is-dismissible">
				<p>
					<strong>🎉 <?php 
            echo esc_html__( 'Your 30-day Pro trial has started and was activated automatically on this site — enjoy!', 'drbu-discount-rules-box-for-woocommerce' );
            ?></strong>
				</p>
			</div>
			<?php 
            return;
        }
        $license_url = admin_url( 'admin.php?page=' . self::MENU_SLUG . '&tab=license' );
        ?>
		<div class="notice notice-warning is-dismissible">
			<p>
				<strong>📧 <?php 
        echo esc_html__( 'Your trial was created, but this site was not activated automatically.', 'drbu-discount-rules-box-for-woocommerce' );
        ?></strong>
				<?php 
        printf( 
            /* translators: %s: URL of the License settings tab */
            esc_html__( 'Check your email for the license key from Freemius, then go to the %s tab and paste it into "Have a License Key?" to activate Pro.', 'drbu-discount-rules-box-for-woocommerce' ),
            '<a href="' . esc_url( $license_url ) . '"><strong>' . esc_html__( 'License', 'drbu-discount-rules-box-for-woocommerce' ) . '</strong></a>'
         );
        ?>
			</p>
		</div>
		<?php 
    }

    /**
     * Renderuje checkbox za zamenu default add-to-cart dugmeta.
     */
    public function render_replace_add_to_cart() {
        $current = $this->get( 'drbu_replace_add_to_cart', 'yes' );
        ?>
		<label>
			<input type="checkbox" name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_replace_add_to_cart]" value="yes" <?php 
        checked( $current, 'yes' );
        ?>>
			<?php 
        echo esc_html__( 'Remove default WooCommerce "Add to cart" button.', 'drbu-discount-rules-box-for-woocommerce' );
        ?>
		</label>
		<?php 
    }

    /**
     * Renderuje checkbox za skrivanje default WooCommerce cene.
     */
    public function render_hide_default_price() {
        $current = $this->get( 'drbu_hide_default_price', 'no' );
        ?>
		<label>
			<input type="checkbox" name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_hide_default_price]" value="yes" <?php 
        checked( $current, 'yes' );
        ?>>
			<?php 
        echo esc_html__( 'Hide standard price from product header when buy box is active.', 'drbu-discount-rules-box-for-woocommerce' );
        ?>
		</label>
		<?php 
    }

    /**
     * Renderuje color picker polje.
     */
    public function render_color_field( $args ) {
        $key = ( isset( $args['key'] ) ? $args['key'] : '' );
        $defaults = $this->defaults();
        $value = $this->get( $key );
        if ( !is_string( $value ) || !preg_match( '/^#[0-9a-fA-F]{6}$/', $value ) ) {
            $value = ( isset( $defaults[$key] ) ? $defaults[$key] : '#c49186' );
        }
        $value_hex = strtoupper( $value );
        ?>
		<div class="drbu-color-picker-wrap" style="display:inline-flex; align-items:center; gap:8px;">
			<input type="color" value="<?php 
        echo esc_attr( $value );
        ?>" data-target="#<?php 
        echo esc_attr( $key );
        ?>" class="drbu-color-picker-swatch" style="width:36px; height:36px; padding:2px; border:1px solid #cbd5e1; border-radius:6px; cursor:pointer; background:#ffffff;">
			<input type="text" name="<?php 
        echo esc_attr( self::OPTION . '[' . $key . ']' );
        ?>" value="<?php 
        echo esc_attr( $value_hex );
        ?>" id="<?php 
        echo esc_attr( $key );
        ?>" class="drbu-hex-input regular-text" placeholder="#0070BA" maxlength="7" style="width:110px; font-family:monospace; font-weight:700; text-transform:uppercase; font-size:13px; text-align:center;">
		</div>
		<?php 
    }

    /**
     * Renderuje tekstualno polje iz grupe drbu_strings.
     */
    public function render_string_field( $args ) {
        $key = ( isset( $args['key'] ) ? $args['key'] : '' );
        $strings = $this->strings();
        $value = ( isset( $strings[$key] ) ? $strings[$key] : '' );
        $name = self::OPTION . '[drbu_strings][' . $key . ']';
        if ( 'footer_badges' === $key ) {
            ?>
			<textarea rows="4" class="large-text drbu-badge-textarea" id="drbu_footer_badges"
				name="<?php 
            echo esc_attr( $name );
            ?>"><?php 
            echo esc_textarea( $value );
            ?></textarea>
			<p class="description"><?php 
            echo esc_html__( 'One trust badge per line. E.g: "Shipping 1–3 days", "Cash on delivery", "Money-back guarantee".', 'drbu-discount-rules-box-for-woocommerce' );
            ?></p>
			<?php 
            return;
        }
        $desc = ( isset( $args['description'] ) ? $args['description'] : '' );
        ?>
		<input type="text" class="large-text drbu-string-input" data-string-key="<?php 
        echo esc_attr( $key );
        ?>"
			name="<?php 
        echo esc_attr( $name );
        ?>"
			value="<?php 
        echo esc_attr( $value );
        ?>">
		<?php 
        if ( !empty( $desc ) ) {
            ?>
			<p class="description"><?php 
            echo esc_html( $desc );
            ?></p>
		<?php 
        }
        ?>
		<?php 
    }

    /**
     * Sanitizacija celokupnog input-a iz forme.
     */
    public function sanitize( $input ) {
        $defaults = $this->defaults();
        $input = ( is_array( $input ) ? $input : array() );
        $clean = array();
        $clean['drbu_tier_count'] = ( isset( $input['drbu_tier_count'] ) && 2 === (int) $input['drbu_tier_count'] ? 2 : 3 );
        $tier_count = $clean['drbu_tier_count'];
        $clean['drbu_discount_type'] = ( isset( $input['drbu_discount_type'] ) && in_array( $input['drbu_discount_type'], array('percentage', 'fixed'), true ) ? $input['drbu_discount_type'] : 'percentage' );
        $clean['drbu_pricing_model'] = ( isset( $input['drbu_pricing_model'] ) && in_array( $input['drbu_pricing_model'], array(
            'model_a',
            'model_b',
            'model_c',
            'model_d'
        ), true ) ? $input['drbu_pricing_model'] : 'model_a' );
        $clean['drbu_best_value_index'] = ( isset( $input['drbu_best_value_index'] ) ? max( 1, min( $tier_count, (int) $input['drbu_best_value_index'] ) ) : max( 1, min( $tier_count, (int) $this->get( 'drbu_best_value_index', 2 ) ) ) );
        $clean['drbu_free_ship_threshold'] = ( isset( $input['drbu_free_ship_threshold'] ) ? max( 0, (float) $input['drbu_free_ship_threshold'] ) : (float) $this->get( 'drbu_free_ship_threshold', 0 ) );
        $clean['drbu_currency_display'] = ( isset( $input['drbu_currency_display'] ) && in_array( $input['drbu_currency_display'], array('default', 'hide_zeros'), true ) ? $input['drbu_currency_display'] : 'default' );
        $clean['drbu_enable_free_shipping'] = ( isset( $input['drbu_enable_free_shipping'] ) && 'yes' === $input['drbu_enable_free_shipping'] ? 'yes' : 'no' );
        $clean['drbu_enable_footer_badges'] = ( isset( $input['drbu_enable_footer_badges'] ) && 'yes' === $input['drbu_enable_footer_badges'] ? 'yes' : 'no' );
        $clean['drbu_enable_savings'] = ( isset( $input['drbu_enable_savings'] ) && 'yes' === $input['drbu_enable_savings'] ? 'yes' : 'no' );
        $clean['drbu_enable_best_value'] = ( isset( $input['drbu_enable_best_value'] ) && 'yes' === $input['drbu_enable_best_value'] ? 'yes' : 'no' );
        $clean['drbu_enable_per_unit'] = ( isset( $input['drbu_enable_per_unit'] ) && 'yes' === $input['drbu_enable_per_unit'] ? 'yes' : 'no' );
        $clean['drbu_enable_was_price'] = ( isset( $input['drbu_enable_was_price'] ) && 'yes' === $input['drbu_enable_was_price'] ? 'yes' : 'no' );
        $clean['drbu_auto_insert_product'] = ( isset( $input['drbu_auto_insert_product'] ) && 'yes' === $input['drbu_auto_insert_product'] ? 'yes' : 'no' );
        $clean['drbu_replace_add_to_cart'] = ( isset( $input['drbu_replace_add_to_cart'] ) && 'yes' === $input['drbu_replace_add_to_cart'] ? 'yes' : 'no' );
        $clean['drbu_hide_default_price'] = ( isset( $input['drbu_hide_default_price'] ) && 'yes' === $input['drbu_hide_default_price'] ? 'yes' : 'no' );
        $clean['drbu_auto_insert_product_ids'] = $this->sanitize_ids( ( isset( $input['drbu_auto_insert_product_ids'] ) ? (string) $input['drbu_auto_insert_product_ids'] : '' ) );
        $clean['drbu_auto_insert_category_ids'] = ( isset( $input['drbu_auto_insert_category_ids'] ) && is_array( $input['drbu_auto_insert_category_ids'] ) ? array_values( array_filter( array_map( 'intval', $input['drbu_auto_insert_category_ids'] ) ) ) : array() );
        $clean['drbu_primary_color'] = $this->sanitize_color( ( isset( $input['drbu_primary_color'] ) ? $input['drbu_primary_color'] : '' ), '#2563eb' );
        $clean['drbu_cta_text_color'] = $this->sanitize_color( ( isset( $input['drbu_cta_text_color'] ) ? $input['drbu_cta_text_color'] : '' ), '#ffffff' );
        $clean['drbu_best_value_color'] = $this->sanitize_color( ( isset( $input['drbu_best_value_color'] ) ? $input['drbu_best_value_color'] : '' ), '#1d4ed8' );
        $clean['drbu_card_bg_color'] = $this->sanitize_color( ( isset( $input['drbu_card_bg_color'] ) ? $input['drbu_card_bg_color'] : '' ), '#f8fafc' );
        $clean['drbu_button_radius'] = ( isset( $input['drbu_button_radius'] ) && in_array( $input['drbu_button_radius'], array(
            '100px',
            '14px',
            '8px',
            '0px'
        ), true ) ? $input['drbu_button_radius'] : '100px' );
        $clean['drbu_card_radius'] = ( isset( $input['drbu_card_radius'] ) && in_array( $input['drbu_card_radius'], array(
            '16px',
            '10px',
            '4px',
            '0px'
        ), true ) ? $input['drbu_card_radius'] : '16px' );
        // Polje se sad uvek renderuje prazno (vidi render_webhook_secret() —
        // stvarna vrednost se nikad ne ispisuje nazad u HTML). Zato prazan
        // submit znači "nisam menjao", ne "obriši" — čuva se postojeća
        // sačuvana vrednost; samo ne-prazan unos je stvarna nova vrednost.
        $clean['drbu_freemius_webhook_secret'] = ( isset( $input['drbu_freemius_webhook_secret'] ) && '' !== trim( (string) $input['drbu_freemius_webhook_secret'] ) ? sanitize_text_field( (string) $input['drbu_freemius_webhook_secret'] ) : (string) $this->get( 'drbu_freemius_webhook_secret', '' ) );
        $current_tiers = $this->tiers();
        $clean['drbu_tiers'] = array();
        $raw_tiers = ( isset( $input['drbu_tiers'] ) && is_array( $input['drbu_tiers'] ) ? $input['drbu_tiers'] : array() );
        for ($i = 0; $i < 3; $i++) {
            $raw = ( isset( $raw_tiers[$i] ) && is_array( $raw_tiers[$i] ) ? $raw_tiers[$i] : array() );
            $current_tier = ( isset( $current_tiers[$i] ) && is_array( $current_tiers[$i] ) ? $current_tiers[$i] : array() );
            $default_label = ( isset( $defaults['drbu_tiers'][$i]['label'] ) ? $defaults['drbu_tiers'][$i]['label'] : '' );
            $default_note = ( isset( $defaults['drbu_tiers'][$i]['note'] ) ? $defaults['drbu_tiers'][$i]['note'] : '' );
            $clean['drbu_tiers'][$i] = array(
                'qty'      => ( isset( $raw['qty'] ) && '' !== $raw['qty'] ? max( 1, (int) $raw['qty'] ) : (( isset( $current_tier['qty'] ) ? (int) $current_tier['qty'] : $i + 1 )) ),
                'label'    => ( isset( $raw['label'] ) && '' !== $raw['label'] ? sanitize_text_field( $raw['label'] ) : (( isset( $current_tier['label'] ) ? $current_tier['label'] : $default_label )) ),
                'note'     => ( isset( $raw['note'] ) && '' !== $raw['note'] ? wp_kses_post( (string) $raw['note'] ) : (( isset( $current_tier['note'] ) ? $current_tier['note'] : $default_note )) ),
                'discount' => ( isset( $raw['discount'] ) && '' !== $raw['discount'] ? max( 0, (float) $raw['discount'] ) : (( isset( $current_tier['discount'] ) ? (float) $current_tier['discount'] : 0 )) ),
            );
        }
        $current_strings = $this->strings();
        $clean['drbu_strings'] = array();
        $text_keys = array(
            'best_label',
            'in_stock_label',
            'per_unit_label',
            'total_label',
            'pack_total_label',
            'savings_label',
            'ship_free_text',
            'ship_paid_prefix',
            'free_ship_flag',
            'cta1',
            'cta2',
            'cta3',
            'cart_pack_label'
        );
        foreach ( $text_keys as $key ) {
            $default_value = ( isset( $defaults['drbu_strings'][$key] ) ? $defaults['drbu_strings'][$key] : '' );
            $current_value = ( isset( $current_strings[$key] ) ? $current_strings[$key] : $default_value );
            $clean['drbu_strings'][$key] = ( isset( $input['drbu_strings'][$key] ) ? sanitize_text_field( (string) $input['drbu_strings'][$key] ) : $current_value );
        }
        $clean['drbu_strings']['footer_badges'] = ( isset( $input['drbu_strings']['footer_badges'] ) ? wp_kses_post( (string) $input['drbu_strings']['footer_badges'] ) : (( isset( $current_strings['footer_badges'] ) ? $current_strings['footer_badges'] : '' )) );
        // NAPOMENA (bezbednost): `drbu_license_key` ovde služi ISKLJUČIVO za
        // prikaz poslednje unete vrednosti u polju — nikad se ne koristi za
        // odlučivanje o Pro statusu. Stvarna aktivacija licence ide preko
        // Freemius AJAX-a (ajax_sync_freemius_license / SDK activate_license),
        // koji stvarno validira ključ na Freemius serveru pre nego što
        // drbu_is_pro_active() ikad vrati true.
        $clean['drbu_license_key'] = ( isset( $input['drbu_license_key'] ) ? sanitize_text_field( trim( (string) $input['drbu_license_key'] ) ) : (string) $this->get( 'drbu_license_key', '' ) );
        // Free korisnik (uključujući istekao trial): Pro opcije se UVEK svode
        // na Free vrednosti, bez obzira na to šta je upisano u polje za
        // license key — samo drbu_is_pro_active() (Freemius) odlučuje.
        if ( !$this->is_pro_active() ) {
            foreach ( $this->pro_free_values() as $pro_key => $pro_value ) {
                $clean[$pro_key] = $pro_value;
            }
            // Indeks "best value" bedža ne sme prelaziti broj aktivnih nivoa (2 u Free-u).
            $clean['drbu_best_value_index'] = max( 1, min( 2, (int) $clean['drbu_best_value_index'] ) );
        }
        return $clean;
    }

    /**
     * Sanitizuje listu ID-jeva razdvojenih zarezom.
     */
    private function sanitize_ids( $raw ) {
        $raw = sanitize_text_field( $raw );
        $raw = str_replace( ' ', '', $raw );
        $ids = array();
        foreach ( explode( ',', $raw ) as $part ) {
            $part = (int) $part;
            if ( $part > 0 ) {
                $ids[] = $part;
            }
        }
        return implode( ',', $ids );
    }

    /**
     * Sanitizuje hex boju sa fallback vrednošću.
     */
    private function sanitize_color( $raw, $default ) {
        $raw = trim( (string) $raw );
        if ( '' !== $raw && '#' !== substr( $raw, 0, 1 ) ) {
            $raw = '#' . $raw;
        }
        $sanitized = sanitize_hex_color( $raw );
        return ( $sanitized ? strtoupper( $sanitized ) : $default );
    }

    /**
     * Podrazumevana podešavanja.
     *
     * @return array
     */
    public function defaults() {
        return array(
            'drbu_tiers'                    => array(array(
                'qty'      => 1,
                'label'    => __( '1 piece', 'drbu-discount-rules-box-for-woocommerce' ),
                'note'     => __( 'Basic packaging', 'drbu-discount-rules-box-for-woocommerce' ),
                'discount' => 0,
            ), array(
                'qty'      => 2,
                'label'    => __( '2 pieces', 'drbu-discount-rules-box-for-woocommerce' ),
                'note'     => __( 'Second item − {d2} · {save}', 'drbu-discount-rules-box-for-woocommerce' ),
                'discount' => 40,
            ), array(
                'qty'      => 3,
                'label'    => __( '3 pieces', 'drbu-discount-rules-box-for-woocommerce' ),
                'note'     => __( 'Third item − {d3} · {save}', 'drbu-discount-rules-box-for-woocommerce' ),
                'discount' => 25,
            )),
            'drbu_discount_type'            => 'percentage',
            'drbu_pricing_model'            => 'model_a',
            'drbu_tier_count'               => ( function_exists( 'drbu_is_pro_active' ) && drbu_is_pro_active() ? 3 : 2 ),
            'drbu_best_value_index'         => 2,
            'drbu_free_ship_threshold'      => 50,
            'drbu_enable_free_shipping'     => ( function_exists( 'drbu_is_pro_active' ) && drbu_is_pro_active() ? 'yes' : 'no' ),
            'drbu_enable_footer_badges'     => 'yes',
            'drbu_enable_savings'           => 'yes',
            'drbu_enable_best_value'        => 'yes',
            'drbu_enable_per_unit'          => 'yes',
            'drbu_enable_was_price'         => 'yes',
            'drbu_auto_insert_product'      => 'yes',
            'drbu_auto_insert_product_ids'  => '',
            'drbu_auto_insert_category_ids' => array(),
            'drbu_replace_add_to_cart'      => 'yes',
            'drbu_currency_display'         => 'default',
            'drbu_primary_color'            => '#2563eb',
            'drbu_cta_text_color'           => '#ffffff',
            'drbu_best_value_color'         => '#1d4ed8',
            'drbu_card_bg_color'            => '#f8fafc',
            'drbu_button_radius'            => '100px',
            'drbu_card_radius'              => '16px',
            'drbu_freemius_webhook_secret'  => '',
            'drbu_strings'                  => array(
                'best_label'       => __( 'Most Popular', 'drbu-discount-rules-box-for-woocommerce' ),
                'in_stock_label'   => __( 'In stock', 'drbu-discount-rules-box-for-woocommerce' ),
                'per_unit_label'   => __( 'per unit', 'drbu-discount-rules-box-for-woocommerce' ),
                'total_label'      => __( 'total', 'drbu-discount-rules-box-for-woocommerce' ),
                'pack_total_label' => __( 'for {qty} pieces · total', 'drbu-discount-rules-box-for-woocommerce' ),
                'savings_label'    => __( 'savings', 'drbu-discount-rules-box-for-woocommerce' ),
                'ship_free_text'   => __( 'Free shipping included in this pack', 'drbu-discount-rules-box-for-woocommerce' ),
                'ship_paid_prefix' => __( 'Free shipping for orders over', 'drbu-discount-rules-box-for-woocommerce' ),
                'free_ship_flag'   => __( 'Free shipping', 'drbu-discount-rules-box-for-woocommerce' ),
                'cta1'             => __( 'Order 1 piece — {price}', 'drbu-discount-rules-box-for-woocommerce' ),
                'cta2'             => __( 'Order 2 pieces — {price}', 'drbu-discount-rules-box-for-woocommerce' ),
                'cta3'             => __( 'Order 3 pieces — {price}', 'drbu-discount-rules-box-for-woocommerce' ),
                'cart_pack_label'  => __( 'Pack of {qty} pieces', 'drbu-discount-rules-box-for-woocommerce' ),
                'footer_badges'    => __( "Shipping 1–3 days\nCash on delivery\nMoney-back guarantee", 'drbu-discount-rules-box-for-woocommerce' ),
            ),
        );
    }

    /**
     * Spaja sačuvane opcije sa podrazumevanim vrednostima.
     */
    public function all() {
        if ( null === $this->all ) {
            $saved = get_option( self::OPTION, array() );
            $this->all = wp_parse_args( ( is_array( $saved ) ? $saved : array() ), $this->defaults() );
        }
        return $this->all;
    }

    /**
     * Vraća jednu opciju.
     */
    public function get( $key, $default = null ) {
        $all = $this->all();
        $value = ( array_key_exists( $key, $all ) ? $all[$key] : $default );
        return $this->maybe_gate( $key, $value );
    }

    /**
     * Pro-only opcije i njihove vrednosti u Free modu.
     *
     * Free korisnik uvek dobija ovu vrednost bez obzira na sačuvano stanje,
     * što je jedinstvena tačka gating-a za sve delove plugina.
     *
     * @return array
     */
    public function pro_free_values() {
        $defaults = $this->defaults();
        // VAŽNO: čita se preko $this->all() (sirova opcija + default), NIKAD
        // preko $this->tiers()/$this->get() — oni prolaze kroz maybe_gate(),
        // koja poziva ovu istu metodu, što bi izazvalo beskonačnu rekurziju.
        $raw = $this->all();
        $current_tiers = ( isset( $raw['drbu_tiers'] ) && is_array( $raw['drbu_tiers'] ) ? $raw['drbu_tiers'] : array() );
        // Treći nivo (indeks 2) je Pro-only — vraća se na default popust kad
        // licenca nije aktivna, tako da zastareo popust ne ostane "živ" u bazi
        // ako korisnik pređe na Free (npr. istekne trial) a nikad ne sačuva
        // podešavanja ponovo. Nivoi 0 i 1 se ne diraju — vraćamo ceo niz jer
        // se ova vrednost direktno dodeljuje u $clean['drbu_tiers'].
        $tier_3_default = ( isset( $defaults['drbu_tiers'][2] ) ? $defaults['drbu_tiers'][2] : array(
            'discount' => 0,
        ) );
        $reset_tiers = ( is_array( $current_tiers ) ? $current_tiers : array() );
        $reset_tiers[2] = ( isset( $reset_tiers[2] ) && is_array( $reset_tiers[2] ) ? $reset_tiers[2] : array() );
        $reset_tiers[2]['discount'] = ( isset( $tier_3_default['discount'] ) ? (float) $tier_3_default['discount'] : 0 );
        return array(
            'drbu_tier_count'               => 2,
            'drbu_tiers'                    => $reset_tiers,
            'drbu_primary_color'            => ( isset( $defaults['drbu_primary_color'] ) ? $defaults['drbu_primary_color'] : '#2563EB' ),
            'drbu_cta_text_color'           => ( isset( $defaults['drbu_cta_text_color'] ) ? $defaults['drbu_cta_text_color'] : '#FFFFFF' ),
            'drbu_best_value_color'         => ( isset( $defaults['drbu_best_value_color'] ) ? $defaults['drbu_best_value_color'] : '#1D4ED8' ),
            'drbu_card_bg_color'            => ( isset( $defaults['drbu_card_bg_color'] ) ? $defaults['drbu_card_bg_color'] : '#F8FAFC' ),
            'drbu_button_radius'            => ( isset( $defaults['drbu_button_radius'] ) ? $defaults['drbu_button_radius'] : '100px' ),
            'drbu_card_radius'              => ( isset( $defaults['drbu_card_radius'] ) ? $defaults['drbu_card_radius'] : '16px' ),
            'drbu_auto_insert_product_ids'  => '',
            'drbu_auto_insert_category_ids' => array(),
        );
    }

    /**
     * Da li je Pro aktivan? (pomoćni getter da ostali kod ne zove funkciju direktno).
     *
     * @return bool
     */
    public function is_pro_active() {
        return function_exists( 'drbu_is_pro_active' ) && drbu_is_pro_active();
    }

    /**
     * Ako opcija pripada Pro skupu i licenca nije aktivna, vraća Free vrednost.
     *
     * NAPOMENA (opseg ove metode posle __premium_only refaktora): ovo NIJE
     * mehanizam koji sam po sebi "krije" Pro funkcionalnost — tier-3
     * rendering, restriction picker UI/AJAX i Appearance panel su fizički
     * izbačeni iz Free ZIP-a preko __premium_only sufiksa (vidi
     * render_tier_row__premium_only(), render_auto_insert_product_ids__premium_only(),
     * render_auto_insert_category_ids__premium_only(), render_appearance_panel__premium_only()
     * i DRBU_Product_Display::is_allowed__premium_only()), pa taj kod uopšte
     * ne postoji u Free ZIP-u. Ova metoda ostaje kao dodatna zaštita na nivou
     * SAČUVANIH VREDNOSTI: sprečava da stare Pro-vrednosti u bazi (npr. sajt
     * koji je bio Pro pa mu je istekao trial) i dalje "cure" na frontend
     * (npr. custom boje u templates/tiered-buy-box.php) i posle prelaska na
     * Free, iako sam kod koji bi ih menjao/postavljao više ne postoji.
     *
     * @param string $key   Ključ opcije.
     * @param mixed  $value Trenutna vrednost.
     * @return mixed
     */
    private function maybe_gate( $key, $value ) {
        if ( $this->is_pro_active() ) {
            return $value;
        }
        $free = $this->pro_free_values();
        if ( array_key_exists( $key, $free ) ) {
            return $free[$key];
        }
        return $value;
    }

    /**
     * Sva podešavanja sa primenjenim Pro gating-om (za JS preview i slično).
     *
     * @return array
     */
    public function gated_all() {
        $all = $this->all();
        foreach ( $all as $key => $value ) {
            $all[$key] = $this->maybe_gate( $key, $value );
        }
        return $all;
    }

    /**
     * Defaults sa primenjenim Pro gating-om.
     *
     * @return array
     */
    public function gated_defaults() {
        $all = $this->defaults();
        foreach ( $all as $key => $value ) {
            $all[$key] = $this->maybe_gate( $key, $value );
        }
        return $all;
    }

    /**
     * Upgrad/trial CTA — link i labela.
     *
     * Kada je Freemius SDK dostupan koristi Freemius checkout; u suprotnom
     * fallback na landing page sa pricing sekcijom.
     *
     * @param string $fallback_label Labela za fallback slučaj.
     * @return array{url:string,label:string}
     */
    public function get_pro_url( $fallback_label = '' ) {
        $label = ( '' !== $fallback_label ? $fallback_label : __( 'Start 30-Day Free Pro Trial', 'drbu-discount-rules-box-for-woocommerce' ) );
        $license = DRBU_License::instance();
        $fs_url = $license->get_upgrade_url();
        if ( !empty( $fs_url ) ) {
            return array(
                'url'   => $fs_url,
                'label' => $label,
            );
        }
        return array(
            'url'   => 'https://discountrulesbox.com/',
            'label' => $label,
        );
    }

    /**
     * Renderuje status licence (tab "License").
     */
    public function render_license_status() {
        $license = DRBU_License::instance();
        $status = $license->get_status();
        $is_pro = 'free' !== $status;
        $status_labels = array(
            'trial'  => array(__( 'Pro Trial Active', 'drbu-discount-rules-box-for-woocommerce' ), 'status-trial'),
            'active' => array(__( 'Pro Active', 'drbu-discount-rules-box-for-woocommerce' ), 'status-active'),
            'free'   => array(__( 'Free Version', 'drbu-discount-rules-box-for-woocommerce' ), 'status-free'),
        );
        $status_label = ( isset( $status_labels[$status] ) ? $status_labels[$status][0] : __( 'Unknown', 'drbu-discount-rules-box-for-woocommerce' ) );
        $status_class = ( isset( $status_labels[$status] ) ? $status_labels[$status][1] : '' );
        $plan_slug = $license->get_plan_slug();
        $plan_title = ( $is_pro ? $license->get_plan_title() : __( 'Free', 'drbu-discount-rules-box-for-woocommerce' ) );
        $sites_limit = $license->get_sites_limit();
        $sites_used = ( $is_pro ? $license->get_sites_used() : 0 );
        $expiration = $license->get_expiration_date();
        $license_key = $license->get_license_key();
        $last_sync = $license->get_last_sync();
        $account_url = $license->get_account_url();
        $manage_url = admin_url( 'admin.php?page=' . self::MENU_SLUG . '&tab=license' );
        $deactivate_url = ( function_exists( 'drbu_fs' ) && drbu_fs() ? drbu_fs()->get_account_url( 'deactivate_license' ) : '' );
        ?>
		<div class="drbu-stat-grid">
			<div class="drbu-stat-card">
				<span class="drbu-stat-label"><?php 
        echo esc_html__( 'Status', 'drbu-discount-rules-box-for-woocommerce' );
        ?></span>
				<strong class="drbu-stat-value <?php 
        echo esc_attr( $status_class );
        ?>"><?php 
        echo esc_html( $status_label );
        ?></strong>
				<?php 
        if ( 'trial' === $status ) {
            ?>
					<span class="drbu-stat-sub"><?php 
            echo esc_html__( '30-day free trial', 'drbu-discount-rules-box-for-woocommerce' );
            ?></span>
				<?php 
        }
        ?>
			</div>
			<div class="drbu-stat-card">
				<span class="drbu-stat-label"><?php 
        echo esc_html__( 'Plan', 'drbu-discount-rules-box-for-woocommerce' );
        ?></span>
				<strong class="drbu-stat-value"><?php 
        echo esc_html( $plan_title );
        ?></strong>
				<span class="drbu-stat-sub" style="font-family:monospace;"><?php 
        echo esc_html( $plan_slug );
        ?></span>
			</div>
			<div class="drbu-stat-card">
				<span class="drbu-stat-label"><?php 
        echo esc_html__( 'Activations', 'drbu-discount-rules-box-for-woocommerce' );
        ?></span>
				<strong class="drbu-stat-value">
					<?php 
        if ( $sites_limit > 0 ) {
            /* translators: 1: number of used sites, 2: total sites limit */
            printf( esc_html__( '%1$d / %2$d sites', 'drbu-discount-rules-box-for-woocommerce' ), (int) $sites_used, (int) $sites_limit );
        } else {
            echo esc_html__( 'Free', 'drbu-discount-rules-box-for-woocommerce' );
        }
        ?>
				</strong>
				<span class="drbu-stat-sub"><?php 
        echo esc_html__( 'used / limit', 'drbu-discount-rules-box-for-woocommerce' );
        ?></span>
			</div>
			<div class="drbu-stat-card">
				<span class="drbu-stat-label"><?php 
        echo esc_html__( 'Expiration', 'drbu-discount-rules-box-for-woocommerce' );
        ?></span>
				<strong class="drbu-stat-value">
					<?php 
        echo ( $expiration ? esc_html( $expiration ) : esc_html__( 'Lifetime / n/a', 'drbu-discount-rules-box-for-woocommerce' ) );
        ?>
				</strong>
				<?php 
        if ( $last_sync > 0 ) {
            ?>
					<span class="drbu-stat-sub">
						<?php 
            /* translators: 1: formatted date and time of the last license sync */
            printf( esc_html__( 'Last sync: %1$s', 'drbu-discount-rules-box-for-woocommerce' ), esc_html( date_i18n( 'Y-m-d H:i', $last_sync ) ) );
            ?>
					</span>
				<?php 
        }
        ?>
			</div>
		</div>

		<?php 
        if ( !empty( $license_key ) ) {
            ?>
			<p style="margin:16px 0 0;font-size:13px;color:var(--drbu-admin-text-muted);">
				<?php 
            echo esc_html__( 'License key:', 'drbu-discount-rules-box-for-woocommerce' );
            ?>
				<code><?php 
            echo esc_html( $license_key );
            ?></code>
			</p>
		<?php 
        }
        ?>

		<div class="drbu-btn-row" style="margin-top:16px;">
			<?php 
        if ( !$is_pro ) {
            ?>
				<?php 
            $trial_cta = $this->get_pro_url( __( 'Start 30-Day Free Trial', 'drbu-discount-rules-box-for-woocommerce' ) );
            ?>
				<a href="<?php 
            echo esc_url( $trial_cta['url'] );
            ?>" class="drbu-btn drbu-btn-primary drbu-open-trial"><?php 
            echo esc_html( $trial_cta['label'] );
            ?></a>
			<?php 
        }
        ?>
			<?php 
        if ( $is_pro && !empty( $deactivate_url ) ) {
            ?>
				<a href="<?php 
            echo esc_url( $deactivate_url );
            ?>" class="drbu-btn drbu-btn-danger"><?php 
            echo esc_html__( 'Deactivate License', 'drbu-discount-rules-box-for-woocommerce' );
            ?></a>
			<?php 
        }
        ?>
			<?php 
        if ( function_exists( 'drbu_fs' ) && drbu_fs() ) {
            ?>
				<button type="button" class="drbu-btn drbu-sync-license-btn">
					<?php 
            echo esc_html__( '🔄 Sync License Now', 'drbu-discount-rules-box-for-woocommerce' );
            ?>
				</button>
			<?php 
        }
        ?>
		</div>
		<p class="description" style="margin-top:8px;">
			<?php 
        echo esc_html__( 'Pulls the current plan/license state directly from Freemius — use this if you just changed something on the Freemius Dashboard (e.g. cancelled or deleted a license) and want it reflected here immediately, instead of waiting for the next automatic sync.', 'drbu-discount-rules-box-for-woocommerce' );
        ?>
		</p>

		<?php 
        if ( !$is_pro ) {
            ?>
			<div class="drbu-trust-badges">
				<span class="drbu-trust-badge">
					<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path></svg>
					<strong><?php 
            echo esc_html__( '14-Day Money-Back Guarantee', 'drbu-discount-rules-box-for-woocommerce' );
            ?></strong>
				</span>
				<span class="drbu-trust-badge">
					<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>
					<strong><?php 
            echo esc_html__( '30-Day Free Trial', 'drbu-discount-rules-box-for-woocommerce' );
            ?></strong>
				</span>
				<span class="drbu-trust-badge">
					<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"></path><line x1="3" y1="6" x2="21" y2="6"></line><path d="M16 10a4 4 0 0 1-8 0"></path></svg>
					<strong><?php 
            echo esc_html__( 'Cancel Anytime', 'drbu-discount-rules-box-for-woocommerce' );
            ?></strong>
				</span>
			</div>
			<p style="margin-top:14px;font-size:12.5px;color:var(--drbu-admin-text-muted);">
				<?php 
            echo esc_html__( 'Want to see the full plan lineup (1, 5, or 10 sites)?', 'drbu-discount-rules-box-for-woocommerce' );
            ?>
				<button type="button" class="drbu-tab-btn-link drbu-goto-upgrade-tab" style="background:none;border:none;padding:0;color:var(--drbu-admin-primary);font-weight:700;cursor:pointer;text-decoration:underline;">
					<?php 
            echo esc_html__( 'See the Upgrade tab →', 'drbu-discount-rules-box-for-woocommerce' );
            ?>
				</button>
			</p>
		<?php 
        }
        ?>

		<?php 
        if ( !$is_pro && function_exists( 'drbu_fs' ) && drbu_fs() ) {
            ?>
		<div style="margin-top:20px;padding:16px 18px;background:#f0f9ff;border:1px solid #bae6fd;border-left:4px solid #0284c7;border-radius:12px;max-width:620px;">
			<h4 style="margin:0 0 6px 0;color:#0369a1;font-size:14px;display:flex;align-items:center;gap:6px;">
				<span>🔑</span> <?php 
            echo esc_html__( 'Have a License Key?', 'drbu-discount-rules-box-for-woocommerce' );
            ?>
			</h4>
			<p style="margin:0 0 10px 0;font-size:12.5px;color:#0c4a6e;line-height:1.5;">
				<?php 
            echo esc_html__( 'Click below and paste the license key received in your welcome email. The key is verified with Freemius before Pro is unlocked — this does not use Save Changes.', 'drbu-discount-rules-box-for-woocommerce' );
            ?>
			</p>
			<?php 
            /**
             * Ovo dugme ne pravi svoj AJAX poziv — otvara Freemius-ov SOPSTVENI
             * dijalog za aktivaciju licence (isti kao "Change License" na Plugins
             * stranici, ubačen na ovu stranicu preko
             * DRBU_Core::maybe_inject_freemius_license_dialog()). Klasa
             * "activate-license-trigger {unique_affix}" je Freemius-ov sopstveni,
             * SDK-definisan selektor (forms/license-activation.php) na koji je
             * njegov JS već vezan.
             */
            ?>
			<button type="button" class="drbu-btn drbu-btn-primary activate-license-trigger <?php 
            echo esc_attr( drbu_fs()->get_unique_affix() );
            ?>">
				<?php 
            echo esc_html__( 'Activate License', 'drbu-discount-rules-box-for-woocommerce' );
            ?>
			</button>
			<p style="margin:8px 0 0 0;font-size:11.5px;color:#0369a1;">
				💡 <?php 
            echo esc_html__( 'Tip: If activation fails, ask your web host to whitelist api.freemius.com and wp.freemius.com for outbound HTTP requests.', 'drbu-discount-rules-box-for-woocommerce' );
            ?>
			</p>
		</div>
		<?php 
        }
        ?>
		<?php 
    }

    /**
     * Renderuje tab "Account" — Freemius nalog/naplata, odvojeno od
     * License taba (koji upravlja samim license key-em). Tekst i
     * struktura prate Account/Billing okvir sa landing stranice.
     */
    public function render_account_tab() {
        $license = DRBU_License::instance();
        $is_pro = $this->is_pro_active();
        $account_url = $license->get_account_url();
        if ( !function_exists( 'drbu_fs' ) || !drbu_fs() ) {
            echo '<p class="description">' . esc_html__( 'Freemius SDK is not available, so account management cannot be shown here.', 'drbu-discount-rules-box-for-woocommerce' ) . '</p>';
            return;
        }
        $user = drbu_fs()->get_user();
        ?>
		<div class="drbu-account-row">
			<div>
				<div class="drbu-account-row-label"><?php 
        echo esc_html__( 'Account email', 'drbu-discount-rules-box-for-woocommerce' );
        ?></div>
				<div class="drbu-account-row-desc"><?php 
        echo esc_html__( 'Where your license key, receipts, and renewal reminders are sent.', 'drbu-discount-rules-box-for-woocommerce' );
        ?></div>
			</div>
			<strong><?php 
        echo esc_html( ( $user && isset( $user->email ) ? $user->email : __( 'Not connected', 'drbu-discount-rules-box-for-woocommerce' ) ) );
        ?></strong>
		</div>

		<div class="drbu-account-row">
			<div>
				<div class="drbu-account-row-label"><?php 
        echo esc_html__( 'Plan', 'drbu-discount-rules-box-for-woocommerce' );
        ?></div>
				<div class="drbu-account-row-desc"><?php 
        echo esc_html__( 'Your current plan and site usage.', 'drbu-discount-rules-box-for-woocommerce' );
        ?></div>
			</div>
			<strong><?php 
        echo esc_html( ( $is_pro ? $license->get_plan_title() : __( 'Free', 'drbu-discount-rules-box-for-woocommerce' ) ) );
        ?></strong>
		</div>

		<div class="drbu-account-row">
			<div>
				<div class="drbu-account-row-label"><?php 
        echo esc_html__( 'Billing &amp; payment method', 'drbu-discount-rules-box-for-woocommerce' );
        ?></div>
				<div class="drbu-account-row-desc"><?php 
        echo esc_html__( 'Update your card, view invoices, or change your billing details — securely hosted by Freemius.', 'drbu-discount-rules-box-for-woocommerce' );
        ?></div>
			</div>
			<?php 
        if ( !empty( $account_url ) ) {
            ?>
				<a href="<?php 
            echo esc_url( $account_url );
            ?>" target="_blank" rel="noopener noreferrer" class="drbu-btn"><?php 
            echo esc_html__( 'Manage Billing', 'drbu-discount-rules-box-for-woocommerce' );
            ?></a>
			<?php 
        } else {
            ?>
				<span class="drbu-account-row-desc"><?php 
            echo esc_html__( 'Available once connected to Freemius.', 'drbu-discount-rules-box-for-woocommerce' );
            ?></span>
			<?php 
        }
        ?>
		</div>

		<div class="drbu-account-row">
			<div>
				<div class="drbu-account-row-label"><?php 
        echo esc_html__( 'Downloads &amp; invoices', 'drbu-discount-rules-box-for-woocommerce' );
        ?></div>
				<div class="drbu-account-row-desc"><?php 
        echo esc_html__( 'Redownload the plugin or a past invoice from your Freemius customer portal.', 'drbu-discount-rules-box-for-woocommerce' );
        ?></div>
			</div>
			<?php 
        if ( !empty( $account_url ) ) {
            ?>
				<a href="<?php 
            echo esc_url( $account_url );
            ?>" target="_blank" rel="noopener noreferrer" class="drbu-btn"><?php 
            echo esc_html__( 'Open Customer Portal', 'drbu-discount-rules-box-for-woocommerce' );
            ?></a>
			<?php 
        }
        ?>
		</div>

		<?php 
        if ( !$is_pro ) {
            ?>
			<p style="margin:18px 0 0;font-size:12.5px;color:var(--drbu-admin-text-muted);">
				<?php 
            echo esc_html__( 'Have a license key already? Activate it from the License tab, or', 'drbu-discount-rules-box-for-woocommerce' );
            ?>
				<button type="button" class="drbu-goto-upgrade-tab" style="background:none;border:none;padding:0;color:var(--drbu-admin-primary);font-weight:700;cursor:pointer;text-decoration:underline;"><?php 
            echo esc_html__( 'see the Upgrade tab', 'drbu-discount-rules-box-for-woocommerce' );
            ?></button>
				<?php 
            echo esc_html__( 'to buy one.', 'drbu-discount-rules-box-for-woocommerce' );
            ?>
			</p>
		<?php 
        }
        ?>
		<?php 
    }

    /**
     * Renderuje tab "Upgrade" — iste pricing kartice (cene, "Most Popular"
     * značka, per-store highlight, guarantee red) kao #pricing sekcija na
     * discountrulesbox.com, da bi kupovina unutar admina bila vizuelno i
     * tekstualno identična onome što korisnik vidi na landing stranici.
     * Dugmad koriste isti drbu-open-checkout/data-licenses obrazac koji
     * initFreemiusCheckout() (assets/js .../admin.js) već obrađuje.
     */
    public function render_upgrade_tab() {
        $is_pro = $this->is_pro_active();
        $plans = array(array(
            'title'     => __( 'Single Site', 'drbu-discount-rules-box-for-woocommerce' ),
            'sub'       => __( 'Pro license for a single store.', 'drbu-discount-rules-box-for-woocommerce' ),
            'price'     => '69',
            'licenses'  => 1,
            'sites'     => __( 'Use on up to 1 site', 'drbu-discount-rules-box-for-woocommerce' ),
            'featured'  => false,
            'highlight' => '',
        ), array(
            'title'     => __( '5 Sites', 'drbu-discount-rules-box-for-woocommerce' ),
            'sub'       => __( 'Pro license for growing stores & agencies.', 'drbu-discount-rules-box-for-woocommerce' ),
            'price'     => '95',
            'licenses'  => 5,
            'sites'     => __( 'Use on up to 5 sites', 'drbu-discount-rules-box-for-woocommerce' ),
            'featured'  => true,
            'highlight' => '⚡ ' . __( 'Only $1.58/mo per store ($19/yr)', 'drbu-discount-rules-box-for-woocommerce' ),
        ), array(
            'title'     => __( '10 Sites', 'drbu-discount-rules-box-for-woocommerce' ),
            'sub'       => __( 'Pro license for established agencies.', 'drbu-discount-rules-box-for-woocommerce' ),
            'price'     => '124',
            'licenses'  => 10,
            'sites'     => __( 'Use on up to 10 sites', 'drbu-discount-rules-box-for-woocommerce' ),
            'featured'  => false,
            'highlight' => '🔥 ' . __( 'Only $1.03/mo per store ($12.40/yr)', 'drbu-discount-rules-box-for-woocommerce' ),
        ));
        ?>
		<div class="drbu-pricing-cards">
			<?php 
        foreach ( $plans as $plan ) {
            ?>
				<div class="drbu-pricing-card<?php 
            echo ( $plan['featured'] ? ' featured' : '' );
            ?>">
					<?php 
            if ( $plan['featured'] ) {
                ?>
						<span class="drbu-pricing-card-badge"><?php 
                echo esc_html__( 'Most Popular', 'drbu-discount-rules-box-for-woocommerce' );
                ?></span>
					<?php 
            }
            ?>
					<h4 class="drbu-pricing-card-title"><?php 
            echo esc_html( $plan['title'] );
            ?></h4>
					<p class="drbu-pricing-card-sub"><?php 
            echo esc_html( $plan['sub'] );
            ?></p>
					<div class="drbu-pricing-amount">$<?php 
            echo esc_html( $plan['price'] );
            ?><span>.00 / yr</span></div>
					<div class="drbu-pricing-cycle"><?php 
            echo esc_html__( 'Billed Annually', 'drbu-discount-rules-box-for-woocommerce' );
            ?></div>
					<ul class="drbu-pricing-features">
						<li><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><polyline points="20 6 9 17 4 12"></polyline></svg><?php 
            echo esc_html__( 'All Pro features included', 'drbu-discount-rules-box-for-woocommerce' );
            ?></li>
						<li><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><polyline points="20 6 9 17 4 12"></polyline></svg><?php 
            echo esc_html( $plan['sites'] );
            ?></li>
					</ul>
					<?php 
            if ( $plan['highlight'] ) {
                ?>
						<div class="drbu-per-store-highlight"><?php 
                echo esc_html( $plan['highlight'] );
                ?></div>
					<?php 
            }
            ?>
					<?php 
            // Svaki plan mora prvo da prođe kroz 30-dnevni free trial —
            // nema direktne kupovine bez trial-a. Klasa drbu-open-trial
            // (ne drbu-open-checkout) je ono što initFreemiusCheckout()
            // (assets/js .../admin.js) čita da odluči da li šalje
            // trial:'free' ili trial:false u FS.Checkout.handler.open().
            $buy_cta = $this->get_pro_url( __( 'Start 30-Day Free Trial', 'drbu-discount-rules-box-for-woocommerce' ) );
            ?>
					<a href="<?php 
            echo esc_url( $buy_cta['url'] );
            ?>" class="drbu-btn drbu-btn-primary drbu-pricing-cta drbu-open-trial" data-licenses="<?php 
            echo esc_attr( $plan['licenses'] );
            ?>"><?php 
            echo esc_html( $buy_cta['label'] );
            ?></a>
					<p class="drbu-pricing-cta-note" style="margin:8px 0 0;font-size:11.5px;color:#64748b;text-align:center;"><?php 
            echo esc_html__( 'Then billed annually — cancel anytime during the trial.', 'drbu-discount-rules-box-for-woocommerce' );
            ?></p>
				</div>
			<?php 
        }
        ?>
		</div>

		<div class="drbu-trust-badges" style="margin-top:24px;justify-content:center;">
			<span class="drbu-trust-badge">
				<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path></svg>
				<strong><?php 
        echo esc_html__( '14-Day Money-Back Guarantee', 'drbu-discount-rules-box-for-woocommerce' );
        ?></strong>
			</span>
			<span class="drbu-trust-badge">
				<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>
				<strong><?php 
        echo esc_html__( '30-Day Free Trial, full Pro access', 'drbu-discount-rules-box-for-woocommerce' );
        ?></strong>
			</span>
			<span class="drbu-trust-badge">
				<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"></path><line x1="3" y1="6" x2="21" y2="6"></line><path d="M16 10a4 4 0 0 1-8 0"></path></svg>
				<strong><?php 
        echo esc_html__( 'Secure checkout hosted by Freemius', 'drbu-discount-rules-box-for-woocommerce' );
        ?></strong>
			</span>
		</div>

		<?php 
        if ( $is_pro && function_exists( 'drbu_fs' ) && drbu_fs() ) {
            ?>
			<p style="margin-top:20px;font-size:12.5px;color:var(--drbu-admin-text-muted);text-align:center;">
				<?php 
            echo esc_html__( 'Need more sites or want to change plans? Manage it from the Account tab.', 'drbu-discount-rules-box-for-woocommerce' );
            ?>
			</p>
		<?php 
        }
        ?>
		<?php 
    }

    /**
     * Renderuje webhook secret polje (tab "License").
     */
    public function render_webhook_secret() {
        // Bezbednosna napomena: stvarna sačuvana vrednost se NIKAD ne ispisuje
        // nazad u HTML (čak ni u type="password" polju — vrednost atributa
        // je i dalje čitljiva iz izvora stranice/DOM-a svakome ko ima pristup
        // stranici, npr. Shop Manager sa manage_woocommerce). Polje ostaje
        // prazno; postojeća vrednost se čuva u sanitize() ako korisnik
        // ostavi polje prazno pri snimanju.
        $has_secret = '' !== (string) $this->get( 'drbu_freemius_webhook_secret', '' );
        $endpoint = esc_url_raw( rest_url( 'drbu/v1/freemius-webhook' ) );
        ?>
		<div class="drbu-form-row">
			<label class="drbu-label" for="drbu_freemius_webhook_secret"><?php 
        echo esc_html__( 'Webhook secret', 'drbu-discount-rules-box-for-woocommerce' );
        ?></label>
			<input type="password" class="large-text" id="drbu_freemius_webhook_secret"
				name="<?php 
        echo esc_attr( self::OPTION );
        ?>[drbu_freemius_webhook_secret]"
				value="" placeholder="<?php 
        echo ( $has_secret ? esc_attr__( '•••••••••••••• (already set — leave blank to keep it unchanged)', 'drbu-discount-rules-box-for-woocommerce' ) : '' );
        ?>" autocomplete="off">
			<p class="description">
				<?php 
        echo esc_html__( 'This is NOT a separate webhook-only secret — paste your product\'s own Secret Key here (starts with "sk_"), found on the Freemius Developer Dashboard under this product → Settings. It\'s the same key used for the WP_FS__..._SECRET_KEY constant in wp-config.php for sandbox mode. Requests without a valid HMAC signature computed from this key are rejected.', 'drbu-discount-rules-box-for-woocommerce' );
        ?>
			</p>
			<p class="description" style="margin-top:6px;">
				<?php 
        printf( 
            /* translators: %s: webhook URL */
            esc_html__( 'Webhook URL: %s', 'drbu-discount-rules-box-for-woocommerce' ),
            '<code>' . esc_html( $endpoint ) . '</code>'
         );
        ?>
			</p>
		</div>
		<?php 
    }

    /**
     * Vraća niz nivoa.
     */
    public function tiers() {
        $tiers = $this->get( 'drbu_tiers', array() );
        return ( is_array( $tiers ) ? $tiers : array() );
    }

    /**
     * Vraća niz tekstova.
     */
    public function strings() {
        $strings = $this->get( 'drbu_strings', array() );
        return ( is_array( $strings ) ? $strings : array() );
    }

    /**
     * Vraća podešene boje buy box-a (sekcija "Izgled").
     */
    public function get_primary_colors() {
        return array(
            'primary'    => $this->get( 'drbu_primary_color', '#2563eb' ),
            'cta_text'   => $this->get( 'drbu_cta_text_color', '#ffffff' ),
            'best_value' => $this->get( 'drbu_best_value_color', '#1d4ed8' ),
            'card_bg'    => $this->get( 'drbu_card_bg_color', '#f8fafc' ),
        );
    }

    /**
     * Renderuje stranicu Analitika i Statistika Prodaje u duhu celog interfejsa.
     */
    public function render_analytics_page() {
        if ( !current_user_can( self::CAPABILITY ) ) {
            return;
        }
        // Analytics je Pro funkcija — Free korisnik dobija upsell panel umesto podataka.
        // class_exists() je defense-in-depth: na Free ZIP-u (gde je
        // class-drbu-analytics__premium_only.php fizički izbačen od strane
        // Freemius Deployment-a) klasa uopšte ne postoji, bez obzira na
        // license status.
        if ( !$this->is_pro_active() || !class_exists( 'DRBU_Analytics' ) ) {
            $cta = $this->get_pro_url( __( 'Start 30-Day Free Pro Trial', 'drbu-discount-rules-box-for-woocommerce' ) );
            ?>
			<div class="wrap drbu-wrap drbu-analytics-wrap">
				<div class="drbu-header-card">
					<div class="drbu-header-brand">
						<div class="drbu-brand-icon">
							<img src="<?php 
            echo esc_url( DRBU_PLUGIN_URL . 'assets/images/DRBlogo.svg' );
            ?>" alt="<?php 
            esc_attr_e( 'Discount Rules Box', 'drbu-discount-rules-box-for-woocommerce' );
            ?>" class="drbu-header-logo">
						</div>
						<div>
							<div class="drbu-brand-title">
								<h1><?php 
            echo esc_html__( 'DRBU Sales Analytics', 'drbu-discount-rules-box-for-woocommerce' );
            ?></h1>
								<span class="drbu-version-badge">v<?php 
            echo esc_html( DRBU_VERSION );
            ?></span>
							</div>
							<p class="drbu-brand-subtitle"><?php 
            echo esc_html__( 'Track revenue, conversions, and pack distribution for 1, 2, and 3 piece packs.', 'drbu-discount-rules-box-for-woocommerce' );
            ?></p>
						</div>
					</div>
				</div>
				<hr class="wp-header-end">

				<div class="drbu-card" style="max-width:720px;margin:24px auto;text-align:center;padding:40px 32px;">
					<div style="font-size:48px;line-height:1;">📊</div>
					<h2 style="margin:16px 0 8px;">🔒 <?php 
            echo esc_html__( 'Analytics is a Pro Feature', 'drbu-discount-rules-box-for-woocommerce' );
            ?></h2>
					<p style="max-width:520px;margin:0 auto 8px;color:#475569;line-height:1.6;">
						<?php 
            echo esc_html__( 'Unlock the Sales Analytics dashboard to track upsell revenue, average order value (AOV), tier adoption, and your top-selling bundle products — all in real time.', 'drbu-discount-rules-box-for-woocommerce' );
            ?>
					</p>
					<ul style="margin:16px auto;max-width:420px;text-align:left;list-style-type:disc;color:#475569;line-height:2;">
						<li><?php 
            echo esc_html__( 'Total & incremental upsell revenue', 'drbu-discount-rules-box-for-woocommerce' );
            ?></li>
						<li><?php 
            echo esc_html__( 'AOV and upsell conversion rate', 'drbu-discount-rules-box-for-woocommerce' );
            ?></li>
						<li><?php 
            echo esc_html__( 'Pack distribution (1, 2, 3, 3+)', 'drbu-discount-rules-box-for-woocommerce' );
            ?></li>
						<li><?php 
            echo esc_html__( 'Top upsell products & recent orders', 'drbu-discount-rules-box-for-woocommerce' );
            ?></li>
					</ul>
					<a href="<?php 
            echo esc_url( $cta['url'] );
            ?>" class="button button-primary" style="background:#2563eb;border-color:#1d4ed8;font-weight:700;border-radius:100px;padding:8px 26px;text-decoration:none;height:auto;"><?php 
            echo esc_html( $cta['label'] );
            ?></a>
				</div>
			</div>
			<?php 
            return;
        }
        $this->render_analytics_page__premium_only();
    }

}
