<?php

if ( ! defined( 'ABSPATH' ) ) {
    die();
}

/**
 * Form Elements Framework for KANews Theme Widgets
 * 
 * @package KANews
 * @subpackage Widgets
 * @version 1.0.0
 * @author KANews Team
 */
class Kanews_Form_Elements {
    
    /**
     * Framework version
     */
    const VERSION = '1.0.0';
    
    /**
     * Form element types
     */
    const TYPE_TEXT = 'text';
    const TYPE_TEXTAREA = 'textarea';
    const TYPE_SELECT = 'select';
    const TYPE_CHECKBOX = 'checkbox';
    const TYPE_RADIO = 'radio';
    const TYPE_NUMBER = 'number';
    const TYPE_SLIDER = 'slider';
    const TYPE_COLOR = 'color';
    const TYPE_DATE = 'date';
    const TYPE_TIME = 'time';
    const TYPE_URL = 'url';
    const TYPE_EMAIL = 'email';
    const TYPE_PASSWORD = 'password';
    const TYPE_FILE = 'file';
    const TYPE_HIDDEN = 'hidden';
    const TYPE_HTML = 'html';
    const TYPE_SEPARATOR = 'separator';
    const TYPE_SELECT2_CATEGORIES = 'select2_categories';
    const TYPE_SELECT2_TAGS = 'select2_tags';
    const TYPE_SELECT2_TAXONOMY = 'select2_taxonomy';
    const TYPE_SELECT2_POSTS = 'select2_posts';
    const TYPE_ACCORDION = 'accordion';
    const TYPE_TOGGLE = 'toggle';
    const TYPE_MEDIA = 'media';
    const TYPE_SELECT2 = 'select2';
    const TYPE_ICON_PICKER = 'icon_picker';
    
    /**
     * Sanitize input value
     */
    private static function sanitize_value($value, $type = 'text') {
        switch ($type) {
            case 'url':
                return esc_url($value);
            case 'email':
                return sanitize_email($value);
            case 'html':
                return wp_kses_post($value);
            case 'textarea':
                return sanitize_textarea_field($value);
            case 'color':
                return sanitize_hex_color($value);
            case 'number':
                return filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
            default:
                return sanitize_text_field($value);
        }
    }
    
    /**
     * Render a form field
     */
    public static function render_field($field, $field_id, $field_name, $value) {
        // Render field based on type
        switch($field['type']) {
            case self::TYPE_TEXT:
                self::render_text_field($field_id, $field_name, $value, $field);
                break;
                
            case self::TYPE_TEXTAREA:
                self::render_textarea_field($field_id, $field_name, $value, $field);
                break;
                
            case self::TYPE_SELECT:
                self::render_select_field($field_id, $field_name, $value, $field);
                break;
                
            case self::TYPE_CHECKBOX:
                self::render_checkbox_field($field_id, $field_name, $value, $field);
                break;
                
            case self::TYPE_RADIO:
                self::render_radio_field($field_id, $field_name, $value, $field);
                break;
                
            case self::TYPE_NUMBER:
                self::render_number_field($field_id, $field_name, $value, $field);
                break;
                
            case self::TYPE_SLIDER:
                self::render_slider_field($field);
                break;
                
            case self::TYPE_COLOR:
                self::render_color_field($field_id, $field_name, $value, $field);
                break;
                
            case self::TYPE_DATE:
                self::render_date_field($field_id, $field_name, $value, $field);
                break;
                
            case self::TYPE_TIME:
                self::render_time_field($field_id, $field_name, $value, $field);
                break;
                
            case self::TYPE_URL:
                self::render_url_field($field_id, $field_name, $value, $field);
                break;
                
            case self::TYPE_EMAIL:
                self::render_email_field($field_id, $field_name, $value, $field);
                break;
                
            case self::TYPE_PASSWORD:
                self::render_password_field($field_id, $field_name, $value, $field);
                break;
                
            case self::TYPE_FILE:
                self::render_file_field($field_id, $field_name, $value, $field);
                break;
                
            case self::TYPE_HIDDEN:
                self::render_hidden_field($field_id, $field_name, $value, $field);
                break;
                
            case self::TYPE_HTML:
                self::render_html_field($field);
                break;
                
            case self::TYPE_SEPARATOR:
                self::render_separator_field($field);
                break;
                
            case self::TYPE_ACCORDION:
                self::render_accordion_field($field);
                break;
                
            case self::TYPE_SELECT2_CATEGORIES:
                self::render_select2_categories_field($field_id, $field_name, $value, $field);
                break;
                
            case self::TYPE_SELECT2_TAGS:
                self::render_select2_tags_field($field_id, $field_name, $value, $field);
                break;
                
            case self::TYPE_SELECT2_TAXONOMY:
                self::render_select2_taxonomy_field($field_id, $field_name, $value, $field);
                break;
                
            case self::TYPE_SELECT2_POSTS:
                self::render_select2_posts_field($field_id, $field_name, $value, $field);
                break;
                
            case self::TYPE_TOGGLE:
                self::render_toggle_field($field_id, $field_name, $value, $field);
                break;
                
            case self::TYPE_MEDIA:
                self::render_media_field($field_id, $field_name, $value, $field);
                break;
                
            case self::TYPE_SELECT2:
                self::render_select2_field($field_id, $field_name, $value, $field);
                break;
                
            case self::TYPE_ICON_PICKER:
                self::render_icon_picker_field($field_id, $field_name, $value, $field);
                break;
        }
    }
    
    /**
     * Render tooltip
     */
    private static function render_tooltip($text) {
        if (empty($text)) {
            return;
        }
        ?>
        <span class="kanews-tooltip-icon" data-tooltip="<?php echo esc_attr($text); ?>">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" 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>
                <line x1="12" y1="16" x2="12" y2="12"></line>
                <line x1="12" y1="8" x2="12.01" y2="8"></line>
            </svg>
        </span>
        <?php
    }

    /**
     * Render field label with tooltip
     */
    private static function render_field_label($field) {
        $label = isset($field['label']) ? $field['label'] : '';
        $description = isset($field['description']) ? $field['description'] : '';
        
        if (!empty($label)) {
            echo '<label class="kanews-field-label">';
            echo esc_html($label);
            if (!empty($description)) {
                self::render_tooltip($description);
            }
            echo '</label>';
        }
    }
    
    /**
     * Render text field
     */
    private static function render_text_field($field_id, $field_name, $value, $field) {
        $class = isset($field['class']) ? sanitize_html_class($field['class']) : 'widefat';
        $placeholder = isset($field['placeholder']) ? self::sanitize_value($field['placeholder']) : '';
        
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-text">';
        self::render_field_label($field);
        printf(
            '<input class="%s kanews-field kanews-field-text" id="%s" name="%s" type="text" value="%s"%s>',
            esc_attr($class),
            esc_attr($field_id),
            esc_attr($field_name),
            esc_attr(self::sanitize_value($value)),
            !empty($placeholder) ? ' placeholder="' . esc_attr($placeholder) . '"' : ''
        );
        echo '</div>';
    }
    
    /**
     * Render textarea field
     */
    private static function render_textarea_field($field_id, $field_name, $value, $field) {
        $class = isset($field['class']) ? sanitize_html_class($field['class']) : 'widefat';
        $rows = isset($field['rows']) ? absint($field['rows']) : 5;
        $cols = isset($field['cols']) ? absint($field['cols']) : 50;
        $placeholder = isset($field['placeholder']) ? self::sanitize_value($field['placeholder']) : '';
        $allow_html = isset($field['allow_html']) ? (bool)$field['allow_html'] : false;
        
        // HTML için güvenli etiketleri tanımla
        $allowed_html = array(
            'a' => array(
                'href' => array(),
                'title' => array(),
                'target' => array(),
                'rel' => array()
            ),
            'br' => array(),
            'em' => array(),
            'strong' => array(),
            'p' => array(),
            'div' => array(
                'class' => array(),
                'id' => array()
            ),
            'span' => array(
                'class' => array(),
                'id' => array()
            ),
            'img' => array(
                'src' => array(),
                'alt' => array(),
                'class' => array(),
                'id' => array(),
                'width' => array(),
                'height' => array()
            ),
            'ul' => array(),
            'ol' => array(),
            'li' => array(),
            'h1' => array(),
            'h2' => array(),
            'h3' => array(),
            'h4' => array(),
            'h5' => array(),
            'h6' => array(),
            'script' => array(
                'async' => array(),
                'src' => array(),
                'crossorigin' => array()
            ),
            'ins' => array(
                'class' => array(),
                'style' => array(),
                'data-ad-client' => array(),
                'data-ad-slot' => array(),
                'data-ad-format' => array(),
                'data-full-width-responsive' => array()
            ),
        );

        echo '<div class="kanews-field-wrapper kanews-field-wrapper-textarea">';
        self::render_field_label($field);
        
        // HTML editör için sınıf ekle
        $editor_class = $allow_html ? $class . ' html-active' : $class;
        
        printf(
            '<textarea class="%s kanews-field kanews-field-textarea" id="%s" name="%s" rows="%d" cols="%d"%s>%s</textarea>',
            esc_attr($editor_class),
            esc_attr($field_id),
            esc_attr($field_name),
            $rows,
            $cols,
            !empty($placeholder) ? ' placeholder="' . esc_attr($placeholder) . '"' : '',
            $allow_html ? wp_kses($value, $allowed_html) : esc_textarea(self::sanitize_value($value, 'textarea'))
        );

        // HTML desteği açıksa editör butonlarını ekle
        if ($allow_html) {
            ?>
            <div class="kanews-html-editor-tools">
                <button type="button" class="button" data-tag="strong" title="Kalın"><strong>B</strong></button>
                <button type="button" class="button" data-tag="em" title="İtalik"><em>I</em></button>
                <button type="button" class="button" data-tag="a" title="Link">Link</button>
                <button type="button" class="button" data-tag="img" title="Resim">Resim</button>
            </div>
            <script>
            (function($) {
                'use strict';
                $(document).ready(function() {
                    var $textarea = $('#<?php echo esc_js($field_id); ?>');
                    var $tools = $textarea.siblings('.kanews-html-editor-tools');

                    $tools.find('button').on('click', function(e) {
                        e.preventDefault();
                        var tag = $(this).data('tag');
                        var start = $textarea[0].selectionStart;
                        var end = $textarea[0].selectionEnd;
                        var text = $textarea.val();
                        var selectedText = text.substring(start, end);

                        switch(tag) {
                            case 'a':
                                var url = prompt('URL giriniz:', 'https://');
                                if (url) {
                                    var link = '<a href="' + url + '">' + (selectedText || 'Link Metni') + '</a>';
                                    $textarea.val(text.substring(0, start) + link + text.substring(end));
                                }
                                break;
                            case 'img':
                                var imgUrl = prompt('Resim URL giriniz:', 'https://');
                                if (imgUrl) {
                                    var alt = prompt('Resim açıklaması giriniz:', '');
                                    var img = '<img src="' + imgUrl + '" alt="' + alt + '">';
                                    $textarea.val(text.substring(0, start) + img + text.substring(end));
                                }
                                break;
                            default:
                                var wrapped = '<' + tag + '>' + selectedText + '</' + tag + '>';
                                $textarea.val(text.substring(0, start) + wrapped + text.substring(end));
                        }
                        
                        $textarea.trigger('change');
                    });
                });
            })(jQuery);
            </script>
            <style>
            .kanews-html-editor-tools {
                margin-top: 5px;
                padding: 5px;
                border: 1px solid #ddd;
                background: #f9f9f9;
                border-radius: 3px;
            }
            .kanews-html-editor-tools button {
                margin-right: 5px;
            }
            </style>
            <?php
        }

        echo '</div>';
    }
    
    /**
     * Render select field
     */
    private static function render_select_field($field_id, $field_name, $value, $field) {
        $options = isset($field['options']) ? $field['options'] : array();
        $multiple = isset($field['multiple']) ? $field['multiple'] : false;
        
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-select">';
        self::render_field_label($field);
        echo '<select class="kanews-select' . ($multiple ? ' kanews-select2' : '') . ' kanews-field kanews-field-select"';
        echo ' id="' . esc_attr($field_id) . '"';
        echo ' name="' . esc_attr($field_name) . ($multiple ? '[]' : '') . '"';
        if ($multiple) {
            echo ' multiple="multiple"';
        }
        echo '>';
        
        foreach ($options as $option_value => $option_label) {
            echo '<option value="' . esc_attr($option_value) . '"';
            if ($multiple) {
                if (is_array($value) && in_array($option_value, $value)) {
                    echo ' selected="selected"';
                }
            } else {
                selected($value, $option_value);
            }
            echo '>' . esc_html($option_label) . '</option>';
        }
        
        echo '</select>';
        echo '</div>';
    }
    
    /**
     * Render checkbox field
     */
    private static function render_checkbox_field($field_id, $field_name, $value, $field) {
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-checkbox">';
        echo '<label class="kanews-checkbox-label">';
        echo '<input type="checkbox" class="kanews-field kanews-field-checkbox" id="' . esc_attr($field_id) . '" name="' . esc_attr($field_name) . '" value="1" ' . checked($value, '1', false) . '>';
        echo '<span class="kanews-checkbox-text">' . esc_html($field['checkbox_label'] ?? '') . '</span>';
        echo '</label>';
        if (!empty($field['description'])) {
            echo '<p class="description">' . esc_html($field['description']) . '</p>';
        }
        echo '</div>';
    }
    
    /**
     * Render radio field
     */
    private static function render_radio_field($field_id, $field_name, $value, $field) {
        $options = isset($field['options']) ? $field['options'] : array();
        
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-radio">';
        self::render_field_label($field);
        echo '<div class="kanews-radio-group">';
        foreach ($options as $option_value => $option_label) {
            $option_id = $field_id . '_' . sanitize_key($option_value);
            echo '<label class="kanews-radio-label">';
            echo '<input type="radio" class="kanews-field kanews-field-radio" id="' . esc_attr($option_id) . '" name="' . esc_attr($field_name) . '" value="' . esc_attr($option_value) . '" ' . checked($value, $option_value, false) . '>';
            echo '<span class="kanews-radio-text">' . esc_html($option_label) . '</span>';
            echo '</label>';
        }
        echo '</div>';
        echo '</div>';
    }
    
    /**
     * Render number field
     */
    private static function render_number_field($field_id, $field_name, $value, $field) {
        $class = isset($field['class']) ? $field['class'] : 'widefat';
        $min = isset($field['min']) ? $field['min'] : '';
        $max = isset($field['max']) ? $field['max'] : '';
        $step = isset($field['step']) ? $field['step'] : '';
        
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-number">';
        self::render_field_label($field);
        echo '<input class="' . esc_attr($class) . ' kanews-field kanews-field-number" id="' . esc_attr($field_id) . '" name="' . esc_attr($field_name) . '" type="number" value="' . esc_attr($value) . '"';
        
        if (!empty($min)) {
            echo ' min="' . esc_attr($min) . '"';
        }
        
        if (!empty($max)) {
            echo ' max="' . esc_attr($max) . '"';
        }
        
        if (!empty($step)) {
            echo ' step="' . esc_attr($step) . '"';
        }
        
        echo '>';
        echo '</div>';
    }
    
    /**
     * Render slider field
     */
    public static function render_slider_field($field) {
        $id = $field['id'];
        $name = $field['name'];
        $label = $field['label'];
        $value = isset($field['value']) ? $field['value'] : '';
        $min = isset($field['min']) ? $field['min'] : 0;
        $max = isset($field['max']) ? $field['max'] : 100;
        $step = isset($field['step']) ? $field['step'] : 1;
        $unit = isset($field['unit']) ? $field['unit'] : '';
        $default = isset($field['default']) ? $field['default'] : $min;
        $description = isset($field['description']) ? $field['description'] : '';
        
        // If value is empty, use default
        if (empty($value)) {
            $value = $default;
        }
        
        echo '<div class="kanews-field kanews-field-slider">';
        echo '<label class="kanews-field-label" for="' . esc_attr($id) . '">' . esc_html($label) . '</label>';
        echo '<div class="kanews-slider-container">';
        echo '<div class="kanews-slider-element kanews-slider-element" data-target="' . esc_attr($id) . '" data-min="' . esc_attr($min) . '" data-max="' . esc_attr($max) . '" data-step="' . esc_attr($step) . '" data-value="' . esc_attr($value) . '" data-unit="' . esc_attr($unit) . '" data-default="' . esc_attr($default) . '"></div>';
        echo '<div class="kanews-slider-value">' . esc_html($value . $unit) . '</div>';
        echo '</div>';
        echo '<input type="hidden" id="' . esc_attr($id) . '" name="' . esc_attr($name) . '" value="' . esc_attr($value) . '">';
        if (!empty($description)) {
            echo '<p class="description">' . esc_html($description) . '</p>';
        }
        echo '</div>';
    }
    
    /**
     * Render color field
     */
    private static function render_color_field($field_id, $field_name, $value, $field) {
        $class = isset($field['class']) ? $field['class'] : 'widefat color-picker';
        
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-color">';
        self::render_field_label($field);
        echo '<input class="' . esc_attr($class) . ' kanews-field kanews-field-color" id="' . esc_attr($field_id) . '" name="' . esc_attr($field_name) . '" type="text" value="' . esc_attr($value) . '">';
        echo '</div>';
    }
    
    /**
     * Render date field
     */
    private static function render_date_field($field_id, $field_name, $value, $field) {
        $class = isset($field['class']) ? $field['class'] : 'widefat date-picker';
        
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-date">';
        self::render_field_label($field);
        echo '<input class="' . esc_attr($class) . ' kanews-field kanews-field-date" id="' . esc_attr($field_id) . '" name="' . esc_attr($field_name) . '" type="date" value="' . esc_attr($value) . '">';
        echo '</div>';
    }
    
    /**
     * Render time field
     */
    private static function render_time_field($field_id, $field_name, $value, $field) {
        $class = isset($field['class']) ? $field['class'] : 'widefat time-picker';
        
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-time">';
        self::render_field_label($field);
        echo '<input class="' . esc_attr($class) . ' kanews-field kanews-field-time" id="' . esc_attr($field_id) . '" name="' . esc_attr($field_name) . '" type="time" value="' . esc_attr($value) . '">';
        echo '</div>';
    }
    
    /**
     * Render URL field
     */
    private static function render_url_field($field_id, $field_name, $value, $field) {
        $class = isset($field['class']) ? sanitize_html_class($field['class']) : 'widefat';
        $placeholder = isset($field['placeholder']) ? self::sanitize_value($field['placeholder']) : '';
        
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-url">';
        self::render_field_label($field);
        printf(
            '<input class="%s kanews-field kanews-field-url" id="%s" name="%s" type="text" value="%s"%s>',
            esc_attr($class),
            esc_attr($field_id),
            esc_attr($field_name),
            esc_attr(self::sanitize_value($value, 'url')),
            !empty($placeholder) ? ' placeholder="' . esc_attr($placeholder) . '"' : ''
        );
        
        // URL validation script - nonce ekleyerek güvenliği artırıyoruz
        $nonce = wp_create_nonce('kanews_url_validate_' . $field_id);
        ?>
        <script>
        (function($) {
            'use strict';
            $(document).ready(function() {
                $('#<?php echo esc_js($field_id); ?>').on('change', function() {
                    var url = $(this).val();
                    if (url && !url.match(/^https?:\/\//)) {
                        url = url.replace(/[<>'"]/g, ''); // XSS koruması
                        $(this).val("https://" + url);
                    }
                });
            });
        })(jQuery);
        </script>
        <?php
        echo '</div>';
    }
    
    /**
     * Render email field
     */
    private static function render_email_field($field_id, $field_name, $value, $field) {
        $class = isset($field['class']) ? $field['class'] : 'widefat';
        $placeholder = isset($field['placeholder']) ? $field['placeholder'] : '';
        
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-email">';
        self::render_field_label($field);
        echo '<input class="' . esc_attr($class) . ' kanews-field kanews-field-email" id="' . esc_attr($field_id) . '" name="' . esc_attr($field_name) . '" type="email" value="' . esc_attr($value) . '"';
        
        if (!empty($placeholder)) {
            echo ' placeholder="' . esc_attr($placeholder) . '"';
        }
        
        echo '>';
        echo '</div>';
    }
    
    /**
     * Render password field
     */
    private static function render_password_field($field_id, $field_name, $value, $field) {
        $class = isset($field['class']) ? $field['class'] : 'widefat';
        
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-password">';
        self::render_field_label($field);
        echo '<input class="' . esc_attr($class) . ' kanews-field kanews-field-password" id="' . esc_attr($field_id) . '" name="' . esc_attr($field_name) . '" type="password" value="' . esc_attr($value) . '">';
        echo '</div>';
    }
    
    /**
     * Render file field
     */
    private static function render_file_field($field_id, $field_name, $value, $field) {
        $class = isset($field['class']) ? $field['class'] : 'widefat';
        $accept = isset($field['accept']) ? $field['accept'] : '';
        
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-file">';
        self::render_field_label($field);
        echo '<input class="' . esc_attr($class) . ' kanews-field kanews-field-file" id="' . esc_attr($field_id) . '" name="' . esc_attr($field_name) . '" type="file"';
        
        if (!empty($accept)) {
            echo ' accept="' . esc_attr($accept) . '"';
        }
        
        echo '>';
        
        if (!empty($value)) {
            echo '<span class="description">' . esc_html__('Current file:', 'kanews') . ' ' . esc_html($value) . '</span>';
        }
        echo '</div>';
    }
    
    /**
     * Render hidden field
     */
    private static function render_hidden_field($field_id, $field_name, $value, $field) {
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-hidden">';
        echo '<input type="hidden" class="kanews-field kanews-field-hidden" id="' . esc_attr($field_id) . '" name="' . esc_attr($field_name) . '" value="' . esc_attr($value) . '">';
        echo '</div>';
    }
    
    /**
     * Render HTML field
     */
    private static function render_html_field($field) {
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-html">';
        if (isset($field['html'])) {
            echo wp_kses_post($field['html']);
        }
        echo '</div>';
    }
    
    /**
     * Render separator field
     */
    private static function render_separator_field($field) {
        $class = isset($field['class']) ? $field['class'] : 'kanews-separator';
        $text = isset($field['text']) ? $field['text'] : '';
        
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-separator">';
        echo '<div class="' . esc_attr($class) . '">';
        
        if (!empty($text)) {
            echo '<span>' . esc_html($text) . '</span>';
        }
        
        echo '</div>';
        echo '</div>';
    }
    
    /**
     * Render accordion field
     */
    public static function render_accordion_field($field) {
        $title = isset($field['title']) ? $field['title'] : '';
        $content = isset($field['content']) ? $field['content'] : array();
        $active = isset($field['active']) ? $field['active'] : false;
        
        // Generate a unique ID for this accordion
        $accordion_id = 'kanews-accordion-' . uniqid();
        
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-accordion">';
        ?>
        <div id="<?php echo esc_attr($accordion_id); ?>" class="kanews-accordion<?php echo $active ? ' is-active' : ''; ?>">
            <div class="kanews-accordion-header">
                <span class="kanews-accordion-title"><?php echo esc_html($title); ?></span>
                <span class="kanews-accordion-icon"></span>
            </div>
            <div class="kanews-accordion-content">
                <?php
                foreach ($content as $field) {
                    $field_id = isset($field['id']) ? $field['id'] : '';
                    $field_name = isset($field['name']) ? $field['name'] : '';
                    $field_value = isset($field['value']) ? $field['value'] : '';
                    self::render_field($field, $field_id, $field_name, $field_value);
                }
                ?>
            </div>
        </div>
        <?php
        echo '</div>';
    }
    
    /**
     * Render Select2 categories field
     */
    private static function render_select2_categories_field($field_id, $field_name, $value, $field) {
        $class = isset($field['class']) ? $field['class'] : 'widefat select2-categories';
        $multiple = isset($field['multiple']) && $field['multiple'] ? 'multiple' : '';
        $placeholder = isset($field['placeholder']) ? $field['placeholder'] : __('Kategorileri seçin...', 'kanews');
        
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-select2-categories">';
        self::render_field_label( $field);

        // No need for hidden input with empty value - it causes conflicts
        // We'll handle empty values differently

        // Get selected categories
        $selected_categories = array();
        if (!empty($value)) {
            $value_array = is_array($value) ? $value : explode(',', $value);
            foreach ($value_array as $cat_id) {
                $cat = get_category($cat_id);
                if ($cat) {
                    $selected_categories[$cat_id] = $cat->name;
                }
            }
        }
        
        if (!empty($multiple)) {
            // For multiple selection, use array notation in name
            echo '<select class="' . esc_attr($class) . ' kanews-field kanews-field-select2-categories" id="' . esc_attr($field_id) . '" name="' . esc_attr($field_name) . '[]" ' . $multiple;
        } else {
            // For single selection, use standard name without array notation
            echo '<select class="' . esc_attr($class) . ' kanews-field kanews-field-select2-categories" id="' . esc_attr($field_id) . '" name="' . esc_attr($field_name) . '"';
        }
        
        echo ' data-placeholder="' . esc_attr($placeholder) . '">';
        
        // Add empty option for single selects to allow clearing the selection
        if (empty($multiple)) {
            echo '<option value=""></option>';
        }
        
        // Add selected categories
        foreach ($selected_categories as $cat_id => $cat_name) {
            echo '<option value="' . esc_attr($cat_id) . '" selected>' . esc_html($cat_name) . '</option>';
        }
        
        echo '</select>';
        
        // No need for this hidden input - it causes conflicts
        // if (empty($multiple) && !empty($value)) {
        //     echo '<input type="hidden" name="' . esc_attr($field_name) . '" value="' . esc_attr($value) . '">';
        // }
        echo '</div>';
    }
    
    /**
     * Render Select2 tags field
     */
    private static function render_select2_tags_field($field_id, $field_name, $value, $field) {
        $class = isset($field['class']) ? $field['class'] : 'widefat select2-tags';
        $multiple = isset($field['multiple']) && $field['multiple'] ? 'multiple' : '';
        $placeholder = isset($field['placeholder']) ? $field['placeholder'] : __('Etiketleri seçin...', 'kanews');
        
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-select2-tags">';
        self::render_field_label( $field);

        // No need for hidden input with empty value - it causes conflicts

        // Get selected tags
        $selected_tags = array();
        if (!empty($value)) {
            $value_array = is_array($value) ? $value : explode(',', $value);
            foreach ($value_array as $tag_id) {
                $tag = get_tag($tag_id);
                if ($tag) {
                    $selected_tags[$tag_id] = $tag->name;
                }
            }
        }
        
        if (!empty($multiple)) {
            // For multiple selection, use array notation in name
            echo '<select class="' . esc_attr($class) . ' kanews-field kanews-field-select2-tags" id="' . esc_attr($field_id) . '" name="' . esc_attr($field_name) . '[]" ' . $multiple;
        } else {
            // For single selection, use standard name without array notation
            echo '<select class="' . esc_attr($class) . ' kanews-field kanews-field-select2-tags" id="' . esc_attr($field_id) . '" name="' . esc_attr($field_name) . '"';
        }
        
        echo ' data-placeholder="' . esc_attr($placeholder) . '">';
        
        // Add empty option for single selects to allow clearing the selection
        if (empty($multiple)) {
            echo '<option value=""></option>';
        }
        
        // Add selected tags
        foreach ($selected_tags as $tag_id => $tag_name) {
            echo '<option value="' . esc_attr($tag_id) . '" selected>' . esc_html($tag_name) . '</option>';
        }
        
        echo '</select>';
        
        // No need for the hidden input - it causes conflicts
        echo '</div>';
    }
    
    /**
     * Render Select2 taxonomy field
     */
    private static function render_select2_taxonomy_field($field_id, $field_name, $value, $field) {
        $class = isset($field['class']) ? $field['class'] : 'widefat select2-taxonomy';
        $multiple = isset($field['multiple']) && $field['multiple'] ? 'multiple' : '';
        $placeholder = isset($field['placeholder']) ? $field['placeholder'] : __('Terimleri seçin...', 'kanews');
        $taxonomy = isset($field['taxonomy']) ? $field['taxonomy'] : 'category';
        
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-select2-taxonomy">';
        self::render_field_label( $field);

        // Get selected terms
        $selected_terms = array();
        if (!empty($value)) {
            $value_array = is_array($value) ? $value : explode(',', $value);
            foreach ($value_array as $term_id) {
                $term = get_term($term_id, $taxonomy);
                if ($term && !is_wp_error($term)) {
                    $selected_terms[$term_id] = $term->name;
                }
            }
        }
        
        if (!empty($multiple)) {
            // For multiple selection, use array notation in name
            echo '<select class="' . esc_attr($class) . ' kanews-field kanews-field-select2-taxonomy" id="' . esc_attr($field_id) . '" name="' . esc_attr($field_name) . '[]" ' . $multiple;
        } else {
            // For single selection, use standard name without array notation
            echo '<select class="' . esc_attr($class) . ' kanews-field kanews-field-select2-taxonomy" id="' . esc_attr($field_id) . '" name="' . esc_attr($field_name) . '"';
        }
        
        echo ' data-placeholder="' . esc_attr($placeholder) . '" data-taxonomy="' . esc_attr($taxonomy) . '">';
        
        // Add empty option for single selects to allow clearing the selection
        if (empty($multiple)) {
            echo '<option value=""></option>';
        }
        
        // Add selected terms
        foreach ($selected_terms as $term_id => $term_name) {
            echo '<option value="' . esc_attr($term_id) . '" selected>' . esc_html($term_name) . '</option>';
        }
        
        echo '</select>';
        
        // No need for the hidden input - it causes conflicts
        echo '</div>';
    }
    
    /**
     * Render Select2 posts field
     */
    private static function render_select2_posts_field($field_id, $field_name, $value, $field) {
        $class = isset($field['class']) ? $field['class'] : 'widefat select2-posts';
        $multiple = isset($field['multiple']) && $field['multiple'] ? 'multiple' : '';
        $placeholder = isset($field['placeholder']) ? $field['placeholder'] : __('Yazıları seçin...', 'kanews');
        $post_type = isset($field['post_type']) ? $field['post_type'] : 'post';
        
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-select2-posts">';
        self::render_field_label( $field);

        // Get selected posts
        $selected_posts = array();
        if (!empty($value)) {
            $value_array = is_array($value) ? $value : explode(',', $value);
            foreach ($value_array as $post_id) {
                $post = get_post($post_id);
                if ($post) {
                    $selected_posts[$post_id] = $post->post_title;
                }
            }
        }
        
        if (!empty($multiple)) {
            // For multiple selection, use array notation in name
            echo '<select class="' . esc_attr($class) . ' kanews-field kanews-field-select2-posts" id="' . esc_attr($field_id) . '" name="' . esc_attr($field_name) . '[]" ' . $multiple;
        } else {
            // For single selection, use standard name without array notation
            echo '<select class="' . esc_attr($class) . ' kanews-field kanews-field-select2-posts" id="' . esc_attr($field_id) . '" name="' . esc_attr($field_name) . '"';
        }
        
        echo ' data-placeholder="' . esc_attr($placeholder) . '" data-post-type="' . esc_attr($post_type) . '">';
        
        // Add empty option for single selects to allow clearing the selection
        if (empty($multiple)) {
            echo '<option value=""></option>';
        }
        
        // Add selected posts
        foreach ($selected_posts as $post_id => $post_title) {
            echo '<option value="' . esc_attr($post_id) . '" selected>' . esc_html($post_title) . '</option>';
        }
        
        echo '</select>';
        
        // No need for the hidden input - it causes conflicts
        echo '</div>';
    }
    
    /**
     * Render toggle field
     */
    private static function render_toggle_field($field_id, $field_name, $value, $field) {
        $label = isset($field['label']) ? $field['label'] : '';
        $description = isset($field['description']) ? $field['description'] : '';
        
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-toggle">';
        ?>
        <div class="kanews-toggle-field">
            <div class="kanews-toggle-header">
                <span class="kanews-toggle-title">
                    <?php echo esc_html($label); ?>
                </span>
                <?php if (!empty($description)): ?>
                    <?php self::render_tooltip($description); ?>
                <?php endif; ?>
            </div>
            <div class="kanews-toggle-switch-wrapper">
                <label class="kanews-toggle-switch">
                    <input type="checkbox" 
                           class="kanews-field kanews-field-toggle"
                           id="<?php echo esc_attr($field_id); ?>" 
                           name="<?php echo esc_attr($field_name); ?>" 
                           value="on" 
                           <?php echo ($value === 'on') ? 'checked' : ''; ?>>
                    <span class="kanews-toggle-slider"></span>
                </label>
            </div>
        </div>
        <?php
        echo '</div>';
    }
    
    /**
     * Render media field
     */
    private static function render_media_field($field_id, $field_name, $value, $field) {
        $preview = isset($field['preview']) ? $field['preview'] : false;
        $description = isset($field['description']) ? $field['description'] : '';
        
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-media">';
        self::render_field_label($field);
        
        echo '<div class="kanews-media-field">';
        echo '<input type="text" class="widefat" id="' . esc_attr($field_id) . '" name="' . esc_attr($field_name) . '" value="' . esc_attr($value) . '">';
        echo '<button class="button kanews-field-media-button">' . esc_html__('Görsel Seç', 'kanews') . '</button>';
        
        if ($preview) {
            echo '<div class="kanews-field-media-preview">';
            if (!empty($value)) {
                echo '<img src="' . esc_url($value) . '" style="max-width:100%;height:auto;">';
            }
            echo '</div>';
        }
        
        if (!empty($description)) {
            echo '<p class="description">' . esc_html($description) . '</p>';
        }
        
        echo '</div>';
        echo '</div>';
    }
    
    /**
     * Get categories as options array
     */
    private static function get_categories_options() {
        $categories = get_categories(array('hide_empty' => false));
        $options = array('' => __('Tüm Kategoriler', 'kanews'));
        
        foreach($categories as $category) {
            $options[$category->term_id] = $category->name;
        }
        
        return $options;
    }
    
    /**
     * Enqueue admin scripts
     */
    public static function enqueue_scripts($hook_suffix) {
        if('widgets.php' != $hook_suffix) {
            return;
        }
        
        // Enqueue Select2
        wp_enqueue_style('select2', 'https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css');
        wp_enqueue_script('select2', 'https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js', array('jquery'), null, true);
        
        // Enqueue jQuery UI
        wp_enqueue_script('jquery-ui-slider');
        wp_enqueue_style('jquery-ui', 'https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css');
        
        // Enqueue other scripts
        wp_enqueue_style('wp-color-picker');
        wp_enqueue_script('wp-color-picker');
        wp_enqueue_script('jquery');
        
        // Enqueue custom CSS and JS
        wp_enqueue_style('kanews-widget-admin', get_template_directory_uri() . '/assets/css/widget-admin.css', array(), self::VERSION);
        wp_enqueue_script('kanews-widget-admin', get_template_directory_uri() . '/assets/js/admin/widget-admin.js', array('jquery', 'jquery-ui-slider', 'select2'), self::VERSION, true);
        
        // AJAX için gerekli değişkenleri ekle
        wp_localize_script('kanews-widget-admin', 'kanews_ajax', array(
            'nonce' => wp_create_nonce('kanews_ajax_nonce'),
            'ajaxurl' => admin_url('admin-ajax.php')
        ));
        
        // Add custom styles
        wp_add_inline_style('select2', '
            .select2-container--default .select2-selection--multiple {
                border-color: #ddd;
            }
            .select2-container--default.select2-container--focus .select2-selection--multiple {
                border-color: #007cba;
            }
            .select2-container--default .select2-selection--multiple .select2-selection__choice {
                background-color: #007cba;
                border-color: #007cba;
                color: #fff;
            }
            .select2-container--default .select2-selection--multiple .select2-selection__choice__remove {
                color: #fff;
            }
            .kanews-accordion {
                border: 1px solid #ddd;
                margin-bottom: 10px;
            }
            .kanews-accordion-header {
                background-color: #f5f5f5;
                padding: 10px;
                cursor: pointer;
                font-weight: bold;
            }
            .kanews-accordion-content {
                padding: 10px;
                display: none;
            }
            .kanews-accordion.active .kanews-accordion-content {
                display: block;
            }
            .kanews-slider-container {
                margin-top: 10px;
            }
            .kanews-slider-value {
                margin-top: 5px;
                font-weight: bold;
            }
        ');
        
        // Initialize color picker
        wp_add_inline_script('wp-color-picker', '
            jQuery(document).ready(function($) {
                $(".color-picker").wpColorPicker();
                $(".date-picker").datepicker({
                    dateFormat: "yy-mm-dd"
                });
                $(".time-picker").timepicker();
            });
        ');
    }
    
    /**
     * Register AJAX handlers
     */
    public static function register_ajax_handlers() {
        add_action('wp_ajax_kanews_search_categories', array(__CLASS__, 'ajax_search_categories'));
        add_action('wp_ajax_kanews_search_tags', array(__CLASS__, 'ajax_search_tags'));
        add_action('wp_ajax_kanews_search_taxonomy', array(__CLASS__, 'ajax_search_taxonomy'));
        add_action('wp_ajax_kanews_search_posts', array(__CLASS__, 'ajax_search_posts'));
        add_action('wp_ajax_kanews_get_icons', array(__CLASS__, 'kanews_get_icons_ajax'));
    }
    
    /**
     * AJAX handler for searching categories
     */
    public static function ajax_search_categories() {
        check_ajax_referer('kanews_ajax_nonce', 'nonce');
        
        $search = isset($_GET['q']) ? sanitize_text_field($_GET['q']) : '';
        $results = array();
        
        if (!empty($search)) {
            $categories = get_categories(array(
                'hide_empty' => false,
                'search' => $search
            ));
            
            foreach ($categories as $category) {
                $results[] = array(
                    'id' => $category->term_id,
                    'text' => $category->name
                );
            }
        }
        
        wp_send_json($results);
    }
    
    /**
     * AJAX handler for searching tags
     */
    public static function ajax_search_tags() {
        check_ajax_referer('kanews_ajax_nonce', 'nonce');
        
        $search = isset($_GET['q']) ? sanitize_text_field($_GET['q']) : '';
        $results = array();
        
        if (!empty($search)) {
            $tags = get_tags(array(
                'hide_empty' => false,
                'search' => $search
            ));
            
            foreach ($tags as $tag) {
                $results[] = array(
                    'id' => $tag->term_id,
                    'text' => $tag->name
                );
            }
        }
        
        wp_send_json($results);
    }
    
    /**
     * AJAX handler for searching taxonomy terms
     */
    public static function ajax_search_taxonomy() {
        check_ajax_referer('kanews_ajax_nonce', 'nonce');
        
        $search = isset($_GET['q']) ? sanitize_text_field($_GET['q']) : '';
        $taxonomy = isset($_GET['taxonomy']) ? sanitize_text_field($_GET['taxonomy']) : 'category';
        $results = array();
        
        if (!empty($search) && !empty($taxonomy)) {
            $terms = get_terms(array(
                'taxonomy' => $taxonomy,
                'hide_empty' => false,
                'search' => $search
            ));
            
            if (!is_wp_error($terms)) {
                foreach ($terms as $term) {
                    $results[] = array(
                        'id' => $term->term_id,
                        'text' => $term->name
                    );
                }
            }
        }
        
        wp_send_json($results);
    }
    
    /**
     * AJAX handler for searching posts
     */
    public static function ajax_search_posts() {
        check_ajax_referer('kanews_ajax_nonce', 'nonce');
        
        $search = isset($_GET['q']) ? sanitize_text_field($_GET['q']) : '';
        $post_type = isset($_GET['post_type']) ? sanitize_text_field($_GET['post_type']) : 'post';
        $results = array();
        
        if (!empty($search) && !empty($post_type)) {
            $posts = get_posts(array(
                'post_type' => $post_type,
                'posts_per_page' => 10,
                's' => $search
            ));
            
            foreach ($posts as $post) {
                $results[] = array(
                    'id' => $post->ID,
                    'text' => $post->post_title
                );
            }
        }
        
        wp_send_json($results);
    }

    /**
     * AJAX handler for getting icons
     */
    public static function kanews_get_icons_ajax() {
        check_ajax_referer('kanews_ajax_nonce', 'nonce');
        
        // kanews_icons fonksiyonunu çağır
        $icons = array();
        $icons = apply_filters('csf_field_icon_add_icons', $icons);
        
        if (!empty($icons) && isset($icons[0]['icons'])) {
            wp_send_json_success($icons[0]['icons']);
        } else {
            wp_send_json_error('İkonlar bulunamadı');
        }
        die();
    }

    /**
     * Render global sorting settings for manset widgets
     */
    public static function render_manset_sorting_settings($widget, $instance) {
        return self::render_accordion_field(array(
            'title' => __('Sıralama Ayarları', 'kanews'),
            'content' => array(
                array(
                    'type' => self::TYPE_TOGGLE,
                    'id' => $widget->get_field_id('sticky_posts'),
                    'name' => $widget->get_field_name('sticky_posts'),
                    'label' => __('Sabitlenen Yazıları Göster', 'kanews'),
                    'value' => $instance['sticky_posts']
                ),
                array(
                    'type' => self::TYPE_SELECT,
                    'id' => $widget->get_field_id('sortby'),
                    'name' => $widget->get_field_name('sortby'),
                    'label' => __('Göre Sırala', 'kanews'),
                    'value' => $instance['sortby'],
                    'options' => array(
                        'recent' => __('Yayınlanma Tarihine Göre', 'kanews'),
                        'post-modified' => __('Düzenlenme Tarihine Göre', 'kanews'),
                        'post-viewed' => __('En Çok Okunan Yazı - Tüm Zamanlar', 'kanews'),
                        'commented' => __('En Çok Yorum Yapılan', 'kanews'),
                        'random' => __('Rastgele', 'kanews')
                    )
                ),
                array(
                    'type' => self::TYPE_SELECT,
                    'id' => $widget->get_field_id('date_range'),
                    'name' => $widget->get_field_name('date_range'),
                    'label' => __('Zaman Aralığı', 'kanews'),
                    'value' => $instance['date_range'],
                    'options' => array(
                        '0' => __('Zaman Aralığı Seçin', 'kanews'),
                        'day' => __('Son 1 Gün', 'kanews'),
                        'week' => __('Son 1 Hafta', 'kanews'),
                        'month' => __('Son 1 Ay', 'kanews'),
                        'year' => __('Son 1 Yıl', 'kanews')
                    )
                ),
                array(
                    'type' => self::TYPE_SELECT2_TAXONOMY,
                    'id' => $widget->get_field_id('categories2'),
                    'name' => $widget->get_field_name('categories2'),
                    'label' => __('Manşet Alanı', 'kanews'),
                    'value' => $instance['categories2'],
                    'taxonomy' => 'manset',
                    'multiple' => true,
                    'placeholder' => __('Tüm Kategoriler', 'kanews')
                ),
                array(
                    'type' => self::TYPE_SELECT2_CATEGORIES,
                    'id' => $widget->get_field_id('categories'),
                    'name' => $widget->get_field_name('categories'),
                    'label' => __('Kategori', 'kanews'),
                    'value' => $instance['categories'],
                    'multiple' => true,
                    'placeholder' => __('Tüm Kategoriler', 'kanews')
                ),
                array(
                    'type' => self::TYPE_SELECT2_POSTS,
                    'id' => $widget->get_field_id('pids'),
                    'name' => $widget->get_field_name('pids'),
                    'label' => __('Gösterilecek Yazılar', 'kanews'),
                    'value' => $instance['pids'],
                    'post_type' => 'post',
                    'multiple' => true,
                    'placeholder' => __('Yazıları seçin', 'kanews')
                ),
                array(
                    'type' => self::TYPE_SELECT2_POSTS,
                    'id' => $widget->get_field_id('exclude_pids'),
                    'name' => $widget->get_field_name('exclude_pids'),
                    'label' => __('Çıkarılacak Yazılar', 'kanews'),
                    'value' => $instance['exclude_pids'],
                    'post_type' => 'post',
                    'multiple' => true,
                    'placeholder' => __('Yazıları seçin', 'kanews')
                ),
                array(
                    'type' => self::TYPE_SELECT2_TAGS,
                    'id' => $widget->get_field_id('tags'),
                    'name' => $widget->get_field_name('tags'),
                    'label' => __('Etiketler', 'kanews'),
                    'value' => $instance['tags'],
                    'multiple' => true,
                    'placeholder' => __('Etiketleri seçin', 'kanews')
                ),
                array(
                    'type' => self::TYPE_SLIDER,
                    'id' => $widget->get_field_id('offset'),
                    'name' => $widget->get_field_name('offset'),
                    'label' => __('Offset', 'kanews'),
                    'value' => $instance['offset'],
                    'min' => 0,
                    'max' => 50,
                    'step' => 1,
                    'description' => __('Örneğin 1 girerseniz birinci yazıyı hariç tutar, ikinci yazıdan başlar.', 'kanews')
                ),
                array(
                    'type' => self::TYPE_SLIDER,
                    'id' => $widget->get_field_id('posts'),
                    'name' => $widget->get_field_name('posts'),
                    'label' => __('Yazı Sayısı', 'kanews'),
                    'value' => $instance['posts'],
                    'min' => 1,
                    'max' => 20,
                    'step' => 1
                ),
                array(
                    'type' => self::TYPE_TOGGLE,
                    'id' => $widget->get_field_id('postnotin'),
                    'name' => $widget->get_field_name('postnotin'),
                    'label' => __('Bu yazıları başka bileşende gösterme', 'kanews'),
                    'value' => $instance['postnotin']
                ),
                array(
                    'type' => self::TYPE_TOGGLE,
                    'id' => $widget->get_field_id('include_columist'),
                    'name' => $widget->get_field_name('include_columist'),
                    'label' => __('Köşe yazılarını dahil et', 'kanews'),
                    'value' => $instance['include_columist']
                )
            )
        ));
    }

    public static function render_posts_sorting_settings($widget, $instance) {
        return self::render_accordion_field(array(
            'title' => __('Sıralama Ayarları', 'kanews'),
            'content' => array(
                array(
                    'type' => self::TYPE_SELECT,
                    'id' => $widget->get_field_id('sortby'),
                    'name' => $widget->get_field_name('sortby'),
                    'label' => __('Göre Sırala', 'kanews'),
                    'value' => $instance['sortby'],
                    'options' => array(
                        'recent' => __('Yayınlanma Tarihine Göre', 'kanews'),
                        'post-modified' => __('Düzenlenme Tarihine Göre', 'kanews'),
                        'post-viewed' => __('En Çok Okunan Yazı - Tüm Zamanlar', 'kanews'),
                        'commented' => __('En Çok Yorum Yapılan', 'kanews'),
                        'random' => __('Rastgele', 'kanews')
                    )
                ),
                array(
                    'type' => self::TYPE_SELECT,
                    'id' => $widget->get_field_id('date_range'),
                    'name' => $widget->get_field_name('date_range'),
                    'label' => __('Zaman Aralığı', 'kanews'),
                    'value' => $instance['date_range'],
                    'options' => array(
                        '0' => __('Zaman Aralığı Seçin', 'kanews'),
                        'day' => __('Son 1 Gün', 'kanews'),
                        'week' => __('Son 1 Hafta', 'kanews'),
                        'month' => __('Son 1 Ay', 'kanews'),
                        'year' => __('Son 1 Yıl', 'kanews')
                    )
                ),
                array(
                    'type' => self::TYPE_SELECT2_CATEGORIES,
                    'id' => $widget->get_field_id('categories'),
                    'name' => $widget->get_field_name('categories'),
                    'label' => __('Kategori', 'kanews'),
                    'value' => $instance['categories'],
                    'multiple' => true,
                    'placeholder' => __('Tüm Kategoriler', 'kanews')
                ),
                array(
                    'type' => self::TYPE_SELECT2_TAGS,
                    'id' => $widget->get_field_id('tags'),
                    'name' => $widget->get_field_name('tags'),
                    'label' => __('Etiketler', 'kanews'),
                    'value' => $instance['tags'],
                    'multiple' => true,
                    'placeholder' => __('Etiketleri seçin', 'kanews')
                ),
                array(
                    'type' => self::TYPE_SELECT,
                    'id' => $widget->get_field_id('format'),
                    'name' => $widget->get_field_name('format'),
                    'label' => __('Yazı Formatı', 'kanews'),
                    'value' => $instance['format'],
                    'options' => array(
                        '0' => __('Yazı Formatı Seçin', 'kanews'),
                        'video' => __('Video', 'kanews'),
                        'gallery' => __('Fotoğraf', 'kanews')
                    )
                ),
                array(
                    'type' => self::TYPE_SLIDER,
                    'id' => $widget->get_field_id('offset'),
                    'name' => $widget->get_field_name('offset'),
                    'label' => __('Offset', 'kanews'),
                    'value' => $instance['offset'],
                    'min' => 0,
                    'max' => 50,
                    'step' => 1,
                    'description' => __('Örneğin 1 girerseniz birinci yazıyı hariç tutar, ikinci yazıdan başlar.', 'kanews')
                ),
                array(
                    'type' => self::TYPE_SLIDER,
                    'id' => $widget->get_field_id('posts'),
                    'name' => $widget->get_field_name('posts'),
                    'label' => __('Yazı Sayısı', 'kanews'),
                    'value' => $instance['posts'],
                    'min' => 1,
                    'max' => 20,
                    'step' => 1
                ),
                array(
                    'type' => self::TYPE_TOGGLE,
                    'id' => $widget->get_field_id('postnotin'),
                    'name' => $widget->get_field_name('postnotin'),
                    'label' => __('Bu yazıları başka bileşende gösterme', 'kanews'),
                    'value' => $instance['postnotin']
                ),
                array(
                    'type' => self::TYPE_TOGGLE,
                    'id' => $widget->get_field_id('include_columist'),
                    'name' => $widget->get_field_name('include_columist'),
                    'label' => __('Köşe yazılarını dahil et', 'kanews'),
                    'value' => $instance['include_columist']
                )
            )
        ));
    }

    public static function get_pages_options($include_all = true, $args = []) {
        $default_args = [
            'hide_empty' => 0,
            'depth' => 1,
            'type' => 'post'
        ];
        
        $args = wp_parse_args($args, $default_args);
        $options = [];
        
        if ($include_all) {
            $options['all'] = __('Sayfa Seçin', 'kanews');
        }
        
        $pages = get_pages($args);
        foreach ($pages as $page) {
            $options[$page->ID] = $page->post_title;
        }
        
        return $options;
    }

    /**
     * Render select2 field
     */
    private static function render_select2_field($field_id, $field_name, $value, $field) {
        $options = isset($field['options']) ? $field['options'] : array();
        $multiple = isset($field['multiple']) ? $field['multiple'] : false;
        $placeholder = isset($field['placeholder']) ? $field['placeholder'] : __('Seçim yapın...', 'kanews');
        
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-select2">';
        self::render_field_label($field);
        echo '<select class="kanews-select2 kanews-field kanews-field-select2"';
        echo ' id="' . esc_attr($field_id) . '"';
        echo ' name="' . esc_attr($field_name) . ($multiple ? '[]' : '') . '"';
        echo ' data-placeholder="' . esc_attr($placeholder) . '"';
        
        if ($multiple) {
            echo ' multiple="multiple"';
        }
        
        echo '>';
        
        // Boş seçenek ekle (çoklu seçim değilse)
        if (!$multiple && !isset($field['no_empty_option'])) {
            echo '<option value="">' . esc_html($placeholder) . '</option>';
        }
        
        // Seçenekleri ekle
        foreach ($options as $option_value => $option_label) {
            echo '<option value="' . esc_attr($option_value) . '"';
            if ($multiple) {
                if (is_array($value) && in_array($option_value, $value)) {
                    echo ' selected="selected"';
                }
            } else {
                selected($value, $option_value);
            }
            echo '>' . esc_html($option_label) . '</option>';
        }
        
        echo '</select>';
        
        // Select2 için JavaScript
        ?>
        <script>
        jQuery(document).ready(function($) {
            $('#<?php echo esc_js($field_id); ?>').select2({
                width: '100%',
                placeholder: '<?php echo esc_js($placeholder); ?>',
                allowClear: true
            });
        });
        </script>
        <?php
        
        echo '</div>';
    }

    /**
     * Render icon picker field
     */
    private static function render_icon_picker_field($field_id, $field_name, $value, $field) {
        echo '<div class="kanews-field-wrapper kanews-field-wrapper-icon-picker">';
        self::render_field_label($field);
        ?>
        <div class="kanews-icon-picker">
            <div class="kanews-icon-picker-preview">
                <i class="<?php echo esc_attr($value); ?>"></i>
                <span class="kanews-icon-picker-name"><?php echo esc_html($value); ?></span>
            </div>
            <input type="hidden" 
                   id="<?php echo esc_attr($field_id); ?>" 
                   name="<?php echo esc_attr($field_name); ?>" 
                   value="<?php echo esc_attr($value); ?>" 
                   class="kanews-icon-picker-input">
            <button type="button" class="button kanews-icon-picker-button">
                <?php _e('İkon Seç', 'kanews'); ?>
            </button>
        </div>
        <?php
        echo '</div>';
    }
}

// Register AJAX handlers
Kanews_Form_Elements::register_ajax_handlers(); 