<?php
namespace Kanews;
use Kanews\Helper_Wp;
use kanews_widget_class_posts_11;
use WP_Query;
use Kanews\Kai\Support\Options;

class Helper {
  private static $instance;

	public static function getInstance() {
		if ( null === static::$instance ) {
			static::$instance = new static();
		}
		return static::$instance;
	}

  function __construct() {

    
    add_action( 'kanews_footer',         array( $this, 'wp_footer' ), 5 );
    add_action( 'wp_head',               array( $this, 'wp_head' ) );
    add_filter( 'body_class',            array( $this, 'body_classes' ) );

    add_action('init', function() { 
      

      if(kanews_get_option('firma-rehberi', false)) 
      $this->kanews_firma_post_type();

      $this->kanews_manset_post_type();
      $this->kanews_author_post_type();


      if(kanews_get_option('ilan-sistemi', false))
      $this->kanews_ilan_post_type();

    });


    $this->kanews_manset_post_type();

    if(kanews_get_option('ilan-sistemi', false)) {
      add_filter( 'post_type_link',      array( $this, 'custom_remove_ilan_slug'), 10, 3);
    }

    add_filter( 'post_type_link',      array( $this, 'kanews_author_post_type_link' ), 10, 4 );
    
    add_filter( 'the_excerpt_rss',       array( $this, 'featured_to_rss' ) );
    add_filter( 'excerpt_length',        array( $this, 'excerpt_length' ), 999 );


    add_action( 'wp_ajax_nopriv_widget_posts_11_ajax',   array( $this, 'widget_posts_11_ajax' ) );
    add_action( 'wp_ajax_widget_posts_11_ajax',          array( $this, 'widget_posts_11_ajax' ) );

    add_action( 'wp_ajax_nopriv_kanews_ajax_search',   array( $this, 'kanews_ajax_search' ) );
    add_action( 'wp_ajax_kanews_ajax_search',          array( $this, 'kanews_ajax_search' ) );
    add_action( 'language_attributes',          array( $this, 'kan_html_class' ) );

    // add_filter( 'intermediate_image_sizes_advanced',          array( $this, 'remove_default_image_sizes' ), 999 );

  }


  function kan_html_class( $output ) {

    $classes   = array();
    if( kanews_get_option('mode') ) {

      if(isset($_COOKIE["kanews_dark_mode"]) && $_COOKIE["kanews_dark_mode"] == 'on')
      $classes[] = 'dark-mode';
      else 
      $classes[] = 'light-mode';


      $output .= ' class="' . join( ' ', array_filter( $classes ) ) . '"';
    }

    return $output;
  }

  function body_classes($classes) {
    $classes[] = 'by-kanthemes';

    if( kanews_get_option('colorfull-line', false) )
    $classes[] = 'header-line';

    if(kanews_get_option('navbar-sub-category') != false) {
      if(is_category()) {
        $category= get_category( get_query_var( 'cat' ), false );
        if($category->parent != 0)
        $category = get_category($category->category_parent, false);
        $categories = get_categories(
          array( 'parent' => $category->term_id )
        );
        $category= get_category( get_query_var( 'cat' ), false );
        if($categories)
        $classes[] = 'kanews-subnavbar-is-active';
      }
    }

    if(is_category()) {
      $sidebar = kanews_get_option('category-right-sidebar') ? kanews_get_option('category-right-sidebar') : false;
      
      if($sidebar != true) 
        $classes[] = 'kanews-cat-no-sidebar';
    }

    if(is_single()) {
      $category = Helper_Wp::primary_category_id(get_the_ID());
      $classes[] = 'category-'.$category;
    }

    if (is_singular('columist') || is_singular('post')) {
      global $post;
      $meta = get_post_meta($post->ID, 'select_post_layout_block', true );

      if($meta != 'default' && $meta != '') {
        $classes[] = 'single-layout-'.$meta;
      } elseif($meta != 'off' && kanews_get_option('single-layout-block') != ''  ) {
        $classes[] = 'single-layout-'.kanews_get_option('single-layout-block');
      }
    }

    if(kanews_get_option('tab-bar') && kan_is_mobile()) {
      $classes[] = 'tab-bar-active';
    }

    if( kanews_get_option('back-to-top') )
    $classes[] = 'back-to-top-active';
      
    return $classes;
  }


  function wp_head() {
    // Sayfa bazlı yenileme kontrolü
    if(is_page()) {
      $page_refresh = get_post_meta(get_the_ID(), 'page_auto_refresh', true);
      $time = kanews_get_option('auto-refresh-time', 300);

      // Sayfa ayarı aktifse veya global ayar aktif ve sayfa ayarı varsayılan ise
      if($page_refresh == 'on' || (kanews_get_option('auto-refresh') && $page_refresh != 'off')) {
        echo '<meta http-equiv="refresh" content="'.$time.'" />';
      }
    } 
    // Sayfa değilse ve global ayar aktifse
    elseif(kanews_get_option('auto-refresh')) {
      $time = kanews_get_option('auto-refresh-time', 300);
      echo '<meta http-equiv="refresh" content="'.$time.'" />';
    }

    if (kanews_get_option('wp-head') != '') {
      $out = kanews_get_option('wp-head');
      echo $out;
    }
  }

  function wp_footer() {
    if (kanews_get_option('wp-footer') != '') {
      $out = kanews_get_option('wp-footer');
      echo $out;
    }
    if(kanews_get_option('back-to-top')) {
      echo '<div class="progress-wrap">
      <svg class="progress-circle svg-content" width="100%" height="100%" viewBox="-1 -1 102 102">
      <path d="M50,1 a49,49 0 0,1 0,98 a49,49 0 0,1 0,-98" />
      </svg>
      </div>';
    }

    if ( Options::get( 'kai-audio-enabled', false ) && function_exists( '\kanews_kai_get_latest_audio_summary' ) ) {
      $audio_summary = \kanews_kai_get_latest_audio_summary();

      if ( ! empty( $audio_summary['audio_url'] ) ) {
        $summary_title = ! empty( $audio_summary['title'] ) ? wp_html_excerpt( $audio_summary['title'], 70, '…' ) : esc_html__( 'Haber Bülteni', 'kanews' );
        $slot_label    = ! empty( $audio_summary['slot_label'] ) ? $audio_summary['slot_label'] : esc_html__( 'Haber Bülteni', 'kanews' );
        $permalink     = ! empty( $audio_summary['permalink'] ) ? $audio_summary['permalink'] : '';
        ?>
        <div class="kanews-floating-audio" data-state="idle">
          <button class="kanews-floating-audio__close" aria-label="<?php echo esc_attr__( 'Kapat', 'kanews' ); ?>" title="<?php echo esc_attr__( 'Kapat', 'kanews' ); ?>">
            <i class="icon-close"></i>
          </button>
          <div class="kanews-floating-audio__meta">
            <span class="kanews-floating-audio__slot"><?php echo esc_html( $slot_label ); ?></span>
            <span class="kanews-floating-audio__title"><?php echo esc_html( $summary_title ); ?></span>
          </div>
          <div
            class="audio-icon kanews-floating-audio__button"
            data-src="<?php echo esc_url( $audio_summary['audio_url'] ); ?>"
            data-radius="16"
            role="button"
            tabindex="0"
            aria-label="<?php echo esc_attr__( 'Haber bültenini dinle.', 'kanews' ); ?>"
          >
            <i class="icon-mic icon-2x"></i>
            <svg class="progress-circle" viewBox="0 0 36 36" width="36" height="36">
              <circle class="progress-circle-bg" cx="18" cy="18" r="16"></circle>
              <circle class="progress-circle-progress" cx="18" cy="18" r="16"></circle>
            </svg>
          </div>
        </div>
        <script>
          (function() {
            const cookieName = 'kanews_floating_audio_closed';
            
            const getCookie = function(name) {
              const value = '; ' + document.cookie;
              const parts = value.split('; ' + name + '=');
              if (parts.length === 2) {
                return parts.pop().split(';').shift();
              }
              return null;
            };
            
            const setCookie = function(name, value, days) {
              const date = new Date();
              date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
              const expires = 'expires=' + date.toUTCString();
              document.cookie = name + '=' + value + ';' + expires + ';path=/';
            };
            
            const today = new Date().toDateString();
            const closedDate = getCookie(cookieName);
            
            if (closedDate === today) {
              const floatingAudio = document.querySelector('.kanews-floating-audio');
              if (floatingAudio) {
                floatingAudio.style.display = 'none';
              }
              return;
            }
            
            const initFloatingKaiAudio = function() {
              const floatingAudio = document.querySelector('.kanews-floating-audio');
              if (!floatingAudio) {
                return;
              }
              
              const closeButton = floatingAudio.querySelector('.kanews-floating-audio__close');
              if (closeButton) {
                closeButton.addEventListener('click', function(e) {
                  e.preventDefault();
                  e.stopPropagation();
                  setCookie(cookieName, today, 1);
                  floatingAudio.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
                  floatingAudio.style.opacity = '0';
                  floatingAudio.style.transform = 'translateY(20px)';
                  setTimeout(function() {
                    floatingAudio.style.display = 'none';
                  }, 300);
                });
              }
              
              const icon = floatingAudio.querySelector('.audio-icon');
              if (!icon) {
                return;
              }

              const initWithPlayer = function() {
                if (typeof window.KanAudioPlayer === 'undefined' && typeof KanAudioPlayer === 'undefined') {
                  return false;
                }

                const PlayerClass = window.KanAudioPlayer || KanAudioPlayer;
                
                window.kanAudioPlayer = window.kanAudioPlayer || new PlayerClass({
                  playingIconURL: '<?php echo esc_js( KAN_TEMPLATE_URL . '/assets/img/static/sound.gif' ); ?>',
                  playLabel: '<?php echo esc_js( __( 'Haber bültenini dinle.', 'kanews' ) ); ?>',
                  pauseLabel: '<?php echo esc_js( __( 'Durdur', 'kanews' ) ); ?>'
                });

                window.kanAudioPlayer.addPlayer(icon);
                icon.setAttribute('initialized', 'true');
                return true;
              };

              if (initWithPlayer()) {
                return;
              }

              const audioSrc = icon.getAttribute('data-src');
              if (!audioSrc || audioSrc.trim() === '' || !audioSrc.match(/^https?:\/\//i)) {
                console.warn('Invalid audio source URL:', audioSrc);
                return;
              }

              const svg = icon.querySelector('.progress-circle');
              const bgCircle = svg ? svg.querySelector('.progress-circle-bg') : null;
              const progressCircle = svg ? svg.querySelector('.progress-circle-progress') : null;
              const radius = parseFloat(icon.getAttribute('data-radius') || '16');
              const circumference = 2 * Math.PI * radius;

              if (bgCircle) {
                bgCircle.setAttribute('r', radius.toString());
                bgCircle.style.stroke = '#fff';
                bgCircle.style.strokeWidth = '3';
                bgCircle.style.strokeOpacity = '0.2';
                bgCircle.style.fill = 'none';
                bgCircle.style.transform = 'rotate(-90deg)';
                bgCircle.style.transformOrigin = '50% 50%';
              }

              if (progressCircle) {
                progressCircle.setAttribute('r', radius.toString());
                progressCircle.style.strokeDasharray = `${circumference}`;
                progressCircle.style.strokeDashoffset = `${circumference}`;
                progressCircle.style.stroke = '#fff';
                progressCircle.style.strokeWidth = '3';
                progressCircle.style.strokeOpacity = '1';
                progressCircle.style.fill = 'none';
                progressCircle.style.transform = 'rotate(-90deg)';
                progressCircle.style.transformOrigin = '50% 50%';
                progressCircle.style.transition = 'stroke-dashoffset 0.1s linear';
              }

              const setState = function(state) {
                const container = icon.closest('.kanews-floating-audio');
                if (container) {
                  container.setAttribute('data-state', state);
                }
              };

              let audio = null;
              let isAudioReady = false;
              let isLoading = false;

              const createAudio = function() {
                if (audio) {
                  return audio;
                }
                
                audio = new Audio();
                audio.preload = 'none';
                audio.crossOrigin = 'anonymous';

                audio.addEventListener('error', function(e) {
                  const errorCode = audio.error ? audio.error.code : 'unknown';
                  const errorMessage = audio.error ? audio.error.message : 'Unknown error';
                  
                  console.error('Audio playback error:', {
                    code: errorCode,
                    message: errorMessage,
                    src: audioSrc
                  });
                  
                  setState('error');
                  icon.style.opacity = '0.5';
                  icon.style.cursor = 'not-allowed';
                  isAudioReady = false;
                  isLoading = false;
                });

                audio.addEventListener('loadedmetadata', function() {
                  isAudioReady = true;
                  isLoading = false;
                  icon.style.opacity = '1';
                  icon.style.cursor = 'pointer';
                });

                audio.addEventListener('canplay', function() {
                  isAudioReady = true;
                  isLoading = false;
                  icon.style.opacity = '1';
                  icon.style.cursor = 'pointer';
                });

                audio.addEventListener('loadstart', function() {
                  isLoading = true;
                  isAudioReady = false;
                  icon.style.opacity = '0.7';
                  icon.style.cursor = 'wait';
                });

                audio.addEventListener('stalled', function() {
                  console.warn('Audio loading stalled');
                  isLoading = false;
                });

                audio.addEventListener('suspend', function() {
                  console.warn('Audio loading suspended');
                  isLoading = false;
                });

                audio.addEventListener('play', function() {
                  setState('playing');
                });

                audio.addEventListener('pause', function() {
                  setState('idle');
                });

                audio.addEventListener('ended', function() {
                  setState('idle');
                  if (progressCircle) {
                    progressCircle.style.strokeDashoffset = `${circumference}`;
                  }
                });

                audio.addEventListener('timeupdate', function() {
                  if (!progressCircle || !audio.duration || isNaN(audio.duration) || isNaN(audio.currentTime)) {
                    return;
                  }
                  const progress = Math.min(audio.currentTime / audio.duration, 1);
                  const offset = circumference - (progress * circumference);
                  progressCircle.style.strokeDashoffset = `${offset}`;
                });

                return audio;
              };

              icon.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                if (!audioSrc || audioSrc.trim() === '') {
                  return;
                }

                if (!audio) {
                  audio = createAudio();
                  audio.src = audioSrc;
                  
                  isLoading = true;
                  icon.style.opacity = '0.7';
                  icon.style.cursor = 'wait';
                  
                  audio.load();
                  
                  audio.addEventListener('canplay', function onCanPlay() {
                    audio.removeEventListener('canplay', onCanPlay);
                    if (audio.paused) {
                      const playPromise = audio.play();
                      if (playPromise !== undefined) {
                        playPromise.catch(function(error) {
                          console.error('Error playing audio:', error);
                          setState('error');
                          isAudioReady = false;
                          isLoading = false;
                        });
                      }
                    }
                  }, { once: true });
                  
                  return;
                }

                if (isLoading || !isAudioReady) {
                  return;
                }

                if (audio.paused) {
                  const playPromise = audio.play();
                  if (playPromise !== undefined) {
                    playPromise.catch(function(error) {
                      console.error('Error playing audio:', error);
                      setState('error');
                      isAudioReady = false;
                    });
                  }
                } else {
                  audio.pause();
                }
              });
            };

            if (document.readyState === 'loading') {
              document.addEventListener('DOMContentLoaded', initFloatingKaiAudio);
            } else {
              initFloatingKaiAudio();
            }
          })();
        </script>
        <?php
      }
    }
  }

  function excerpt_length( $length ) {
    if(is_feed())
    return $length;
    
    return kanews_get_option('excerpt-length',$length);
  }


  // Manşet 
  function kanews_manset_post_type() {

	$labels = array(
			'name'              => _x('Manşet Alanları', 'taxonomy general name'),
			'singular_name'     => _x('Manşet Alanı', 'taxonomy singular name'),
			'menu_name'         => _x('Manşet Alanı', 'admin menu'),
			'all_items'         => __('Tüm Manşet Alanları'),
			'edit_item'         => __('Manşet Alanını Düzenle'),
			'view_item'         => __('Manşet Alanını Görüntüle'),
			'update_item'       => __('Manşet Alanını Güncelle'),
			'add_new_item'      => __('Yeni Manşet Alanı Ekle'),
			'new_item_name'     => __('Yeni Manşet Alanı Adı'),
			'search_items'      => __('Manşet Alanı Ara'),
	);

	$args = array(
			'hierarchical'      => true,  // Kategoriler gibi bir yapı
			'labels'            => $labels,
			'public'            => false, // Ön yüzde ve aramalarda görünmesin
			'show_ui'           => true,  // Yazı editöründe görünsün
			'show_in_nav_menus' => false, // Navigasyon menülerinde görünmesin
			'show_tagcloud'     => false, // Tag bulutunda görünmesin
			'show_in_rest'      => true,  // REST API ve Gutenberg editörü için aktif
			'rewrite'           => false, // URL yeniden yazımı devre dışı
	);

	register_taxonomy('manset', array('post', 'columist'), $args);

  }

  // Firma Rehberi
  function kanews_firma_post_type() {
    $base = get_option('kanews_firma_slug', 'firma-rehberi');
    $catbase = 'firma-kategori';

    // Set the labels, this variable is used in the $args array
    $labels = array(
      'name'               => __( 'Firma Rehberi', 'kanews' ),
      'singular_name'      => __( 'Firma Rehberi', 'kanews' )
    );

    // The arguments for our post type, to be entered as parameter 2 of register_post_type()
    $args = array(
      'labels'            => $labels,
      // 'show_in_rest'      => true,
      'public'            => true,
      'menu_position'     => 5,
      'supports'          => array( 'title', 'editor', 'excerpt', 'author', 'comments', 'custom-fields', 'thumbnail' ),
      'show_in_nav_menus' => true,
      'menu_icon'         => 'dashicons-networking',
      'has_archive'       => true,
      'query_var'         => true,
      'exclude_from_search' => false,
      'rewrite' => array(
        'slug' => $base,
        'with_front' => true,
      ),
    );

  
    register_post_type( 'firma', $args);
    register_taxonomy(
      'kategori',  // The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces).
      'firma',             // post type name
      array(
        'hierarchical' => true,
        'label' => esc_html__('Firma Kategorisi','kanews' ), // display name
        'query_var' => true,
        'show_in_nav_menus' => true,
        'exclude_from_search' => false,
        'rewrite' => array(
          'slug' => $catbase,    // This controls the base slug that will display before each term
          'with_front' => false  // Don't display the category base before
        )
      )
    );
    
  }

  // İlan Sistemi
  function kanews_ilan_post_type() {
    $base    = get_option('kanews_ilan_slug', 'ilan');
    $catbase = 'ilan-kategori';

    // Set the labels, this variable is used in the $args array
    $labels = array(
      'name'               => __( 'İlanlar', 'kanews' ),
      'singular_name'      => __( 'İlan', 'kanews' )
    );

    // The arguments for our post type, to be entered as parameter 2 of register_post_type()
    $args = array(
      'labels'            => $labels,
      'public'            => true,
      'menu_position'     => 5,
      'supports'          => array( 'title', 'editor', 'excerpt', 'author', 'custom-fields', 'thumbnail' ),
      'show_in_nav_menus' => true,
      'has_archive'       => true,
      'query_var'         => true,
      'menu_icon'         => 'dashicons-insert',
      'exclude_from_search' => false,
      'rewrite' => array(
        'slug' => $base,
        'with_front' => true,
      ),
    );

  
    register_post_type( 'ilan', $args);
    register_taxonomy(
      'ilan-kategori',  // The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces).
      'ilan',     // post type name
      array(
        'hierarchical' => true,
        'label' => esc_html__('İlan Kategori', 'kanews'), // display name
        
        'query_var' => true,
        'show_in_nav_menus' => true,
        'exclude_from_search' => false,
        'rewrite' => array(
          'slug' => $catbase,    // This controls the base slug that will display before each term
          'with_front' => false  // Don't display the category base before
        )
      )
    );
    register_taxonomy(
      'ilan-etiket',  // The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces).
      'ilan',     // post type name
      array(
        'hierarchical' => false,
        'label' => esc_html__('İlan Etiket', 'kanews'), // display name
        'query_var' => true,
        'show_in_nav_menus' => true,
        'exclude_from_search' => false,
        'rewrite' => array('slug' => 'ilan-etiket', 'with_front' => true)
      )
    );    
    
    register_taxonomy(
      'ilan-il',  // The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces).
      'ilan',     // post type name
      array(
        'hierarchical' => false,
        'label' => esc_html__('İl', 'kanews'), // display name
        'query_var' => true,
        'show_in_nav_menus' => true,
        'exclude_from_search' => false,
        'rewrite' => array('slug' => 'ilan-il', 'with_front' => true)
      )
    );    
    
    register_taxonomy(
      'ilan-ilce',  // The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces).
      'ilan',     // post type name
      array(
        'hierarchical' => false,
        'label' => esc_html__('İlçe', 'kanews'), // display name
        'query_var' => true,
        'show_in_nav_menus' => true,
        'exclude_from_search' => false,
        'rewrite' => array('slug' => 'ilan-ilce', 'with_front' => true)
      )
    );
    
  }

  /**
   * Remove the slug from published post permalinks.
   */
  function custom_remove_ilan_slug($post_link, $post, $leavename)
  {
      if ('ilan-kategori' != $post->post_type || 'publish' != $post->post_status)
      {
          return $post_link;
      }
      $post_link = str_replace('/' . $post->post_type . '/', '/', $post_link);

      return $post_link;
  }

  // columist post type
  function kanews_author_post_type() {
    $base = get_option('kanews_author_base', 'author');
    $slug = get_option('kanews_author_slug', 'kose-yazisi');
    
    $labels = array(
      'name'               => __( 'Köşe Yazıları' ),
      'singular_name'      => __( 'Köşe Yazıları' ),
      'add_new'            => __( 'Add New Post' ),
      'add_new_item'       => __( 'Add New Post' ),
      'edit_item'          => __( 'Edit Post' ),
      'new_item'           => __( 'New Post' ),
      'all_items'          => __( 'All Posts' ),
      'view_item'          => __( 'View Post' ),
      'search_items'       => __( 'Search Posts' )
    );

    // The arguments for our post type, to be entered as parameter 2 of register_post_type()
    $args = array(
      'labels'            => $labels,
      'show_in_rest'      => true,
      'public'            => true,
      'menu_icon'         => 'dashicons-format-quote',
      'menu_position'     => 5,
      'supports'          => array( 'title', 'editor', 'excerpt', 'comments',  'author', 'thumbnail' ),
      'show_in_nav_menus' => true,
      'has_archive'       => $base,
      'taxonomies'        => array( 'category', 'post_tag' ),
      'query_var'         => true,
      'rewrite' => array(
        'slug' => $slug . '/%author%',
        'with_front' => true,
      ),
    );

    register_post_type( 'columist', $args);
  }

  function kanews_author_post_type_link( $post_link, $post, $leavename, $sample ) {
    if ( 'columist' == $post->post_type ) {
      $authordata = get_userdata( $post->post_author );
      $author = $authordata->user_nicename;
      $post_link = str_replace( '%author%', $author, $post_link );
    }
    return $post_link;
  }


  // Do not duplicate 
  public static function do_not_dublicate( $post_id = false ){

    if( empty( $post_id ) ){
      return;
    }

    if( empty( $GLOBALS['kan_do_not_duplicate'] ) ){
      $GLOBALS['kan_do_not_duplicate'] = array();
    }

    $GLOBALS['kan_do_not_duplicate'][ $post_id ] = $post_id;
  }

  // Featured Image to RSS Feed
  function featured_to_rss($content) {
    global $post;

    if(!kanews_get_option('featured-to-rss'))
    return $content;

    if(empty($content))
    $content = get_the_content();

    if ( has_post_thumbnail( $post->ID ) ){
      $content = strip_shortcodes($content);
      $content = '<div>' . get_the_post_thumbnail( $post->ID, 'medium', array( 'style' => 'margin-bottom: 15px;' ) ) . '</div>' . $content;
    }
    
    return $content;
  }

function kanews_ajax_search() {
    $search_qry = sanitize_text_field($_REQUEST['query']);

    $search_json = array(
        'query'       => $search_qry,
        'suggestions' => array(),
    );

    // WP_Query optimize edilmiş
    $args = array(
        's'                   => $search_qry,
        'post_type'           => array('post', 'columist'),
        'no_found_rows'       => true,
        'posts_per_page'      => 3,
        'post_status'         => 'publish',
        'ignore_sticky_posts' => true,
        'fields'              => 'ids', // sadece ID döndür
    );

    $kanews_query = new WP_Query($args);

    if ($kanews_query->have_posts()) {
        foreach ($kanews_query->posts as $post_id) {
            ob_start(); ?>
            <div class="kanews-post-item kanews-post-grid-item kanews-post-small-item">
              <?php echo get_the_post_thumbnail($post_id, 'thumbnail', array('class' => 'kanews-post-thumb')); ?>
              <div class="kanews-post-content">
                <?php echo get_the_date('', $post_id); ?>
                <h3 class="kanews-post-headline truncate truncate-2">
                    <a href="<?php echo esc_url(get_permalink($post_id)); ?>" rel="bookmark">
                        <?php echo esc_html(get_the_title($post_id)); ?>
                    </a>
                </h3>
              </div>
            </div>
            <?php
            $search_json["suggestions"][] = array(
                'layout'   => ob_get_clean(),
                'value'    => get_the_title($post_id),
                'url'      => get_permalink($post_id),
            );
        }

        // "Tüm sonuçlar" butonu
        $search_json['suggestions'][] = array(
            'layout'   => '<a class="kanews-btn kanews-btn-sm" href="' . esc_url(home_url('?s=' . urlencode($search_qry))) . '">' . esc_html__('Tüm Sonuçlar', 'kanews') . '</a>',
            'value'    => $search_qry,
            'url'      => esc_url(home_url('?s=' . urlencode($search_qry))),
        );
    }

    echo wp_json_encode($search_json);
    wp_die();
}

  function widget_posts_11_ajax() {
    if( ! empty( $_REQUEST['query'] ) ){
      $query = stripslashes( $_REQUEST['query'] );
      $query = json_decode( str_replace( '\'', '"', $query ), true );

      $style = stripslashes( $_REQUEST['style'] );
      $style = json_decode( str_replace( '\'', '"', $style ), true );

      $query['pagi'] = 1;
      $query['target_page'] = $_REQUEST['page'];
      $kanews_query = kan_query( $query );
      
      if ($kanews_query->have_posts()) {
        ob_start();
        kanews_widget_class_posts_11::post_content($kanews_query, $style, $query['number']*$_REQUEST['page2'], $query['target_page']);
        wp_send_json( wp_json_encode(
          array(
            'content'  => ob_get_clean(),
            'button'   => esc_html__( 'Yazı bulunamadı', 'kanews' ),
          )));

        die;
      }
    }

    wp_send_json( wp_json_encode(
      array(
        'disabled' => 1,
        'button' => esc_html__( 'Yazı bulunamadı', 'kanews' ),
      ))
    );

    die;
  }

  public static function remove_default_image_sizes( $sizes ) {

    /* Default WordPress */
    unset( $sizes[ 'thumbnail' ]);       // Remove Thumbnail (150 x 150 hard cropped)
    unset( $sizes[ 'medium' ]);          // Remove Medium resolution (300 x 300 max height 300px)
    unset( $sizes[ 'medium_large' ]);    // Remove Medium Large (added in WP 4.4) resolution (768 x 0 infinite height)
    unset( $sizes[ 'large' ]);           // Remove Large resolution (1024 x 1024 max height 1024px)
    unset( $sizes[ '1536x1536' ]);         
    unset( $sizes[ '2048x2048' ]);       
    
    /* With WooCommerce */
    unset( $sizes[ 'shop_thumbnail' ]);  // Remove Shop thumbnail (180 x 180 hard cropped)
    unset( $sizes[ 'shop_catalog' ]);    // Remove Shop catalog (300 x 300 hard cropped)
    unset( $sizes[ 'shop_single' ]);     // Shop single (600 x 600 hard cropped)
  
    unset( $sizes[ 'kanews-manset-1' ]); 
    unset( $sizes[ 'kanews-manset-2' ]); 
    unset( $sizes[ 'kanews-manset-3' ]); 
    unset( $sizes[ 'kanews-manset-4' ]);   
    unset( $sizes[ 'kanews-manset-5' ]);    
  
    unset( $sizes[ 'kanews-post-1' ]);
    unset( $sizes[ 'kanews-post-2' ]);
    unset( $sizes[ 'kanews-post-3' ]);
    
    return $sizes;
  }


}

