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

/**
 * KNSDD_Page_Settings Class
 *
 * "Ayarlar" admin sayfasını oluşturur ve yönetir.
 */
class KNSDD_Page_Settings {

    private $settings_group = 'knsdd_settings_group';
    private $option_name = 'knsdd_global_settings';

    public function __construct() {
        add_action( 'admin_init', array( $this, 'register_settings' ) );
        // Erken aşamada (admin_init) yanlış aktivasyon bildirimlerine yol açan query arg'ları temizle
        add_action( 'admin_init', array( $this, 'maybe_strip_activation_query' ), 1 );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_styles' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
    }

    /**
     * Sadece bizim ayar sayfamızda, aktivasyonla ilgili query arg'larını temizleyip yönlendirir.
     * Bunu erken çalıştırarak (admin_notices'tan önce) yanlış bildirimin çıkmasını engelleriz.
     */
    public function maybe_strip_activation_query() {
        if ( ! is_admin() ) { return; }
        $page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
        if ( $page !== 'knsdd-settings' ) { return; }
        $to_remove = array( 'activate', 'activate-multi', 'deactivate', 'activate-plugin', 'deactivate-plugin' );
        foreach ( $to_remove as $arg ) {
            if ( isset( $_GET[ $arg ] ) ) {
                $clean_url = remove_query_arg( $to_remove );
                wp_safe_redirect( $clean_url );
                exit;
            }
        }
    }

    /**
     * Bölüm giriş işaretleyicileri (JS için sağlam anchor sağlar)
     */
    public function render_general_section_intro() {
        echo '<div class="screen-reader-text" data-knsdd-section="knsdd_general_section"></div>';
    }
    public function render_language_section_intro() {
        echo '<div class="screen-reader-text" data-knsdd-section="knsdd_language_section"></div>';
    }
    public function render_dates_section_intro() {
        echo '<div class="screen-reader-text" data-knsdd-section="knsdd_dates_section"></div>';
    }
    public function render_ui_section_intro() {
        echo '<div class="screen-reader-text" data-knsdd-section="knsdd_ui_section"></div>';
    }
    public function render_notifications_section_intro() {
        echo '<div class="screen-reader-text" data-knsdd-section="knsdd_notifications_section"></div>';
    }
    public function render_advanced_section_intro() {
        echo '<div class="screen-reader-text" data-knsdd-section="knsdd_advanced_section"></div>';
    }
    public function render_rules_section_intro() {
        echo '<div class="screen-reader-text" data-knsdd-section="knsdd_rules_section"></div>';
    }

    /**
     * Sadece bu sayfada kullanılacak stil dosyasını yükler.
     */
    public function enqueue_styles( $hook ) {
        // Bu sayfanın hook değeri menü yapısına göre değişebilir.
        // Güvenli yaklaşım: $hook içinde 'knsdd-settings' geçiyorsa stilleri yükle.
        if ( strpos( $hook, 'knsdd-settings' ) === false ) {
            return;
        }
        wp_enqueue_style( 'knsdd-admin-css', KNSDD_PLUGIN_URL . 'assets/css/index.css', array(), KNSDD_VERSION );
        wp_enqueue_style( 'knsdd-settings-css', KNSDD_PLUGIN_URL . 'assets/css/settings.css', array('knsdd-admin-css'), KNSDD_VERSION );
    }

    /**
     * Ayarlar sayfası için gerekli JS dosyalarını yükler.
     */
    public function enqueue_scripts( $hook ) {
        if ( strpos( $hook, 'knsdd-settings' ) === false ) {
            return;
        }
        wp_enqueue_script( 'knsdd-settings-js', KNSDD_PLUGIN_URL . 'assets/js/settings/index.js', array( 'jquery' ), KNSDD_VERSION, true );

        // Provide i18n strings for JS via centralized provider (ensures POT/PO extraction)
        wp_localize_script( 'knsdd-settings-js', 'knsdd_settings_i18n', KNSDD_I18n::get_settings_js_i18n() );
    }

    /**
     * Ayarlarımızı WordPress'e kaydeder.
     */
    public function register_settings() {
        register_setting(
            $this->settings_group,
            $this->option_name,
            array( $this, 'sanitize_settings' )
        );

        add_settings_section(
            'knsdd_general_section',
            __( 'Genel Ayarlar', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_general_section_intro' ),
            $this->settings_group
        );

        add_settings_field(
            'global_status',
            __( 'Eklentinin Genel Durumu', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_global_status_field' ),
            $this->settings_group,
            'knsdd_general_section'
        );

        add_settings_section(
            'knsdd_language_section',
            __( 'Dil Ayarları', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_language_section_intro' ),
            $this->settings_group
        );

        add_settings_field(
            'language_mode',
            __( 'Dil Modu', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_language_mode_field' ),
            $this->settings_group,
            'knsdd_language_section'
        );

        add_settings_field(
            'language_locale',
            __( 'Dil', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_language_locale_field' ),
            $this->settings_group,
            'knsdd_language_section'
        );

        // Tarih Yönetimi
        add_settings_section(
            'knsdd_dates_section',
            __( 'Tarih Yönetimi', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_dates_section_intro' ),
            $this->settings_group
        );

        add_settings_field(
            'conflict_action',
            __( 'Tarih Uyuşmazlığı durumunda yapılacak işlem', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_conflict_action_field' ),
            $this->settings_group,
            'knsdd_dates_section'
        );

        // Inline warning duration field is registered under UI section below 'Uyarı Konumu'

        add_settings_field(
            'conflict_scope',
            __( 'Tarih uyuşmazlığı kontrol kapsamı', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_conflict_scope_field' ),
            $this->settings_group,
            'knsdd_dates_section'
        );

        add_settings_field(
            'validate_same_day',
            __( 'Aynı gün aralıklarını kabul et', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_validate_same_day_field' ),
            $this->settings_group,
            'knsdd_dates_section'
        );

        add_settings_field(
            'date_alt_format',
            __( 'Tarih gösterim formatı', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_date_alt_format_field' ),
            $this->settings_group,
            'knsdd_dates_section'
        );

        add_settings_field(
            'lock_started_campaigns',
            __( 'Başlamış kampanyaların tarihlerini kilitle', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_lock_started_campaigns_field' ),
            $this->settings_group,
            'knsdd_dates_section'
        );

        // UI & Accessibility
        add_settings_section(
            'knsdd_ui_section',
            __( 'Görünüm ve Erişilebilirlik', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_ui_section_intro' ),
            $this->settings_group
        );

        add_settings_field(
            'warning_theme',
            __( 'Uyarı Renk Teması', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_warning_theme_field' ),
            $this->settings_group,
            'knsdd_ui_section'
        );

        add_settings_field(
            'warning_location',
            __( 'Uyarı Konumu', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_warning_location_field' ),
            $this->settings_group,
            'knsdd_ui_section'
        );

        add_settings_field(
            'inline_warning_ms',
            __( 'Uyarı mesajı görünüm süresi (ms)', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_inline_warning_ms_field' ),
            $this->settings_group,
            'knsdd_ui_section'
        );

        add_settings_field(
            'focus_theme',
            __( 'Son Odak Vurgu Rengi', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_focus_theme_field' ),
            $this->settings_group,
            'knsdd_ui_section'
        );

        add_settings_field(
            'last_highlight_ms',
            __( 'Son Odak Vurgusu (ms)', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_last_highlight_ms_field' ),
            $this->settings_group,
            'knsdd_ui_section'
        );

        add_settings_field(
            'a11y_alert_role',
            __( 'Erişilebilirlik: Alert Rolü', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_a11y_alert_role_field' ),
            $this->settings_group,
            'knsdd_ui_section'
        );

        // Sepet & Ödeme Mesaj Konumu (Kademeli İndirim)
        add_settings_field(
            'cart_msg_positions',
            __( 'Mini Sepet & Sepet & Ödeme Mesaj Konumu (Kademeli İndirim Mesaj Konumu)', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_cart_msg_positions_field' ),
            $this->settings_group,
            'knsdd_ui_section'
        );

        // Özel Kampanya Mesajlarını Ürün Satırı Altında Göster (varsayılan: açık)
        add_settings_field(
            'special_msg_under_item',
            __( 'Özel Kampanya Mesajlarını Ürün Satırı Altında Göster', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_special_msg_under_item_field' ),
            $this->settings_group,
            'knsdd_ui_section'
        );

        // Ürün Mesajı: Konum + Zorla (tema/builder uyumluluğu)
        add_settings_field(
            'product_message_location',
            __( 'Ürün Mesajı Konumu', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_product_message_location_field' ),
            $this->settings_group,
            'knsdd_ui_section'
        );

        add_settings_field(
            'product_message_force',
            __( 'Ürün Mesajı Konumunu Zorla (tema/builder uyumluluğu)', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_product_message_force_field' ),
            $this->settings_group,
            'knsdd_ui_section'
        );

        // Ürün Sayfası: Kademe Tablosu
        add_settings_field(
            'tier_table_enabled',
            __( 'Ürün Sayfası Kademe İndirim Tablosu', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_tier_table_enabled_field' ),
            $this->settings_group,
            'knsdd_ui_section'
        );

        add_settings_field(
            'tier_table_location',
            __( 'Kademe İndirim Tablosu Konumu', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_tier_table_location_field' ),
            $this->settings_group,
            'knsdd_ui_section'
        );

        // Konumu Zorla (tema/builder uyumluluğu)
        add_settings_field(
            'tier_table_force',
            __( 'Kademe İndirim Tablosu Konumunu Zorla (tema/builder uyumluluğu)', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_tier_table_force_field' ),
            $this->settings_group,
            'knsdd_ui_section'
        );

        // Sepet/Checkout Üstü Çizili Fiyat
        add_settings_field(
            'strikethrough_price_enabled',
            __( 'Sepet/Checkout Üstü Çizili Fiyat', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_strikethrough_price_field' ),
            $this->settings_group,
            'knsdd_ui_section'
        );

        // Kademe İndirim Tablosu: Renk Ayarı
        add_settings_field(
            'tier_theme_use_custom',
            __( 'Kademe İndirim Tablosunda Özel Renk Kullan', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_tier_theme_use_custom_field' ),
            $this->settings_group,
            'knsdd_ui_section'
        );

        add_settings_field(
            'tier_theme_preset',
            __( 'Kademe İndirim Tablosu Renk Teması', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_tier_theme_preset_field' ),
            $this->settings_group,
            'knsdd_ui_section'
        );

        // Rules Behavior
        add_settings_section(
            'knsdd_rules_section',
            __( 'Kural Davranışları', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_rules_section_intro' ),
            $this->settings_group
        );

        add_settings_field(
            'auto_fill_category_from_products',
            __( 'Ürün seçiminden kategori otomatik dolsun', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_auto_fill_category_field' ),
            $this->settings_group,
            'knsdd_rules_section'
        );

        // Notifications
        add_settings_section(
            'knsdd_notifications_section',
            __( 'Bildirimler', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_notifications_section_intro' ),
            $this->settings_group
        );

        add_settings_field(
            'notifications_enabled',
            __( 'Bildirim Sistemi', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_notifications_enabled_field' ),
            $this->settings_group,
            'knsdd_notifications_section'
        );

        // Advanced
        add_settings_section(
            'knsdd_advanced_section',
            __( 'Gelişmiş', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_advanced_section_intro' ),
            $this->settings_group
        );

        add_settings_field(
            'trigger_timing',
            __( 'Değişiklikleri Ne Zaman Kontrol Edelim?', 'kns-dynamic-discounts-for-woocommerce' ),
            array( $this, 'render_trigger_timing_field' ),
            $this->settings_group,
            'knsdd_advanced_section'
        );

    }

    /**
     * Ayarları kaydetmeden önce temizler.
     */
    public function sanitize_settings( $input ) {
        $sanitized_input = array();
        $sanitized_input['global_status'] = isset( $input['global_status'] ) ? 1 : 0;
        $mode = isset( $input['language_mode'] ) ? sanitize_text_field( $input['language_mode'] ) : 'auto';
        $sanitized_input['language_mode'] = in_array( $mode, array( 'auto', 'manual' ), true ) ? $mode : 'auto';
        $locale = isset( $input['language_locale'] ) ? sanitize_text_field( $input['language_locale'] ) : 'en_US';
        $supported = array_keys( KNSDD_Utils::get_supported_locales() );
        $sanitized_input['language_locale'] = in_array( $locale, $supported, true ) ? $locale : 'en_US';

        // Tarih Yönetimi
        $action = isset( $input['conflict_action'] ) ? sanitize_text_field( $input['conflict_action'] ) : 'revert';
        $sanitized_input['conflict_action'] = in_array( $action, array( 'revert', 'clear' ), true ) ? $action : 'revert';

        $ms = isset( $input['inline_warning_ms'] ) ? intval( $input['inline_warning_ms'] ) : 5000;
        if ( $ms < 2000 ) { $ms = 2000; }
        if ( $ms > 15000 ) { $ms = 15000; }
        $sanitized_input['inline_warning_ms'] = $ms;

        $scope = isset( $input['conflict_scope'] ) ? sanitize_text_field( $input['conflict_scope'] ) : 'same_rules';
        $sanitized_input['conflict_scope'] = in_array( $scope, array( 'same_rules', 'all' ), true ) ? $scope : 'same_rules';

        $same_day = isset( $input['validate_same_day'] ) ? (int) !! $input['validate_same_day'] : 1;
        $sanitized_input['validate_same_day'] = $same_day;

        $format = isset( $input['date_alt_format'] ) ? sanitize_text_field( $input['date_alt_format'] ) : 'd.m.Y';
        $allowed_formats = array( 'd.m.Y', 'd/m/Y', 'Y-m-d' );
        $sanitized_input['date_alt_format'] = in_array( $format, $allowed_formats, true ) ? $format : 'd.m.Y';

        $lock_started = isset( $input['lock_started_campaigns'] ) ? (int) !! $input['lock_started_campaigns'] : 1;
        $sanitized_input['lock_started_campaigns'] = $lock_started;

        // UI & Accessibility
        $theme = isset( $input['warning_theme'] ) ? sanitize_text_field( $input['warning_theme'] ) : 'rose';
        $sanitized_input['warning_theme'] = in_array( $theme, array( 'rose', 'blue', 'gray', 'sage', 'lavender', 'amber' ), true ) ? $theme : 'rose';

        // Focus highlight theme — default to 'amber' unless explicitly set
        $focus = isset( $input['focus_theme'] ) ? sanitize_text_field( $input['focus_theme'] ) : 'amber';
        $sanitized_input['focus_theme'] = in_array( $focus, array( 'rose', 'blue', 'gray', 'sage', 'lavender', 'amber' ), true ) ? $focus : 'amber';

        $wl = isset( $input['warning_location'] ) ? sanitize_text_field( $input['warning_location'] ) : 'inplace';
        $sanitized_input['warning_location'] = in_array( $wl, array( 'inplace', 'top_notice' ), true ) ? $wl : 'inplace';

        $hl = isset( $input['last_highlight_ms'] ) ? intval( $input['last_highlight_ms'] ) : 3500;
        if ( $hl < 1000 ) { $hl = 1000; }
        if ( $hl > 10000 ) { $hl = 10000; }
        $sanitized_input['last_highlight_ms'] = $hl;

        $a11y = isset( $input['a11y_alert_role'] ) ? (int) !! $input['a11y_alert_role'] : 1;
        $sanitized_input['a11y_alert_role'] = $a11y;

        // Sepet & Ödeme Mesaj Konumu (Kademeli İndirim)
        // Varsayılan: ürün altı (under_item) açık, blok alan kapalı
        $sanitized_input['cart_msg_under_item'] = isset( $input['cart_msg_under_item'] ) ? (int) !! $input['cart_msg_under_item'] : 1;
        $sanitized_input['cart_msg_block_area'] = isset( $input['cart_msg_block_area'] ) ? (int) !! $input['cart_msg_block_area'] : 0;

        // Özel kampanya mesajlarını ürün satırı altında göster (varsayılan: açık)
        $sanitized_input['special_msg_under_item'] = isset( $input['special_msg_under_item'] ) ? (int) !! $input['special_msg_under_item'] : 1;

        // Ürün Mesajı (ürün sayfası)
        $msg_loc = isset( $input['product_message_location'] ) ? sanitize_text_field( $input['product_message_location'] ) : 'auto';
        $allowed_msg_locs = array( 'auto', 'summary', 'price_above', 'button_before', 'button_after' );
        $sanitized_input['product_message_location'] = in_array( $msg_loc, $allowed_msg_locs, true ) ? $msg_loc : 'auto';
        $sanitized_input['product_message_force'] = isset( $input['product_message_force'] ) ? (int) !! $input['product_message_force'] : 0;

        // Ürün Sayfası Kademe Tablosu
        $sanitized_input['tier_table_enabled'] = isset( $input['tier_table_enabled'] ) ? (int) !! $input['tier_table_enabled'] : 1;
        $loc = isset( $input['tier_table_location'] ) ? sanitize_text_field( $input['tier_table_location'] ) : 'auto';
        $allowed_locs = array( 'auto', 'summary', 'price_above', 'button_before', 'button_after' );
        $sanitized_input['tier_table_location'] = in_array( $loc, $allowed_locs, true ) ? $loc : 'auto';
        $sanitized_input['tier_table_force'] = isset( $input['tier_table_force'] ) ? (int) !! $input['tier_table_force'] : 0;

        // Üstü Çizili Fiyat (varsayılan: kapalı)
        $sanitized_input['strikethrough_price_enabled'] = isset( $input['strikethrough_price_enabled'] ) ? (int) !! $input['strikethrough_price_enabled'] : 0;

        // Kademe Tablosu Renk Ayarı
        $sanitized_input['tier_theme_use_custom'] = isset( $input['tier_theme_use_custom'] ) ? (int) !! $input['tier_theme_use_custom'] : 0;
        // Özel renk: geçerli hex değilse boş bırak
        $custom_color = isset( $input['tier_theme_color'] ) ? sanitize_text_field( $input['tier_theme_color'] ) : '';
        // Hex rengi normalize et (# yoksa ekle)
        if ( $custom_color && ! str_starts_with( $custom_color, '#' ) ) {
            $custom_color = '#' . $custom_color;
        }
        if ( function_exists('sanitize_hex_color') ) {
            $custom_color = sanitize_hex_color( $custom_color );
        }
        // Eğer sanitize_hex_color yoksa veya başarısız olduysa, basit regex kontrolü yap
        if ( ! $custom_color && isset( $input['tier_theme_color'] ) ) {
            $raw = sanitize_text_field( $input['tier_theme_color'] );
            if ( $raw && ! str_starts_with( $raw, '#' ) ) {
                $raw = '#' . $raw;
            }
            if ( preg_match( '/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/', $raw ) ) {
                $custom_color = strtolower( $raw );
            }
        }
        $sanitized_input['tier_theme_color'] = $custom_color ? $custom_color : '';
        $preset = isset( $input['tier_theme_preset'] ) ? sanitize_text_field( $input['tier_theme_preset'] ) : 'blue';
        $allowed_presets = array( 'rose','blue','gray','sage','lavender','amber' );
        $sanitized_input['tier_theme_preset'] = in_array( $preset, $allowed_presets, true ) ? $preset : 'blue';

        // Rules Behavior
        $sanitized_input['auto_fill_category_from_products'] = isset( $input['auto_fill_category_from_products'] ) ? (int) !! $input['auto_fill_category_from_products'] : 1;

        // Notifications
        $sanitized_input['notifications_enabled'] = isset( $input['notifications_enabled'] ) ? (int) !! $input['notifications_enabled'] : 0;

        // Advanced
        $tt = isset( $input['trigger_timing'] ) ? sanitize_text_field( $input['trigger_timing'] ) : 'realtime';
        $sanitized_input['trigger_timing'] = in_array( $tt, array( 'realtime', 'blur' ), true ) ? $tt : 'realtime';

        // Frontend cache'lerini hemen temizle (tier tablosu, mesajlar vb.)
        update_option( 'knsdd_cache_version', time() );
        
        // Object cache temizle (Redis/Memcached eklentileri için)
        wp_cache_delete( 'knsdd_global_settings', 'options' );
        wp_cache_flush_group( 'options' );
        
        // İlgili transient'leri temizle
        delete_transient( 'knsdd_all_rules' );
        delete_transient( 'knsdd_active_rules' );

        return $sanitized_input;
    }

    /**
     * Genel Aç/Kapa anahtarının HTML'ini oluşturur.
     */
    public function render_global_status_field() {
        $options = get_option( $this->option_name, ['global_status' => 1] );
        $status = isset( $options['global_status'] ) ? $options['global_status'] : 1;
        ?>
        <div class="knsdd-switch-wrapper">
            <label class="knsdd-toggle-switch">
                <input type="checkbox" id="knsdd_global_status" name="<?php echo esc_attr( $this->option_name ); ?>[global_status]" value="1" <?php checked( $status, 1 ); ?> />
                <span class="knsdd-toggle-slider" aria-hidden="true"></span>
            </label>
            <?php
            if ( $status ) {
                echo '<span id="knsdd-status-text-indicator" class="knsdd-status-text knsdd-status-text-active">' . esc_html__( 'Aktif', 'kns-dynamic-discounts-for-woocommerce' ) . '</span>';
            } else {
                echo '<span id="knsdd-status-text-indicator" class="knsdd-status-text knsdd-status-text-inactive">' . esc_html__( 'Pasif', 'kns-dynamic-discounts-for-woocommerce' ) . '</span>';
            }
            ?>
        </div>
        <p class="description">
            <?php esc_html_e( 'Bu anahtar kapalıysa, hiçbir indirim kuralı çalışmaz. Eklentiyi geçici olarak durdurmak için kullanabilirsiniz.', 'kns-dynamic-discounts-for-woocommerce' ); ?>
        </p>
        <?php
    }

    /**
     * Sayfanın HTML içeriğini oluşturur.
     */
    public function render_page() {
        ?>
        <div class="wrap">
            <h1><?php esc_html_e( 'Kns Dynamic Discounts Ayarları', 'kns-dynamic-discounts-for-woocommerce' ); ?></h1>
            
            <?php
            if ( isset( $_GET['settings-updated'] ) && sanitize_text_field( wp_unslash( $_GET['settings-updated'] ) ) ) {
                $saved_message = __( 'Değişiklikler başarıyla kaydedildi.', 'kns-dynamic-discounts-for-woocommerce' );
                echo '<div id="message" class="notice notice-success is-dismissible"><p><strong>' . esc_html( $saved_message ) . '</strong></p></div>';
            }
            ?>

            <form action="options.php" method="post" id="knsdd-settings-form" class="knsdd-settings-form">
                <?php settings_fields( $this->settings_group ); ?>

                <nav class="knsdd-tabs" role="tablist" aria-label="KNSDD Settings Tabs">
                    <a href="#tab-general" class="knsdd-tab is-active" role="tab" aria-controls="tab-general" aria-selected="true"><?php esc_html_e('Genel', 'kns-dynamic-discounts-for-woocommerce'); ?></a>
                    <a href="#tab-dates" class="knsdd-tab" role="tab" aria-controls="tab-dates" aria-selected="false"><?php esc_html_e('Tarih Yönetimi', 'kns-dynamic-discounts-for-woocommerce'); ?></a>
                    <a href="#tab-ui" class="knsdd-tab" role="tab" aria-controls="tab-ui" aria-selected="false"><?php esc_html_e('Arayüz ve Erişilebilirlik', 'kns-dynamic-discounts-for-woocommerce'); ?></a>
                    <a href="#tab-rules" class="knsdd-tab" role="tab" aria-controls="tab-rules" aria-selected="false"><?php esc_html_e('Kural Davranışları', 'kns-dynamic-discounts-for-woocommerce'); ?></a>
                    <a href="#tab-notifications" class="knsdd-tab" role="tab" aria-controls="tab-notifications" aria-selected="false"><?php esc_html_e('Bildirimler', 'kns-dynamic-discounts-for-woocommerce'); ?></a>
                    <a href="#tab-i18n" class="knsdd-tab" role="tab" aria-controls="tab-i18n" aria-selected="false"><?php esc_html_e('Dil Ayarları', 'kns-dynamic-discounts-for-woocommerce'); ?></a>
                    <a href="#tab-advanced" class="knsdd-tab" role="tab" aria-controls="tab-advanced" aria-selected="false"><?php esc_html_e('Gelişmiş', 'kns-dynamic-discounts-for-woocommerce'); ?></a>
                </nav>

                <div class="knsdd-tab-panels">
                    <section id="tab-general" class="knsdd-tab-panel is-active" role="tabpanel" tabindex="0">
                        <div class="knsdd-tab-body"></div>
                    </section>
                    <section id="tab-dates" class="knsdd-tab-panel" role="tabpanel" tabindex="0">
                        <div class="knsdd-tab-body"></div>
                    </section>
                    <section id="tab-ui" class="knsdd-tab-panel" role="tabpanel" tabindex="0">
                        <div class="knsdd-tab-body"></div>
                    </section>
                    <section id="tab-rules" class="knsdd-tab-panel" role="tabpanel" tabindex="0">
                        <div class="knsdd-tab-body"></div>
                    </section>
                    <section id="tab-notifications" class="knsdd-tab-panel" role="tabpanel" tabindex="0">
                        <div class="knsdd-tab-body"></div>
                    </section>
                    <section id="tab-i18n" class="knsdd-tab-panel" role="tabpanel" tabindex="0">
                        <div class="knsdd-tab-body"></div>
                    </section>
                    <section id="tab-advanced" class="knsdd-tab-panel" role="tabpanel" tabindex="0">
                        <div class="knsdd-tab-body"></div>
                    </section>
                    
                </div>

                <!-- Erişilebilirlik için gizli bölümler -->
                <div id="knsdd-settings-sections-raw" class="screen-reader-text">
                    <?php do_settings_sections( $this->settings_group ); ?>
                </div>

                <!-- Sayfanın en altında statik butonlar -->
                <div class="knsdd-settings-actions">
                    <?php submit_button( __( 'Değişiklikleri Kaydet', 'kns-dynamic-discounts-for-woocommerce' ), 'primary', 'submit', false ); ?>
                    <button type="button" class="button button-secondary knsdd-reset-to-defaults"><?php esc_html_e('Varsayılanlara Dön', 'kns-dynamic-discounts-for-woocommerce'); ?></button>
                </div>
            </form>
        </div>
        <?php
        $this->add_inline_script();
    }

    public function render_language_mode_field() {
        $options = get_option( $this->option_name, array( 'language_mode' => 'auto' ) );
        $mode = isset( $options['language_mode'] ) ? $options['language_mode'] : 'auto';
        ?>
        <fieldset>
            <label><input type="radio" name="<?php echo esc_attr( $this->option_name ); ?>[language_mode]" value="auto" <?php checked( $mode, 'auto' ); ?> /> <?php esc_html_e( 'Otomatik (WordPress site diline göre)', 'kns-dynamic-discounts-for-woocommerce' ); ?></label><br />
            <label><input type="radio" name="<?php echo esc_attr( $this->option_name ); ?>[language_mode]" value="manual" <?php checked( $mode, 'manual' ); ?> /> <?php esc_html_e( 'Manuel', 'kns-dynamic-discounts-for-woocommerce' ); ?></label>
        </fieldset>
        <?php
    }

    public function render_language_locale_field() {
        $options = get_option( $this->option_name, array( 'language_locale' => 'en_US' ) );
        $current = isset( $options['language_locale'] ) ? $options['language_locale'] : 'en_US';
        $locales = KNSDD_Utils::get_supported_locales();
        ?>
        <select name="<?php echo esc_attr( $this->option_name ); ?>[language_locale]">
            <?php foreach ( $locales as $locale => $label ) : ?>
                <option value="<?php echo esc_attr( $locale ); ?>" <?php selected( $current, $locale ); ?>><?php echo esc_html( $label . ' (' . $locale . ')' ); ?></option>
            <?php endforeach; ?>
        </select>
        <p class="description"><?php esc_html_e( 'Manuel mod seçiliyse geçerli olur. Aksi halde WordPress site dili kullanılır. Desteklenen diller arasında değilse varsayılan İngilizce (en_US) kullanılır.', 'kns-dynamic-discounts-for-woocommerce' ); ?></p>
        <?php
    }

    // Tarih Yönetimi: Alanlar
    public function render_conflict_action_field() {
        $options = get_option( $this->option_name, array( 'conflict_action' => 'revert' ) );
        $current = isset( $options['conflict_action'] ) ? $options['conflict_action'] : 'revert';
        ?>
        <select name="<?php echo esc_attr( $this->option_name ); ?>[conflict_action]">
            <option value="revert" <?php selected( $current, 'revert' ); ?>><?php esc_html_e('Son geçerli tarihe geri al', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="clear" <?php selected( $current, 'clear' ); ?>><?php esc_html_e('Tarih Alanlarını temizle (yeniden seçtir)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
        </select>
        <p class="description"><?php esc_html_e('Seçilen tarih aralığı başka bir kuralla uyuşmazlık gösterirse ne yapılsın?', 'kns-dynamic-discounts-for-woocommerce'); ?></p>
        <?php
    }

    public function render_inline_warning_ms_field() {
        $options = get_option( $this->option_name, array( 'inline_warning_ms' => 5000 ) );
        $current = isset( $options['inline_warning_ms'] ) ? intval( $options['inline_warning_ms'] ) : 5000;
        ?>
        <input type="number" min="2000" max="15000" step="500" style="width:120px" name="<?php echo esc_attr( $this->option_name ); ?>[inline_warning_ms]" value="<?php echo esc_attr( $current ); ?>" />
        <p class="description"><?php esc_html_e('Uyarı Konumu seçiminize göre satır içi veya üst bildirim için uygulanır. Önerilen: 2.000–15.000 ms.', 'kns-dynamic-discounts-for-woocommerce'); ?></p>
        <?php
    }

    public function render_conflict_scope_field() {
        $options = get_option( $this->option_name, array( 'conflict_scope' => 'same_rules' ) );
        $current = isset( $options['conflict_scope'] ) ? $options['conflict_scope'] : 'same_rules';
        ?>
        <select name="<?php echo esc_attr( $this->option_name ); ?>[conflict_scope]">
            <option value="same_rules" <?php selected( $current, 'same_rules' ); ?>><?php esc_html_e('Sadece aynı kural setinde', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="all" <?php selected( $current, 'all' ); ?>><?php esc_html_e('Tüm gruplar ve kurallar arasında', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
        </select>
        <p class="description"><?php esc_html_e('Tarih uyuşmazlığı hangi kurallar arasında denetlensin?', 'kns-dynamic-discounts-for-woocommerce'); ?></p>
        <?php
    }

    public function render_validate_same_day_field() {
        $options = get_option( $this->option_name, array( 'validate_same_day' => 1 ) );
        $checked = ! empty( $options['validate_same_day'] );
        ?>
        <label>
            <input type="checkbox" name="<?php echo esc_attr( $this->option_name ); ?>[validate_same_day]" value="1" <?php checked( $checked ); ?> />
            <?php esc_html_e('Başlangıç tarihi = Bitiş tarihi ise aralığı geçerli say', 'kns-dynamic-discounts-for-woocommerce'); ?>
        </label>
        <p class="description"><?php esc_html_e('Tek günlük kampanyalar için işaretleyin.', 'kns-dynamic-discounts-for-woocommerce'); ?></p>
        <?php
    }

    public function render_date_alt_format_field() {
        $options = get_option( $this->option_name, array( 'date_alt_format' => 'd.m.Y' ) );
        $current = isset( $options['date_alt_format'] ) ? $options['date_alt_format'] : 'd.m.Y';
        ?>
        <select name="<?php echo esc_attr( $this->option_name ); ?>[date_alt_format]">
            <option value="d.m.Y" <?php selected( $current, 'd.m.Y' ); ?>><?php esc_html_e('d.m.Y (18.08.2025)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="d/m/Y" <?php selected( $current, 'd/m/Y' ); ?>><?php esc_html_e('d/m/Y (18/08/2025)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="Y-m-d" <?php selected( $current, 'Y-m-d' ); ?>><?php esc_html_e('Y-m-d (2025-08-18)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
        </select>
        <p class="description"><?php esc_html_e('Tarihin arayüzde nasıl görüneceği.', 'kns-dynamic-discounts-for-woocommerce'); ?></p>
        <?php
    }

    public function render_lock_started_campaigns_field() {
        $options = get_option( $this->option_name, array() );
        // Varsayılan: 1 (açık) - Eğer ayar hiç set edilmemişse açık olmalı
        $lock_value = isset( $options['lock_started_campaigns'] ) ? $options['lock_started_campaigns'] : 1;
        $checked = ! empty( $lock_value );
        ?>
        <label>
            <input type="checkbox" name="<?php echo esc_attr( $this->option_name ); ?>[lock_started_campaigns]" value="1" <?php checked( $checked ); ?> />
            <?php esc_html_e('Başlamış kampanyaların başlangıç tarihini değiştirmeyi engelle', 'kns-dynamic-discounts-for-woocommerce'); ?>
        </label>
        <p class="description">
            <?php esc_html_e('Bu seçenek AÇIKKEN: Başlamış kampanyaların başlangıç tarihi değiştirilemez. Kampanya verisi tutarlı kalır (ÖNERİLİR).', 'kns-dynamic-discounts-for-woocommerce'); ?>
            <br>
            <?php esc_html_e('Bu seçenek KAPALI IKEN: Tüm tarihler her zaman düzenlenebilir. Esneklik artar ama kampanya verisi tutarsız olabilir.', 'kns-dynamic-discounts-for-woocommerce'); ?>
            <br>
            <strong><?php esc_html_e('Not:', 'kns-dynamic-discounts-for-woocommerce'); ?></strong> <?php esc_html_e('Geçmiş kampanyalar her durumda kilitli kalır.', 'kns-dynamic-discounts-for-woocommerce'); ?>
        </p>
        <?php
    }

    // UI & Accessibility: Fields
    public function render_warning_theme_field() {
        $options = get_option( $this->option_name, array( 'warning_theme' => 'rose' ) );
        $current = isset( $options['warning_theme'] ) ? $options['warning_theme'] : 'rose';
        ?>
        <select name="<?php echo esc_attr( $this->option_name ); ?>[warning_theme]" id="knsdd-warning-theme">
            <option value="rose" <?php selected( $current, 'rose' ); ?>><?php esc_html_e('Gül (rose)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="blue" <?php selected( $current, 'blue' ); ?>><?php esc_html_e('Gökyüzü (blue)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="gray" <?php selected( $current, 'gray' ); ?>><?php esc_html_e('Füme (gray)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="sage" <?php selected( $current, 'sage' ); ?>><?php esc_html_e('Adaçayı (sage)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="lavender" <?php selected( $current, 'lavender' ); ?>><?php esc_html_e('Lavanta (lavender)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="amber" <?php selected( $current, 'amber' ); ?>><?php esc_html_e('Kehribar (amber)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
        </select>
        <div class="knsdd-theme-preview<?php echo ' theme-' . esc_attr( $current ); ?>">
            <div class="preview-box" aria-live="polite"><?php esc_html_e('Örnek uyarı metni', 'kns-dynamic-discounts-for-woocommerce'); ?></div>
        </div>
        <p class="description"><?php esc_html_e('Uyarı kutuları için renk paleti. Aşağıda önizlemeyi görebilirsiniz.', 'kns-dynamic-discounts-for-woocommerce'); ?></p>
        <?php
    }

    public function render_focus_theme_field() {
        $options = get_option( $this->option_name, array( 'focus_theme' => 'amber' ) );
        $current = isset( $options['focus_theme'] ) ? $options['focus_theme'] : 'amber';
        ?>
        <select name="<?php echo esc_attr( $this->option_name ); ?>[focus_theme]" id="knsdd-focus-theme">
            <option value="rose" <?php selected( $current, 'rose' ); ?>><?php esc_html_e('Gül (rose)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="blue" <?php selected( $current, 'blue' ); ?>><?php esc_html_e('Gökyüzü (blue)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="gray" <?php selected( $current, 'gray' ); ?>><?php esc_html_e('Füme (gray)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="sage" <?php selected( $current, 'sage' ); ?>><?php esc_html_e('Adaçayı (sage)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="lavender" <?php selected( $current, 'lavender' ); ?>><?php esc_html_e('Lavanta (lavender)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="amber" <?php selected( $current, 'amber' ); ?>><?php esc_html_e('Kehribar (amber)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
        </select>
        <div class="knsdd-theme-preview<?php echo ' theme-' . esc_attr( $current ); ?>">
            <div class="preview-box" aria-live="polite"><?php esc_html_e('Örnek son odak vurgusu rengi', 'kns-dynamic-discounts-for-woocommerce'); ?></div>
        </div>
        <p class="description"><?php esc_html_e("Gruplar sayfasında son etkileşimi yaptığınız alanın vurgusunun rengini belirler.", 'kns-dynamic-discounts-for-woocommerce'); ?></p>
        <?php
    }

    public function render_warning_location_field() {
        $options = get_option( $this->option_name, array( 'warning_location' => 'inplace' ) );
        $current = isset( $options['warning_location'] ) ? $options['warning_location'] : 'inplace';
        ?>
        <select name="<?php echo esc_attr( $this->option_name ); ?>[warning_location]">
            <option value="inplace" <?php selected( $current, 'inplace' ); ?>><?php esc_html_e('Satır içi (form alanının içinde)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="top_notice" <?php selected( $current, 'top_notice' ); ?>><?php esc_html_e('Üstte bildirim (toast)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
        </select>
        <p class="description"><?php esc_html_e('Uyarı mesajı nerede gösterilsin?', 'kns-dynamic-discounts-for-woocommerce'); ?></p>
        <?php
    }

    public function render_last_highlight_ms_field() {
        $options = get_option( $this->option_name, array( 'last_highlight_ms' => 3500 ) );
        $current = isset( $options['last_highlight_ms'] ) ? intval( $options['last_highlight_ms'] ) : 3500;
        ?>
        <input type="number" min="1000" max="10000" step="250" style="width:120px" name="<?php echo esc_attr( $this->option_name ); ?>[last_highlight_ms]" value="<?php echo esc_attr( $current ); ?>" />
        <p class="description"><?php esc_html_e('Gruplar sayfasında son etkileşimi yaptığınız alanın vurgusunun ekranda kalma süresi. Önerilen: 1.000–10.000 ms.', 'kns-dynamic-discounts-for-woocommerce'); ?></p>
        <?php
    }

    public function render_a11y_alert_role_field() {
        $options = get_option( $this->option_name, array( 'a11y_alert_role' => 1 ) );
        $checked = ! empty( $options['a11y_alert_role'] );
        ?>
        <label>
            <input type="checkbox" name="<?php echo esc_attr( $this->option_name ); ?>[a11y_alert_role]" value="1" <?php checked( $checked ); ?> />
            <?php esc_html_e('Satır içi uyarılara role="alert" ekle', 'kns-dynamic-discounts-for-woocommerce'); ?>
        </label>
        <p class="description"><?php esc_html_e('Ekran okuyucuların uyarıları anında okumasını sağlar.', 'kns-dynamic-discounts-for-woocommerce'); ?></p>
        <?php
    }

    /**
     * Mini Sepet & Sepet & Ödeme Mesaj Konumu (Kademeli İndirim Mesaj Konumu)
     * 2 checkbox: ürün altı (varsayılan açık), blok alan (varsayılan kapalı)
     */
    public function render_cart_msg_positions_field() {
        $defaults = array(
            'cart_msg_under_item' => 1,
            'cart_msg_block_area' => 0,
        );
        $options = get_option( $this->option_name, $defaults );
        $under = isset( $options['cart_msg_under_item'] ) ? (int) !!$options['cart_msg_under_item'] : 1;
        $block = isset( $options['cart_msg_block_area'] ) ? (int) !!$options['cart_msg_block_area'] : 0;
        ?>
        <fieldset>
            <label style="display:block; margin-bottom:6px;">
                <input type="checkbox" name="<?php echo esc_attr( $this->option_name ); ?>[cart_msg_under_item]" value="1" <?php checked( $under, 1 ); ?> />
                <?php esc_html_e('Ürün bloğunun hemen altında (varsayılan)', 'kns-dynamic-discounts-for-woocommerce'); ?>
            </label>
            <label style="display:block;">
                <input type="checkbox" name="<?php echo esc_attr( $this->option_name ); ?>[cart_msg_block_area]" value="1" <?php checked( $block, 1 ); ?> />
                <?php esc_html_e('Toplam/Buton alanında blok olarak', 'kns-dynamic-discounts-for-woocommerce'); ?>
            </label>
        </fieldset>
        <p class="description">
            <?php esc_html_e('Kademeli (miktar) indirim mesajları için geçerlidir. "Ürün altı" AÇIK ise kademeli mesajlar satır altında gösterilir ve blok alanda yinelenmez. Sepet-genel kampanyalar (örn. sepet tutarı indirimi) blok alanda kalmaya devam eder.', 'kns-dynamic-discounts-for-woocommerce'); ?>
        </p>
        <?php
    }

    /**
     * Özel Kampanya Mesajları: Ürün Satırı Altında Göster
     * Varsayılan: AÇIK
     */
    public function render_special_msg_under_item_field() {
        $options = get_option( $this->option_name, array( 'special_msg_under_item' => 1 ) );
        $checked = isset( $options['special_msg_under_item'] ) ? (int) !! $options['special_msg_under_item'] : 1;
        ?>
        <label>
            <input type="hidden" name="<?php echo esc_attr( $this->option_name ); ?>[special_msg_under_item]" value="0" />
            <input type="checkbox" name="<?php echo esc_attr( $this->option_name ); ?>[special_msg_under_item]" value="1" <?php checked( $checked, 1 ); ?> />
            <?php esc_html_e('Buy X Pay Y, N\'inci ürüne %… gibi ürün-bazlı özel kampanya mesajlarını ürün adının hemen altında göster', 'kns-dynamic-discounts-for-woocommerce'); ?>
        </label>
        <p class="description">
            <?php esc_html_e('Sepet toplamına göre indirim (cart_total) kampanyaları blok alanda kalır. Bu seçenek yalnız ürünle ilişkili özel kampanyaları satır altında gösterir.', 'kns-dynamic-discounts-for-woocommerce'); ?>
        </p>
        <?php
    }

    /**
     * Ürün Mesajı Konumu (ürün sayfası)
     */
    public function render_product_message_location_field() {
        $options = get_option( $this->option_name, array( 'product_message_location' => 'auto' ) );
        $current = isset( $options['product_message_location'] ) ? $options['product_message_location'] : 'auto';
        ?>
        <select name="<?php echo esc_attr( $this->option_name ); ?>[product_message_location]">
            <option value="auto" <?php selected( $current, 'auto' ); ?>><?php esc_html_e('Otomatik (Sepete ekle üstü - önerilen)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="button_before" <?php selected( $current, 'button_before' ); ?>><?php esc_html_e('Sepete ekle üstü', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="button_after" <?php selected( $current, 'button_after' ); ?>><?php esc_html_e('Sepete ekle altı', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="price_above" <?php selected( $current, 'price_above' ); ?>><?php esc_html_e('Fiyat üstü', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="summary" <?php selected( $current, 'summary' ); ?>><?php esc_html_e('Ürün özeti', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
        </select>
        <p class="description"><?php esc_html_e('Otomatik: En görünür ve uyumlu konumu bulmak için sırayla dener: 1) Sepete ekle üstü (tercih edilen), 2) Fiyat üstü, 3) Sepete ekle altı. İlk çalışan konum uygulanır.', 'kns-dynamic-discounts-for-woocommerce'); ?></p>
        <p class="description"><?php esc_html_e('Not: Otomatik dışındaki konumları seçerseniz fallback uygulanmaz; tema/builder bu kancayı tetiklemezse mesaj görünmeyebilir.', 'kns-dynamic-discounts-for-woocommerce'); ?></p>
        <?php
    }

    /**
     * Ürün Mesajı Konumu: Zorla (tema/builder uyumluluğu)
     */
    public function render_product_message_force_field() {
        $options = get_option( $this->option_name, array( 'product_message_force' => 0 ) );
        $checked = ! empty( $options['product_message_force'] );
        ?>
        <label>
            <input type="hidden" name="<?php echo esc_attr( $this->option_name ); ?>[product_message_force]" value="0" />
            <input type="checkbox" name="<?php echo esc_attr( $this->option_name ); ?>[product_message_force]" value="1" <?php checked( $checked ); ?> />
            <?php esc_html_e('Seçili ürün mesajı konumu, tema/builder farklarına rağmen DOM içinde kesin olarak uygula.', 'kns-dynamic-discounts-for-woocommerce'); ?>
        </label>
        <p class="description"><?php esc_html_e('Bu seçenek açıkken ürün mesajı konteyneri, seçtiğiniz konuma JavaScript ile taşınır. Elementor/özel şablon reflow’larında da konum korunur.', 'kns-dynamic-discounts-for-woocommerce'); ?></p>
        <?php
    }

    /**
     * Ürün Sayfası Kademe Tablosu: Etkin/Pasif
     */
    public function render_tier_table_enabled_field() {
        $options = get_option( $this->option_name, array( 'tier_table_enabled' => 1 ) );
        $checked = isset( $options['tier_table_enabled'] ) ? (int) $options['tier_table_enabled'] : 1;
        ?>
        <label>
            <input type="hidden" name="<?php echo esc_attr( $this->option_name ); ?>[tier_table_enabled]" value="0" />
            <input type="checkbox" name="<?php echo esc_attr( $this->option_name ); ?>[tier_table_enabled]" value="1" <?php checked( $checked ); ?> />
            <?php esc_html_e('Ürün sayfasında miktar kademelerini göster', 'kns-dynamic-discounts-for-woocommerce'); ?>
        </label>
        <p class="description"><?php esc_html_e('Kademe İndirim Tablosu, Otomatik seçiliyken şu sıraya göre yerleştirilir. Sepete ekle üstü → Fiyat üstü → Sepete ekle altı. İlk uygun kancada gösterilir.', 'kns-dynamic-discounts-for-woocommerce'); ?></p>
        <?php
    }

    /**
     * Kademe Tablosu Konumu
     */
    public function render_tier_table_location_field() {
        $options = get_option( $this->option_name, array( 'tier_table_location' => 'auto' ) );
        $current = isset( $options['tier_table_location'] ) ? $options['tier_table_location'] : 'auto';
        ?>
        <select name="<?php echo esc_attr( $this->option_name ); ?>[tier_table_location]">
            <option value="auto" <?php selected( $current, 'auto' ); ?>><?php esc_html_e('Otomatik (Sepete ekle üstü - önerilen)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="button_before" <?php selected( $current, 'button_before' ); ?>><?php esc_html_e('Sepete ekle üstü', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="button_after" <?php selected( $current, 'button_after' ); ?>><?php esc_html_e('Sepete ekle altı', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="price_above" <?php selected( $current, 'price_above' ); ?>><?php esc_html_e('Fiyat üstü', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="summary" <?php selected( $current, 'summary' ); ?>><?php esc_html_e('Ürün özeti', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
        </select>
        <p class="description"><?php esc_html_e('Otomatik: En görünür ve uyumlu konumu bulmak için sırayla dener: 1) Sepete ekle üstü (tercih edilen), 2) Fiyat üstü (fiyatın hemen üzerinde), 3) Sepete ekle altı. İlk çalışan konum uygulanır.', 'kns-dynamic-discounts-for-woocommerce'); ?></p>
        <p class="description"><?php esc_html_e('Not: Otomatik dışındaki konumları seçerseniz fallback uygulanmaz. Tema/builder bu kancayı tetiklemezse tablo görünmeyebilir.', 'kns-dynamic-discounts-for-woocommerce'); ?></p>
        <?php
    }

    /**
     * Kademe Tablosu Konumu: Zorla (tema/builder uyumluluğu)
     */
    public function render_tier_table_force_field() {
        $options = get_option( $this->option_name, array( 'tier_table_force' => 0 ) );
        $checked = ! empty( $options['tier_table_force'] );
        ?>
        <label>
            <input type="hidden" name="<?php echo esc_attr( $this->option_name ); ?>[tier_table_force]" value="0" />
            <input type="checkbox" name="<?php echo esc_attr( $this->option_name ); ?>[tier_table_force]" value="1" <?php checked( $checked ); ?> />
            <?php esc_html_e('Seçili kademe indirim tablosu konumu, tema/builder farklarına rağmen DOM içinde kesin olarak uygula.', 'kns-dynamic-discounts-for-woocommerce'); ?>
        </label>
        <p class="description"><?php esc_html_e('Bu seçenek açıkken tablo konteyneri, seçtiğiniz konuma JavaScript ile taşınır. Elementor/özel şablon reflow’larında da konum korunur.', 'kns-dynamic-discounts-for-woocommerce'); ?></p>
        <?php
    }

    /**
     * Kademe Tablosu: Tema Renk Ayarı (Özel renk)
     */
    public function render_tier_theme_use_custom_field() {
        $defaults = array( 'tier_theme_use_custom' => 0, 'tier_theme_color' => '' );
        $options = get_option( $this->option_name, $defaults );
        $use_custom = ! empty( $options['tier_theme_use_custom'] );
        $color = isset( $options['tier_theme_color'] ) ? $options['tier_theme_color'] : '';
        ?>
        <label>
            <input type="hidden" name="<?php echo esc_attr( $this->option_name ); ?>[tier_theme_use_custom]" value="0" />
            <input type="checkbox" name="<?php echo esc_attr( $this->option_name ); ?>[tier_theme_use_custom]" value="1" <?php checked( $use_custom ); ?> />
            <?php esc_html_e('İşaretliyse aşağıdaki renk uygulanır. Değilse alttaki Renk Teması geçerli olur.', 'kns-dynamic-discounts-for-woocommerce'); ?>
        </label>
        <div id="knsdd-tier-custom-row" style="margin-top:8px;display:flex;gap:12px;align-items:center;">
            <label for="knsdd-tier-theme-color" class="knsdd-inline-label"><strong><?php esc_html_e('Özel renk', 'kns-dynamic-discounts-for-woocommerce'); ?></strong></label>
            <input id="knsdd-tier-theme-color" type="color" name="<?php echo esc_attr( $this->option_name ); ?>[tier_theme_color]" value="<?php echo esc_attr( $color ); ?>" />
            <div class="knsdd-tier-custom-controls" style="display: flex; gap:2px; align-items:center;">
                <label for="knsdd-tier-theme-hex" class="knsdd-inline-label" style="min-width:auto;margin-right:2px;"><?php esc_html_e('Hex', 'kns-dynamic-discounts-for-woocommerce'); ?></label>
                <input id="knsdd-tier-theme-hex" type="text" class="knsdd-hex-input" value="<?php echo esc_attr( $color ); ?>" inputmode="text" spellcheck="false" />
                <button type="button" class="button button-secondary knsdd-tier-color-reset"><?php esc_html_e('Sıfırla', 'kns-dynamic-discounts-for-woocommerce'); ?></button>
            </div>
            <span class="description"><?php esc_html_e('İşaretliyse tablo tonu bu renge göre ayarlanır.', 'kns-dynamic-discounts-for-woocommerce'); ?></span>
        </div>
        <?php
    }

    /**
     * Kademe Tablosu Renk Teması (Hazır palet)
     */
    public function render_tier_theme_preset_field() {
        $options = get_option( $this->option_name, array( 'tier_theme_preset' => 'blue' ) );
        $current = isset( $options['tier_theme_preset'] ) ? $options['tier_theme_preset'] : 'blue';
        ?>
        <select name="<?php echo esc_attr( $this->option_name ); ?>[tier_theme_preset]" id="knsdd-tier-theme-preset">
            <option value="rose" <?php selected( $current, 'rose' ); ?>><?php esc_html_e('Gül (rose)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="blue" <?php selected( $current, 'blue' ); ?>><?php esc_html_e('Gökyüzü (blue)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="gray" <?php selected( $current, 'gray' ); ?>><?php esc_html_e('Füme (gray)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="sage" <?php selected( $current, 'sage' ); ?>><?php esc_html_e('Adaçayı (sage)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="lavender" <?php selected( $current, 'lavender' ); ?>><?php esc_html_e('Lavanta (lavender)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="amber" <?php selected( $current, 'amber' ); ?>><?php esc_html_e('Kehribar (amber)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
        </select>
        <div class="knsdd-tier-theme-preview" aria-live="polite">
            <div class="preview-box" data-i18n-key="sample_table_tone"></div>
        </div>
        <p class="description"><?php esc_html_e('Özel renk kapalıyken tablo rengi, seçtiğiniz Renk Teması’na göre ayarlanır. Varsayılan: Gökyüzü (blue).', 'kns-dynamic-discounts-for-woocommerce'); ?></p>
        <?php
    }

    public function render_auto_fill_category_field() {
        $options = get_option( $this->option_name, array( 'auto_fill_category_from_products' => 1 ) );
        $checked = isset( $options['auto_fill_category_from_products'] ) ? (int) $options['auto_fill_category_from_products'] : 1;
        ?>
        <label>
            <input type="hidden" name="<?php echo esc_attr( $this->option_name ); ?>[auto_fill_category_from_products]" value="0" />
            <input type="checkbox" name="<?php echo esc_attr( $this->option_name ); ?>[auto_fill_category_from_products]" value="1" <?php checked( $checked ); ?> />
            <?php esc_html_e('Kategori alanı boşken, seçili ürün(ler)in ortak kategorisi tek ise kategori alanını otomatik doldur.', 'kns-dynamic-discounts-for-woocommerce'); ?>
        </label>
        <?php
    }

    // Advanced: Fields
    public function render_trigger_timing_field() {
        $options = get_option( $this->option_name, array( 'trigger_timing' => 'realtime' ) );
        $current = isset( $options['trigger_timing'] ) ? $options['trigger_timing'] : 'realtime';
        ?>
        <select name="<?php echo esc_attr( $this->option_name ); ?>[trigger_timing]">
            <option value="realtime" <?php selected( $current, 'realtime' ); ?>><?php esc_html_e('Anında (yazarken)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
            <option value="blur" <?php selected( $current, 'blur' ); ?>><?php esc_html_e('Alan dışına çıkınca (blur)', 'kns-dynamic-discounts-for-woocommerce'); ?></option>
        </select>
        <p class="description"><?php esc_html_e('Tarih alanındaki değişiklikler ne zaman kontrol edilsin ve uygulansın?', 'kns-dynamic-discounts-for-woocommerce'); ?></p>
        <?php
    }

    /**
     * Bildirim Sistemi alanı
     */
    public function render_notifications_enabled_field() {
        $options = get_option( $this->option_name, array( 'notifications_enabled' => 1 ) );
        $checked = ! empty( $options['notifications_enabled'] );
        ?>
        <label>
            <input type="checkbox" name="<?php echo esc_attr( $this->option_name ); ?>[notifications_enabled]" value="1" <?php checked( $checked ); ?> />
            <?php esc_html_e('Bildirim sistemini aktif et', 'kns-dynamic-discounts-for-woocommerce'); ?>
        </label>
        <p class="description">
            <?php esc_html_e('Admin panelinde bildirim sistemi (FAB butonu) gösterilsin mi? Kapalıysa hiçbir bildirim gösterilmez.', 'kns-dynamic-discounts-for-woocommerce'); ?>
        </p>
        <?php
    }


    /**
     * Sadece bu sayfaya özel, anlık durum değişikliği ve kaydedilmemiş değişiklik uyarısı için JavaScript ekler.
     */
    private function add_inline_script() {
        $i18n_strings = array(
            'active'          => __( 'Aktif', 'kns-dynamic-discounts-for-woocommerce' ),
            'inactive'        => __( 'Pasif', 'kns-dynamic-discounts-for-woocommerce' ),
            'unsaved_changes' => __( 'Yaptığınız değişiklikler kaydedilmemiş olabilir.', 'kns-dynamic-discounts-for-woocommerce' ),
            'copied'          => __( 'Kopyalandı!', 'kns-dynamic-discounts-for-woocommerce' ),
            'copy_error'      => __( 'Hata!', 'kns-dynamic-discounts-for-woocommerce' ),
        );

        $js = 'jQuery(document).ready(function($) {' .
            'var i18n = ' . wp_json_encode( $i18n_strings ) . ';' .
            'var hasUnsavedChanges = false;' .
            '$("#knsdd_global_status, #knsdd-settings-form input, #knsdd-settings-form select").on("change", function() {' .
                'hasUnsavedChanges = true;' .
                'if ($(this).attr("id") === "knsdd_global_status") {' .
                    'var statusIndicator = $("#knsdd-status-text-indicator");' .
                    'if ($(this).is(":checked")) {' .
                        'statusIndicator.text(i18n.active).removeClass("knsdd-status-text-inactive").addClass("knsdd-status-text-active");' .
                    '} else {' .
                        'statusIndicator.text(i18n.inactive).removeClass("knsdd-status-text-active").addClass("knsdd-status-text-inactive");' .
                    '}' .
                '}' .
            '});' .
            '$("#knsdd-settings-form").on("submit", function() { hasUnsavedChanges = false; });' .
            '$(window).on("beforeunload", function() { if (hasUnsavedChanges) { return i18n.unsaved_changes; } });' .
            'var $notice = $("#message.notice");' .
            'if ($notice.length) { setTimeout(function() { $notice.fadeOut(500); }, 4000); }' .
        '});';

        wp_add_inline_script( 'knsdd-settings-js', $js );
    }

    /**
     * Sepet/Checkout Üstü Çizili Fiyat ayarının HTML'ini oluşturur.
     */
    public function render_strikethrough_price_field() {
        $options = get_option( $this->option_name, array( 'strikethrough_price_enabled' => 0 ) );
        $checked = isset( $options['strikethrough_price_enabled'] ) ? (int) $options['strikethrough_price_enabled'] : 0;
        ?>
        <label>
            <input type="hidden" name="<?php echo esc_attr( $this->option_name ); ?>[strikethrough_price_enabled]" value="0" />
            <input type="checkbox" name="<?php echo esc_attr( $this->option_name ); ?>[strikethrough_price_enabled]" value="1" <?php checked( $checked ); ?> />
            <?php esc_html_e( 'İndirim uygulanan ürünlerde orijinal fiyatı üstü çizili göster', 'kns-dynamic-discounts-for-woocommerce' ); ?>
        </label>
        <p class="description">
            <?php esc_html_e( 'Aktif olduğunda mini sepet, sepet ve ödeme sayfalarında indirimli ürünlerin orijinal fiyatı üstü çizili, yeni fiyatı vurgulu görünür.', 'kns-dynamic-discounts-for-woocommerce' ); ?>
        </p>
        <?php
    }
}
