<?php 

if( class_exists( 'CSF' ) ) {

  // Helper: Firma meta bilgilerini tek bir yerden üret
  if ( ! function_exists( 'kanews_widget_firma_get_comp' ) ) {
    function kanews_widget_firma_get_comp( $post_id ) {
      return [
        'name'    => get_post_meta( $post_id, 'comp_name', true )   ? get_post_meta( $post_id, 'comp_name', true )   : get_the_title( $post_id ),
        'auth'    => get_post_meta( $post_id, 'comp_auth', true )   ? get_post_meta( $post_id, 'comp_auth', true )   : 'Belirtilmemiş',
        'city'    => get_post_meta( $post_id, 'comp_city', true )   ? get_post_meta( $post_id, 'comp_city', true )   : 'Belirtilmemiş',
        'address' => get_post_meta( $post_id, 'comp_adress', true ) ? get_post_meta( $post_id, 'comp_adress', true ) : 'Belirtilmemiş',
        'phone'   => get_post_meta( $post_id, 'comp_tel', true )    ? get_post_meta( $post_id, 'comp_tel', true )    : 'Belirtilmemiş',
        'fax'     => get_post_meta( $post_id, 'comp_fax', true )    ? get_post_meta( $post_id, 'comp_fax', true )    : 'Belirtilmemiş',
        'site'    => get_post_meta( $post_id, 'comp_site', true )   ? get_post_meta( $post_id, 'comp_site', true )   : 'Belirtilmemiş',
        'map'     => get_post_meta( $post_id, 'comp_map', true ),
      ];
    }
  }

  // Helper: Özel firma kartını (variation 2) render et
  if ( ! function_exists( 'kanews_widget_firma_render_special_item' ) ) {
    /**
     * @param string $col                Bootstrap kolon sınıfları
     * @param bool   $rating             Puan gösterilsin mi
     * @param array  $comp               kanews_widget_firma_get_comp çıktısı
     * @param bool   $show_excerpt       İçerik özetini göster
     * @param bool   $city_always_visible Şehir her durumda görünsün mü (rating kapalı olsa bile)
     */
    function kanews_widget_firma_render_special_item( $col, $rating, $comp, $show_excerpt = false, $city_always_visible = true ) {
      global $post, $sidebar;
      ?>
      <div class="kanews-slider-col <?php echo esc_attr( $col ); ?>">
      <div class="kanews-post-item kanews-post-grid-item">
									<a href="<?php the_permalink(); ?>" class="kanews-post-href kanews-slide-href" aria-label="<?php the_title(); ?>"></a>	
									<?php do_action('kanews_post_hook'); ?>
                  <?php kanews_post_thumbnail('kanews-post-3', 'kanews-post-thumb'); ?>
                  <div class="kanews-post-content">

                    <?php the_title( sprintf( '<h4 class="kanews-post-headline truncate truncate-2"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h4>' ); ?>
                    <?php if ( $city_always_visible || $rating ) : ?>
                  <div class="d-flex justify-content-center">
                    <?php if ( $city_always_visible || $rating ) : ?>
                      <div><i class="icon-location color-muted"></i> <?php echo esc_html( $comp['city'] ); ?></div>
                    <?php endif; ?>
                    <?php if ( $rating ) : ?>
                      <div style="margin-left: 1em"><i class="icon-star color-warning"></i> <?php echo ci_comment_rating_get_average_ratings( $post->ID ); ?></div>
                    <?php endif; ?>
                  </div>
                <?php endif; ?>

									</div>
                </div>
  
      </div>
      <?php
    }
  }

  CSF::createWidget( 'kanews_widget_firma', array(
    'title'       => KAN_THEME_NAME .' - '."Firma",
    'description' => "Firma rehberi ile alakalı tüm bileşenler.",
    'classname'   => 'kanews_widget_class_firma',
    'fields'      => array(

      array(
        'id'      => 'title',
        'type'    => 'text',
        'title'   => 'Title',
        'default'   => 'Firma',
      ),

      array(
        'id'      => 'widget',
        'type'    => 'select',
        'title'   => 'Kullanılacak Bileşen',
        'options' => array(
          'hero' => 'Hero (Page Header)',
          'post' => 'Firma Listesi',
          'search' => 'Firma Ara',
          'insights' => 'Abone Firmalar',
        ),
        'default' => 'post'
      ),
      array(
        'id'      => 'grid',
        'type'    => 'select',
        'title'   => 'Genişlik',
        'options' => array(
          'col-12' => '12/12',
          'col-12 col-lg-8' => '12/8',
          'col-12 col-lg-6' => '12/6',
          'col-12 col-lg-4' => '12/4'
        ),
        'default' => 'col-12'
      ),

      // Posts
      array(
        'id'      => 'col',
        'type'    => 'select',
        'dependency' => array( 'widget', '!=', 'search' ),
        'title'   => 'Sütun Başına Yazı',
        'options' => array(
          'col-6 col-lg-12' => '1',
          'col-6 col-lg-6' => '2',
          'col-6 col-lg-4' => '3',
          'col-6 col-md-4 col-lg-3' => '4',
          'col-6 col-md-3 col-lg-2' => '6',
        ),
        'default' => 'col-6 col-md-4 col-lg-3'
      ),
      array(
        'id'      => 'variations',
        'type'    => 'select',
        'dependency' => array( 'widget', '!=', 'search' ),
        'title'   => 'Varyasyon',
        'options' => array('1' => '1', '2' => '2'),
        'default' => '1'
      ),
      array(
        'id'       => 'posts',
        'dependency' => array( 'widget', '!=', 'search' ),
        'type'     => 'slider',
        'title'    => 'Firma Sayısı',
        'min'      => 1,
        'step'     => 1,
        'default'  => 6,
      ),
      array(
        'id'      => 'sortby',
        'type'    => 'select',
        'title'   => 'Göre Sırala',
        'dependency' => array( 'widget', '==', 'post' ),
        'options' => array(
          'recent' => 'Yayınlanma Tarihine Göre',
          'post-modified' => 'Düzenlenme Tarihine Göre',
          'rating' => 'Ortalama Puana Göre',
          'commented' => 'En Çok Yorum Yapılan',
          'random' => 'Rastgele'
        ),
        'default' => 'recent'
      ),
      array(
        'id'      => 'date_range',
        'type'    => 'select',
        'dependency' => array( 'widget', '==', 'post' ),
        'title'   => 'Zaman Aralığı',
        'options' => array(
          '0' => 'Zaman Aralığı Seçin',
          'day' => 'Son 1 Gün',
          'week' => 'Son 1 Hafta',
          'month' => 'Son 1 Ay',
          'year' => 'Son 1 Yıl',
        ),
        'default' => '0'
      ),
      array(
        'id'      => 'categories',
        'type'    => 'select',
        'dependency' => array( 'widget', '!=', 'search' ),
        'title'   => 'Kategori',
        'options' => 'kanews_get_terms_firma_kategori',
        'multiple'=> true,
        'chosen'  => true,
        'default' => '0'
      ),
      array(
        'id'      => 'city',
        'type'    => 'text',
        'dependency' => array( 'widget', '==', 'post' ),
        'title'   => 'İl',
      ),
      array(
        'id'      => 'rating',
        'type'    => 'switcher',
        'dependency' => array( 'widget', '!=', 'search' ),
        'title'   => 'Ortalama Puan',
        'default' => false
      ),
      array(
        'id'      => 'postnotin',
        'type'    => 'text',
        'dependency' => array( 'widget', '==', 'post' ),
        'title'   => 'Hariç Tutulan Firmalar',
        'default' => ''
      ),

      array(
        'id'      => 'show_more_link',
        'type'    => 'text',
        'dependency' => array( 'widget', '==', 'post' ),

        'title'   => 'Daha Fazla Linki',
        'default' => ''
      ),

      array(
        'id'      => 'hide_desktop',
        'type'    => 'switcher',
        'title'   => 'Masaüstünde Gizle',
        'default' => false
      ),
      array(
        'id'      => 'hide_mobile',
        'type'    => 'switcher',
        'title'   => 'Mobilde Gizle',
        'default' => false
      ),

      // Hero Settings
      array(
        'id'      => 'hero_title',
        'type'    => 'text',
        'dependency' => array( 'widget', '==', 'hero' ),
        'title'   => 'Başlık',
        'default' => 'Firma Rehberi'
      ),
      array(
        'id'      => 'hero_description',
        'type'    => 'textarea',
        'dependency' => array( 'widget', '==', 'hero' ),
        'title'   => 'Açıklama',
        'default' => 'Binlerce firmanın bilgilerine ulaşın, işletmenizi ücretsiz ekleyin.'
      ),
      array(
        'id'      => 'hero_bg_image',
        'type'    => 'media',
        'dependency' => array( 'widget', '==', 'hero' ),
        'title'   => 'Arka Plan Görseli',
        'library' => 'image',
      ),
      array(
        'id'      => 'hero_bg_color',
        'type'    => 'color',
        'dependency' => array( 'widget', '==', 'hero' ),
        'title'   => 'Arka Plan Rengi',
        'default' => '',
      ),
      array(
        'id'      => 'hero_overlay_color',
        'type'    => 'color',
        'dependency' => array( 'widget', '==', 'hero' ),
        'title'   => 'Overlay Rengi', 
      ),
      array(
        'id'      => 'hero_show_add_button',
        'type'    => 'switcher',
        'dependency' => array( 'widget', '==', 'hero' ),
        'title'   => 'Firma Ekle Butonu Göster',
        'default' => true
      ),
      array(
        'id'      => 'hero_show_all_button',
        'type'    => 'switcher',
        'dependency' => array( 'widget', '==', 'hero' ),
        'title'   => 'Tüm Firmalar Butonu Göster',
        'default' => true
      ),
      array(
        'id'      => 'hero_show_search',
        'type'    => 'switcher',
        'dependency' => array( 'widget', '==', 'hero' ),
        'title'   => 'Arama Formu Göster',
        'default' => true
      ),
      array(
        'id'      => 'hero_search_hint',
        'type'    => 'text',
        'dependency' => array( 'widget', '==', 'hero' ),
        'title'   => 'Arama Formu Altı Yazı',
        'default' => 'Firma adı ile arama yaparak aradığınız firmanın bilgilerine ulaşabilirsiniz.'
      ),
    
    )
  ) );
  
  if( ! function_exists( 'kanews_widget_firma' ) ) {
    function kanews_widget_firma( $widget_args, $instance ) {
      $hide_mobile = $instance['hide_mobile'] ? 'on' : 'off';
      $hide_desktop = $instance['hide_desktop']? 'on' : 'off';

      if( ! kanews_get_option('firma-rehberi') )
      return;

      if($hide_mobile == 'on') {
        if(kan_is_mobile())
        return;
      }

      if($hide_desktop == 'on') {
        if(!kan_is_mobile())
        return;
      }

      if( $instance['widget'] == 'hero' ) {
        $args_defaults = array( 
          'hero_title'           => 'Firma Rehberi',
          'hero_description'     => 'Binlerce firmanın bilgilerine ulaşın, işletmenizi ücretsiz ekleyin.',
          'hero_bg_image'        => '',
          'hero_bg_color'        => '',
          'hero_overlay_color'   => '',
          'hero_show_add_button' => true,
          'hero_show_all_button' => true,
          'hero_show_search'     => true,
          'hero_search_hint'     => 'Firma adı ile arama yaparak aradığınız firmanın bilgilerine ulaşabilirsiniz.',
        ); 
        $args = wp_parse_args( $instance, $args_defaults );
        
        // Translate default values if empty
        if (empty($instance['hero_title'])) {
          $args['hero_title'] = esc_html__('Firma Rehberi', 'kanews');
        } else {
          $args['hero_title'] = esc_html($args['hero_title']);
        }
        if (empty($instance['hero_description'])) {
          $args['hero_description'] = esc_html__('Binlerce firmanın bilgilerine ulaşın, işletmenizi ücretsiz ekleyin.', 'kanews');
        } else {
          $args['hero_description'] = esc_html($args['hero_description']);
        }
        if (empty($instance['hero_search_hint'])) {
          $args['hero_search_hint'] = esc_html__('Firma adı ile arama yaparak aradığınız firmanın bilgilerine ulaşabilirsiniz.', 'kanews');
        } else {
          $args['hero_search_hint'] = esc_html($args['hero_search_hint']);
        }
        
        // Get background image
        $bg_image = '';
        if (!empty($args['hero_bg_image'])) {
          $bg_image_id = is_array($args['hero_bg_image']) ? $args['hero_bg_image']['id'] : $args['hero_bg_image'];
          if ($bg_image_id) {
            $bg_image = wp_get_attachment_image_url($bg_image_id, 'full');
          }
        }
        
        // Get background color
        $bg_color = !empty($args['hero_bg_color']) ? $args['hero_bg_color'] : '';
        if( empty($bg_image) && empty($bg_color) ) {
          $bg_image = get_template_directory_uri() . '/assets/img/static/Footer.jpg';
        }
        
        // Get overlay color
        $overlay_color = !empty($args['hero_overlay_color']) ? $args['hero_overlay_color'] : '';
        
        // Get links
        $add_firma_url = kanews_get_option('account-page') ? esc_url(add_query_arg('islem', 'firma-ekle', kanews_account_page_url())) : '#';
        $all_firma_url = get_post_type_archive_link('firma');
        
        // Unique ID for widget instance
        $widget_id = 'widget-' . uniqid();
        
        echo '<div class="col-12"><div class="kanews-widget-firma-hero container-full">'; ?>
        
        <div class="kanews-page-header kanews-page-header-cpt">
            <div class="kanews-page-header-bg" style="<?php 
              if (!empty($bg_image)) : 
                echo 'background-image: url(\'' . esc_url($bg_image) . '\');';
              endif;
              if (!empty($bg_color)) : 
                echo ' background-color: ' . esc_attr($bg_color) . ';';
              endif;
            ?>"></div>
            <div class="kanews-page-header-overlay" style="<?php 
              if (!empty($overlay_color)) : 
                echo 'background-color: ' . esc_attr($overlay_color) . ';';
              endif;
            ?>"></div>
            
            <div class="container">
                <div class="row align-items-center justify-content-center text-center">
                    <div class="col-12 col-lg-6">
                        
                        <h1 class="kanews-page-title"><?php echo esc_html($args['hero_title']); ?></h1>
                        
                        <?php if (!empty($args['hero_description'])) : ?>
                        <p class="kanews-page-description"><?php echo esc_html($args['hero_description']); ?></p>
                        <?php endif; ?>
                        
                        <?php if ($args['hero_show_add_button'] || $args['hero_show_all_button']) : ?>
                        <div class="kanews-page-header-actions gap-1 d-flex flex-wrap">
                            <?php if ($args['hero_show_add_button'] && kanews_get_option('account-page')) : ?>
                            <a href="<?php echo esc_url($add_firma_url); ?>" class="kanews-btn kanews-btn-sm">
                                <i class="icon-plus"></i> <?php esc_html_e('Firma Ekle', 'kanews'); ?>
                            </a>
                            <?php endif; ?>
                            <?php if ($args['hero_show_all_button']) : ?>
                            <a href="<?php echo esc_url($all_firma_url); ?>" class="kanews-btn bg-info kanews-btn-sm">
                                <?php esc_html_e('Tüm Firmalar', 'kanews'); ?>
                            </a>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>
                        
                        <?php if ($args['hero_show_search']) : ?>
                        <div class="kanews-page-header-search">
                            <form method="GET" class="kanews-form-filter" action="<?php echo get_post_type_archive_link('firma'); ?>">
                                <div class="kanews-form2 mb-0 position-relative">
                                    <input value="<?php echo isset($_GET['comp_name']) ? esc_attr($_GET['comp_name']) : ''; ?>" type="text" name="comp_name" placeholder="<?php esc_html_e('Firma Adı Ara...', 'kanews'); ?>">
                                </div>
                            </form>
                            <?php if (!empty($args['hero_search_hint'])) : ?>
                            <div class="kanews-search-hint"><?php echo esc_html($args['hero_search_hint']); ?></div>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        
        <?php 
        echo '</div></div>';
      } else if( $instance['widget'] == 'search' ): 
        $args_defaults = array( 
          'title' => 'Firma Rehberi',
          'grid'  => 'col-12',
        );
        $args = wp_parse_args( $instance, $args_defaults );

        echo '<div class="'.$args['grid'].'"><div class="kanews-section kanews-widget-ilan-search">'; ?>
        
        <?php if ( ! empty($args['title']) ):
          echo ( $widget_args['before_title'] . $args['title'] . $widget_args['after_title'] );
        endif; ?>

        <form method="GET" action="<?php echo get_post_type_archive_link('firma'); ?> ">
          <div class="d-flex flex-wrap" style="padding: 1em 0">
            <div class="col-12 col-lg-6">
              <div class="kanews-form2">
                <input value="<?php echo isset($_GET['comp_name']) ? $_GET['comp_name'] : ''; ?>" type="text" name="comp_name" placeholder="Firma Adı">
              </div>
            </div>
            <div class="col-12 col-lg-6">
              <div class="kanews-form2">
                <input value="<?php echo isset($_GET['comp_city'])? $_POST['comp_city'] : ''; ?>" type="text" name="comp_city" placeholder="Şehir">
              </div>
            </div>
            <div class="col-12">
              <div class="kanews-form2">
                <?php $select_value = isset($_POST['comp_cat']) ? $_POST['comp_cat'] : ''; ?>
                <?php 
                if( $terms = get_terms( array(
                  'taxonomy' => 'kategori', // to make it simple I use default categories
                  'orderby' => 'name'
              ) ) ) : 
                // if categories exist, display the dropdown
                echo '<select value="'.$select_value.'" name="comp_cat"><option value="">Kategori</option>';
                foreach ( $terms as $term ) :
                  echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as an option value
                endforeach;
                echo '</select>';
              endif;
              ?>
              </div>
            </div>
            <div class="col-12">
              <div class="kanews-form2">
                <select name="comp_rating_min">
                  <option value="">Minumum Puan</option>
                  <option <?php echo (isset($_GET['comp_rating_min']) && $_GET['comp_rating_min'] == '1') ? 'selected="select""': ''; ?> value="1">1</option>
                  <option <?php echo (isset($_GET['comp_rating_min']) && $_GET['comp_rating_min'] == '1') == '2' ? 'selected="select""': ''; ?>  value="2">2</option>
                  <option <?php echo (isset($_GET['comp_rating_min']) && $_GET['comp_rating_min'] == '1') == '3' ? 'selected="select""': ''; ?>  value="3">3</option>
                  <option <?php echo (isset($_GET['comp_rating_min']) && $_GET['comp_rating_min'] == '1') == '4' ? 'selected="select""': ''; ?>  value="4">4</option>
                  <option <?php echo (isset($_GET['comp_rating_min']) && $_GET['comp_rating_min'] == '1') == '5' ? 'selected="select"': ''; ?>  value="5">5</option>
                </select>
              </div>
            </div>
            <div class="col-12">
              <div class="kanews-form2 mb-0">
                <select name="comp_rating_max">
                  <option value="">Maksimum Puan</option>
                  <option <?php echo (isset($_GET['comp_rating_max']) && $_GET['comp_rating_max'] == '1') == '1' ? 'selected="select""': ''; ?> value="1">1</option>
                  <option <?php echo (isset($_GET['comp_rating_max']) && $_GET['comp_rating_max'] == '1') == '2' ? 'selected="select""': ''; ?>  value="2">2</option>
                  <option <?php echo (isset($_GET['comp_rating_max']) && $_GET['comp_rating_max'] == '1') == '3' ? 'selected="select""': ''; ?>  value="3">3</option>
                  <option <?php echo (isset($_GET['comp_rating_max']) && $_GET['comp_rating_max'] == '1') == '4' ? 'selected="select""': ''; ?>  value="4">4</option>
                  <option <?php echo (isset($_GET['comp_rating_max']) && $_GET['comp_rating_max'] == '1') == '5' ? 'selected="select"': ''; ?>  value="5">5</option>
                </select>
              </div>
            </div>
            <div class="col-12">
              <button type="submit" class="kanews-btn kanews-btn-block mb-0 kanews-btn-sm"><?php esc_html_e('Ara', 'kanews'); ?></button>
            </div>
          </div>
        </form>
        <?php echo '</div></div>';
      elseif( $instance['widget'] == 'insights' ): 
        $args_defaults = array( 
          'grid'       => 'col-12',
          'col'        => 'col-6 col-md-4 col-lg-3',
          'title'      => 'Abone Firmalar',
          'categories' => '',
          'variations' => '1',
          'rating'     => false,
          'posts'      => 10,
        ); 
        $args = wp_parse_args( $instance, $args_defaults );
        extract($args);

        if(!empty($categories)) {
          $tax_query = array(
            array(
              'taxonomy' => 'kategori',
              'field' => 'id',
              'terms' => $categories,
            ) 
            );
        } else {
          $tax_query = '';
        }
    
        $all_user_ids = Kanews\Util\Cache::get_users([
          'fields' => 'id',
          'meta_key' => 'kanews_insights_purchase_date',
          'meta_compare' => '!==',
          'meta_value' => ''
        ]);
        
        $kanews_query = new WP_Query(
          array( 
            'showposts'    => $posts,
            'post_type'    => 'firma',
            'author__in'   => $all_user_ids,
            'tax_query'    => $tax_query
          )
        );
        ?>
        <?php if ($kanews_query->have_posts()) :?>
          <div class="<?php echo $grid; ?>"> 
            <div class="kanews-section kanews_widget_comp_2 kanews_widget_comp <?php echo $variations != 2 ? 'kanews-section-flat' : 'kanews-section-gutter'; ?>">
              <?php if ( ! empty($title) ):
                echo ( $widget_args['before_title'] . $title . $widget_args['after_title'] );
              endif; ?>
      
      <?php if($variations == 2): 
   $item = 4;
    if(isset($widget_args['id']))
		$sidebar = explode('-', $widget_args['id']);
		else
		$sidebar = array('0' => 'home', '1' => 'content');
      if(isset($sidebar[2]) && $sidebar[2] == 'full') {
     
			switch($grid) {
				case 'col-12':
					$item = 4;
				break;
				case 'col-12 col-lg-8':
					$item = 3;
				break;
				case 'col-12 col-lg-6':
					$item = 2;
				break;
				case 'col-12 col-lg-4':
					$item = 1;
				break;
			}
		}
    elseif($sidebar[1] == 'content') {
      $item = 3;
      $grid = 'col-12';
		}
		elseif($sidebar[1] == 'sidebar') {
      $item = 1;
      $thumbnail = 'kanews-post-3';
      $grid = 'col-12';
		}
        $slick_options = [
          'slidesToShow'  => $item,
          'dots'  => true,
          'adaptiveHeight'  => false,
          'arrows'			  => true,
          'autoplay'			=> 1,
          'responsive' 			=> [
            [
              'breakpoint' 	 => 992,
              'settings'		 => [
                'slidesToShow' => 3
              ]
            ],
            [
              'breakpoint' 	 => 525,
              'settings'		 => [
                'slidesToShow' => 2
              ]
            ],
            [
              'breakpoint' 	 => 400,
              'settings'		 => [
                'slidesToShow' => 1
              ]
            ],
          ]
        ];

        switch($item) {
          case 1:
            $item_Col = 'kanews-slider-col col-12 col-md-12';
            break;
          case 2:
            $item_Col = 'kanews-slider-col col-12 col-md-4 col-lg-6';
            break;
          case 3:
            $item_Col = 'kanews-slider-col col-12 col-md-4 col-lg-4';
            break;
          case 4:
            $item_Col = 'kanews-slider-col col-12 col-md-4 col-lg-3';
            break;
        }
        ?>
        <div class="kanews-slider-0">

<div class="kanews-slider-wrapper kanews-slider-grid" data-slick='<?php echo wp_json_encode( $slick_options ); ?>'>
  <?php else: ?>
              <div class="row">
                <?php endif; ?>
                <?php $counter = 0; while($kanews_query->have_posts()): $kanews_query->the_post(); global $post;  ?>
                  <?php if(kanews_insights_control($post->post_author) == true): $counter++; ?>
                    <?php if($variations == 2): ?>
                      <?php $comp = kanews_widget_firma_get_comp( $post->ID ); ?>
                      <?php kanews_widget_firma_render_special_item( $col, $rating, $comp, true, false ); ?>
                    <?php else: ?>
                      <div class="<?php echo $col; ?> ">
                        <div class="kanews-post-item kanews-post-grid-item">
                          <a href="<?php the_permalink(); ?>" class="kanews-post-href"></a>
                          <?php kanews_post_thumbnail($thumbnail, 'kanews-post-comp-thumb'); ?>
                          <div class="kanews-post-content">
                            <?php the_title( sprintf( '<h4 class="kanews-post-headline truncate truncate-2"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h4>' ); ?>
                            <?php if($rating): ?>
                            <div><i class="icon-star"></i> <?php echo ci_comment_rating_get_average_ratings($post->ID); ?></div>
                            <?php endif; ?>
                          </div>
                        </div>
                      </div>
                    <?php endif; ?>
                  <?php endif; ?>
          
                <?php endwhile; wp_reset_postdata(); ?>
                <?php if($counter == 0): ?>
                  <p style="margin: 15px">Abone firma bulunamadı</p>
                <?php endif; ?>
                <?php if($variations != 2): ?>
                  </div>
                <?php else: ?>
                  </div>
                  </div>
              <?php endif; ?>
            </div>
            
          </div>
        <?php endif; ?>
      <?php else: 
        $args_defaults = array( 
          'grid'       => 'col-12',
          'col'        => 'col-6 col-md-4 col-lg-3',
          'title'      => '',
          'city'       => '',
          'postnotin'  => '',
          'show_more_link'  => '',
          'sortby'     => 'recent',
          'categories' => '',
          'variations' => '1',
          'rating'     => false,
          'posts'      => 6,
        ); 
        $args = wp_parse_args( $instance, $args_defaults );
        extract($args); 

        $postnotin = !empty($instance['postnotin']) ? $instance['postnotin'] : '';
        $excludeposts = explode(",", $postnotin);

        if(!empty($categories)) {
          $tax_query = array(
            array(
              'taxonomy' => 'kategori',
              'field' => 'id',
              'terms' => $categories,
            ) 
            );
        } else {
          $tax_query = '';
        }

        if(!empty($city)) {
          $meta_query = array( 'meta_query' => array(array('key' => 'comp_city', 'value' => $city, 'compare' => '=' )));
        } else {
          $meta_query = '';
        }

        if($sortby == 'commented') {
          $kanews_query = new WP_Query(
            array( 
              'post_type' => 'firma',
              'showposts' => $posts, 
              'orderby' => 'comment_count',
              'post__not_in' => $excludeposts,
              'tax_query' => $tax_query,
              'meta_query' => $meta_query
            )
          );
        }elseif($sortby == 'rating') {
          $kanews_query = new WP_Query(
            array( 
              'post_type'    => 'firma',
              'showposts'    => $posts,
              'post__not_in' => $excludeposts,
              'meta_key' => '_kanews_post_rating_overall',
              'orderby' => 'meta_value_num',
              'tax_query' => $tax_query,
              'meta_query' => $meta_query
            )
          );
        }elseif($sortby == 'random') {
          $kanews_query = new WP_Query(
            array( 
              'post_type'    => 'firma',
              'showposts'    => $posts,
              'post__not_in' => $excludeposts,
              'orderby' => 'rand',
              'tax_query' => $tax_query,
              'meta_query' => $meta_query
            )
          );
        }
        else {
          $kanews_query = new WP_Query(
            array( 
              'post_type'    => 'firma',
              'showposts'    => $posts,
              'post__not_in' => $excludeposts,
              'tax_query' => $tax_query,
              'meta_query' => $meta_query
            )
          );
        }
        ?>

        <?php if ($kanews_query->have_posts()) :?>
          <div class="<?php echo $grid; ?>"> 
          <div class="kanews-section kanews_widget_comp_2 kanews_widget_comp <?php echo $variations != 2 ? 'kanews-section-flat' : 'kanews-section-gutter'; ?>">
          <?php 
              if ( ! empty($title) ){
                echo ( $widget_args['before_title'] . $title . $widget_args['after_title'] );
              }
              ?>
      
      <?php if($variations == 2): 
   $item = 4;
    if(isset($widget_args['id']))
		$sidebar = explode('-', $widget_args['id']);
		else
		$sidebar = array('0' => 'home', '1' => 'content');
      if(isset($sidebar[2]) && $sidebar[2] == 'full') {
     
			switch($grid) {
				case 'col-12':
					$item = 4;
				break;
				case 'col-12 col-lg-8':
					$item = 3;
				break;
				case 'col-12 col-lg-6':
					$item = 2;
				break;
				case 'col-12 col-lg-4':
					$item = 1;
				break;
			}
		}
    elseif($sidebar[1] == 'content') {
      $item = 3;
      $grid = 'col-12';
		}
		elseif($sidebar[1] == 'sidebar') {
      $item = 1;
      $thumbnail = 'kanews-post-3';
      $grid = 'col-12';
		}
        $slick_options = [
          'slidesToShow'  => $item,
          'dots'  => true,
          'adaptiveHeight'  => false,
          'arrows'			  => true,
          'autoplay'			=> 1,
          'responsive' 			=> [
            [
              'breakpoint' 	 => 992,
              'settings'		 => [
                'slidesToShow' => 3
              ]
            ],
            [
              'breakpoint' 	 => 525,
              'settings'		 => [
                'slidesToShow' => 2
              ]
            ],
            [
              'breakpoint' 	 => 400,
              'settings'		 => [
                'slidesToShow' => 1
              ]
            ],
          ]
        ];

        switch($item) {
          case 1:
            $item_Col = 'kanews-slider-col col-12 col-md-12';
            break;
          case 2:
            $item_Col = 'kanews-slider-col col-12 col-md-4 col-lg-6';
            break;
          case 3:
            $item_Col = 'kanews-slider-col col-12 col-md-4 col-lg-4';
            break;
          case 4:
            $item_Col = 'kanews-slider-col col-12 col-md-4 col-lg-3';
            break;
        }
        ?>
        <div class="kanews-slider-0">

<div class="kanews-slider-wrapper kanews-slider-grid" data-slick='<?php echo wp_json_encode( $slick_options ); ?>'>
  <?php else: ?>
              <div class="row">
                <?php endif; ?>
                <?php while($kanews_query->have_posts()): $kanews_query->the_post(); global $post;  ?>

                    <?php if($variations == 2): ?>
                      <?php $comp = kanews_widget_firma_get_comp( $post->ID ); ?>
                      <?php kanews_widget_firma_render_special_item( $item_Col, $rating, $comp, false, true ); ?>
                    <?php else: ?>
                      <div class="<?php echo $col; ?> ">
                        <div class="kanews-post-item kanews-post-grid-item">
                          <a href="<?php the_permalink(); ?>" class="kanews-post-href"></a>
                          <?php kanews_post_thumbnail($thumbnail, 'kanews-post-comp-thumb'); ?>
                          <div class="kanews-post-content">
                            <?php echo get_the_term_list($post->ID, 'kategori', '<div class="kanews-post-meta">', ', ', '</div>'); ?>
                            <?php the_title( sprintf( '<h4 class="kanews-post-headline truncate truncate-2"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h4>' ); ?>
                            <div><i class="icon-star color-warning"></i> <?php echo ci_comment_rating_get_average_ratings($post->ID); ?></div>
                          </div>
                        </div>
                      </div>
                    <?php endif; ?>
                <?php endwhile; wp_reset_postdata(); ?>

                <?php if ( isset($instance['show_more_link']) && !empty($instance['show_more_link']) ): ?>
							<div class="col-12">
              <div class="d-flex justify-content-center align-items-center"><a href="<?php echo esc_url($instance['show_more_link']); ?>" class="kanews-label kanews-label-widget"><?php esc_html_e( 'Daha Fazla', 'kanews' ); ?></a></div>
							</div>
						<?php endif; ?>
          
              <?php if($variations != 2): ?>
                </div>
              <?php else: ?>
                </div> 
                </div> 
              <?php endif; ?>
            </div>
            </div>
        <?php endif; ?>
      <?php endif;
    }
  }
}