<?php
namespace Kanews\Util;
use Kanews\Helper_Wp;

class Seo {

  private static $instance;

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

  function __construct() {
    add_action( 'wp_head', array($this, 'json_ld'), 10);   
    add_post_type_support('post', 'kanews-article-json-ld');
    add_post_type_support('page', 'kanews-article-json-ld');
    add_post_type_support('columist', 'kanews-article-json-ld'); 
  }

  /**
  * Check Seo Plugins
  */
  function check_seo_plugins(){

    $is_active = false;

    // Yoast SEO
    if( class_exists( 'WPSEO_Frontend' ) )
    $is_active = true;

    // Rank Math SEO
    elseif( function_exists('rank_math') )
    $is_active = true;

    return $is_active;
  }

  function json_ld() {
    if(!kanews_get_option('json-ld'))
    return;

    $jsonld = $data = '';

    $data = array(
      $this->organization(),
      $this->thumbnail(),
      $this->website(),
      $this->page(),
      $this->posting(),
      $this->archives()
    );

    $jsonld = json_encode(array_values(array_filter($data)));
    $out = '<!-- Kanews: Schema Meta -->'."\n";
    $out .=  '<script id="kanews-theme-schema" type="application/ld+json">'."\n";
    $out .= '{"@context": "https://schema.org","@graph": '.$jsonld.'}'."\n";
    $out .= '</script>' . "\n";
    $out .= '<!-- /Kanews: Schema Meta -->'."\n";

    echo kan_minify_js($out);
  }

  function organization() {
    $data['@type'] = 'Organization';
    $data['@id']   = home_url('/#organization');
    $data['url']   = home_url('/');
    $data['name']  = get_bloginfo('name', 'display');
    $data['logo']  = kanews_get_option('logo');

    if ($data['logo']['type'] == 'img' && $data['logo']['logo-img']['url'] != '') {
      $data['logo'] = [
        '@type'  => 'ImageObject',
        'url'    => $data['logo']['logo-img']['url'],
        'width'  => $data['logo']['logo-img']['width'],
        'height' => $data['logo']['logo-img']['height'],
      ];        
    } else {
      unset($data['logo']);
    }

    $data = apply_filters('kanews_organization_json_ld_data', $data);
    return $data;
  }

  /* Thumbnail */
  function thumbnail($post = null) {
    $post = get_post($post);
    $data = array();

    if($post == NULL)
    return;

    if(!is_singular())
    return;

    $post_thumbnail_id = get_post_thumbnail_id($post->ID);
    if (!empty($post_thumbnail_id)) {
      $post_thumbnail_src = wp_get_attachment_image_src($post_thumbnail_id, 'full');
      if (!empty($post_thumbnail_src)) {
        $data = array(
          '@type'  => 'ImageObject',
          '@id'     => get_the_permalink($post->ID).'#primaryImage',
          'url'    => $post_thumbnail_src[0],
          'width'  => $post_thumbnail_src[1],
          'height' => $post_thumbnail_src[2],
          'inLanguage' => get_bloginfo("language")
        );
      }
    } else {
      return false;
    }

    $data = apply_filters('kanews_thumbnail_json_ld_data', $data, $post);
    return $data;
  }

  /* Website */
  function website() {
    global $wp;

    $data['@type']           = 'WebSite';
    $data['@id']             = home_url('/#website');
    $data['url']             = home_url();
    $data['name']            = get_bloginfo('name');
    $data['description']     = get_bloginfo('description');
    $data['publisher']       = array('@id' => home_url('/#organization'));
    $data['inLanguage']      = get_bloginfo("language");
    $data['potentialAction'] = $this->search();

    $data = apply_filters('kanews_website_json_ld_data', $data);
    return $data;
  }

  /* WebPage or CollectionPage */
  function page() {
    global $wp;
    // wp_die(print_r($wp));
    $current_url = trailingslashit(home_url($wp->request));

    if( is_archive() && !is_post_type_archive('columist') ) {
      $type = 'CollectionPage';
      $title = preg_replace( '#^[\w\d\s]+:\s*#', '', strip_tags( get_the_archive_title() ) ).' - '.get_bloginfo('name');
    } elseif( is_home() || is_front_page() ) {
      $type = 'CollectionPage';
      $data['about'] = array('@id' => home_url('/#organization'));
      $title = get_bloginfo('name').' - '.get_bloginfo('description');
    } elseif( is_singular()) {
      global $post;
      $type = 'WebPage';
      $title = get_the_title($post->ID).' - '.get_bloginfo('name');
      if( is_page_template( 'inc/emtia.php' ) ) {
        $name = isset($_GET['emtia']) && !empty($_GET['emtia']) ? $_GET['emtia'] : get_query_var('emtia');
				if( $name ) {
          $current_url = kanews_get_page_link('emtia', $name, 'emtia');

          $search  = array('ONS', 'GRA', 'CEY', 'YAR', 'TAM', 'CUM', 'ATA', 'RES', 'HAM', 'IKI', 'GRE', 'BES', 'ODA', 'OSA', 'YIA', 'GUM' );
          $replace = array('ONS Altın ', 'Gram Altın', 'Çeyrek Altın', 'Yarım Altın', 'Tam Altın', 'Cumhuriyet Altın', 'Ata Altın', 'Reşat Altın', 'Hamit Altın', 'İkibuçuk Altın', 'Gremse Altın', 'Beşli Altın', '14 Ayar Altın', '18 Ayar Altın', '22 Ayar Altın', 'Gümüş Gram');

          $title = wp_sprintf( esc_html__('%1$s Ne Kadar, Kaç TL?', 'kanews'), esc_html(str_replace($search, $replace, strtoupper($name))) ).' - '.get_bloginfo( 'name' );
        }
      }elseif( is_page_template( 'inc/standings.php' ) ) {
        $name = isset($_GET['lig']) && !empty($_GET['lig']) ? $_GET['lig'] : get_query_var('lig');
        if( $name ) {
          $current_url = kanews_get_page_link('lig', $name, 'puan');
            $title = wp_sprintf( __('%1$s Puan Durumu', 'kanews'), ucwords( str_replace("-", " ", $name)) );
        } else {
            $name = isset($_GET['lig']) && !empty($_GET['lig']) ? $_GET['lig'] : kanews_get_option('league-default', 'super-lig');;
            $title = wp_sprintf( __('%1$s Puan Durumu', 'kanews'), ucwords( str_replace("-", " ", $name)) );
        }
      }elseif( is_page_template( 'inc/livescore.php' ) ) {
        global $wp;
        $name = isset($_GET['lig']) && !empty($_GET['lig']) ? $_GET['lig'] : get_query_var('lig');
        $tarih = isset($_GET['tarih']) && !empty($_GET['tarih']) ? $_GET['tarih'] : date('Y-m-d');
				if( $name )  {
          $lig_title = kanews_correct_league_title2($name);

          $current_url = home_url(add_query_arg( array('lig' => urlencode( $name ), 'tarih' => $tarih), $wp->request));
          $title = sprintf(esc_html__('%s Canlı Maç Sonuçları (%s)', 'kanews'), $lig_title, $tarih).' - '.get_bloginfo( 'name' );
        }
      }elseif( is_page_template( 'inc/newspaper.php' ) ) {
        $name = isset($_GET['gazete']) && !empty($_GET['gazete']) ? $_GET['gazete'] : get_query_var('gazete');
				if( $name )  {
          $newspapers = [
            'aksam' => 'Akşam',
            // 'yeni-safak' => 'Yeni Şafak',
            // 'fanatik' => 'Fanatik',
            'fotomac' => 'Fotomaç',
            'milliyet' => 'Milliyet',
            // 'sozcu' => 'Sözcü',
            'takvim-gazetesi' => 'Takvim',
            'hurriyet' => 'Hürriyet',
            'sabah' => 'Sabah',
            'milli-gazete' => 'Milli',
            'yenicag' => 'Yeni Çağ',
            'milat' => 'Milat',
            'turkiye' => 'Türkiye',
            'turkgun' => 'Türkgün',
            'dunya' => 'Dünya',
            'yenisoz' => 'Yenisöz',
            // 'harbi-gazete' => 'Harbi Gazete',
            'dogru-haber' => 'Doğru Haber',
            'yeni-birlik' => 'Yeni Birlik',
            'aydinlik' => 'Aydınlık',
					];
          $current_url = kanews_get_page_link('gazete', $name, 'gazete');
          $title = sprintf(esc_html__('%s Gazetesi Manşetleri', 'kanews'), ( isset($newspapers[$name]) ? $newspapers[$name] : $name )).' - '.get_bloginfo( 'name' );
        }
      }elseif( is_page_template( 'inc/currencies.php' ) ) {
        $name = isset($_GET['parite']) && !empty($_GET['parite']) ? $_GET['parite'] : get_query_var('parite');
				if( $name )  {
          $current_url = kanews_get_page_link('parite', $name, 'doviz');
          $title = wp_sprintf( esc_html__('%1$s Ne Kadar, Kaç TL?', 'kanews'), strtoupper($name).'/TRY' ).' - '.get_bloginfo( 'name' );
        }
      }elseif( is_page_template( 'inc/prayer.php' ) ) {
        $name = isset($_GET['sehir']) && !empty($_GET['sehir']) ? $_GET['sehir'] : get_query_var('sehir');
        $region = (isset($_GET['sehir']) &&  $_GET['sehir'] != 'null' && !empty($_GET['sehir'])) ? esc_html(ucwords($_GET['sehir'])) : kanews_get_option('prayer-page-city', 'Ankara');
        $city = (isset($_GET['ilce']) && $_GET['ilce'] != 'null' && !empty($_GET['ilce'])) ? esc_html(ucwords($_GET['ilce'])) : kanews_get_option('prayer-page-city2', $region);
        if( empty($city) )
        $city = $region;

        if( $region == 'Kocaeli' && $region == $city )
        $city = 'İzmit';
        
        if( $name )
        $current_url = kanews_get_page_link('sehir', $name, 'namaz');
        $title = wp_sprintf( esc_html__('%1$s Namaz Vakitleri', 'kanews'), $city ).' - '.get_bloginfo( 'name' );
        
      }elseif( is_page_template( 'inc/exchange.php' ) ) {
        $name = isset($_GET['hisse']) && !empty($_GET['hisse']) ? $_GET['hisse'] : get_query_var('hisse');
				if( $name ) {
        $current_url = kanews_get_page_link('hisse', $name, 'exchange');
        $title = wp_sprintf( esc_attr__('%1$s — Hisse Senedi Grafiği ve Piyasa Değeri', 'kanews'), strtoupper($name) ).' - '.get_bloginfo('name');
        }
      }elseif( is_page_template( 'inc/exchange2.php' ) ) {
        $name = isset($_GET['hisse']) && !empty($_GET['hisse']) ? $_GET['hisse'] : get_query_var('hisse');
				if( $name ) {
          $name = explode(':', $name)[1];
        $current_url = kanews_get_page_link('hisse', $name, 'exchange2');
        $title = wp_sprintf( esc_attr__('%1$s — Hisse Senedi Grafiği ve Piyasa Değeri', 'kanews'), strtoupper($name) ).' - '.get_bloginfo('name');
        }
      }elseif( (is_page_template( 'inc/cryptocurrencies.php' ) || is_page_template( 'inc/cryptocurrencies2.php'))  ) {
        $name = isset($_GET['coin']) && !empty($_GET['coin']) ? $_GET['coin'] : get_query_var('coin');
				if( $name ) {
          $current_url = kanews_get_page_link('coin', $name, 'crypto');
          $index = isset($_GET['index']) ? $_GET['index'] : kanews_get_option('crypto-page-index', 'try');
          $title = wp_sprintf( esc_attr__('%1$s Grafiği ve Piyasa Değeri', 'kanews'), strtoupper($name.'/'.$index)).' - '.get_bloginfo('name');
        }
      }elseif( is_page_template( 'inc/weather-2.php' )  ) {
        $name = isset($_GET['sehir']) && !empty($_GET['sehir']) ? $_GET['sehir'] : get_query_var('sehir');
        if( empty($name) ) {

        }
				if( $name ) {
          $current_url = kanews_get_page_link('sehir', $name, 'weather');

          $title = wp_sprintf( esc_attr__('%s için Hava Durumu', 'kanews'), ucfirst($name)).' - '.get_bloginfo('name');
        } else {
          $default_city = kanews_get_option('weather-cities') ? kanews_get_option('weather-cities') : '745042';
          $name = ucwords(kanews_get_turkey_cities2('key', $default_city));
          $title = wp_sprintf( esc_attr__('%s için Hava Durumu', 'kanews'), ucfirst($name)).' - '.get_bloginfo('name');
        }
      }elseif( is_page_template( 'inc/traffic.php' )  ) {
        $name = isset($_GET['sehir']) && !empty($_GET['sehir']) ? $_GET['sehir'] : get_query_var('sehir');
				if( $name )
        $title = wp_sprintf( esc_attr__('%s Yol Durumu', 'kanews'), ucfirst($name)).' - '.get_bloginfo('name');
      }elseif( is_page_template( 'inc/eczane.php' )  ) {
        $name = isset($_GET['sehir']) && !empty($_GET['sehir']) ? $_GET['sehir'] : get_query_var('sehir');
				if( $name ) {
          $current_url = kanews_get_page_link('sehir', $name, 'eczane');

          $title = wp_sprintf( esc_attr__('%s Nöbetçi Eczaneleri', 'kanews'), ucwords($name)).' - '.get_bloginfo('name');
        }else
        $title = wp_sprintf( esc_attr__('%s Nöbetçi Eczaneleri', 'kanews'), ucwords(kanews_get_option('eczane-page-city', 'Ankara'))).' - '.get_bloginfo('name');
      }
    } elseif(is_post_type_archive('columist')) {
      $type = 'WebPage';
      $title = esc_html__('Yazarlarımız', 'kanews').' - '.get_bloginfo('name');
    } else {
      $type = 'WebPage';
      $title = get_bloginfo('name');
      
    }
    
    $data['@type']           = $type;
    $data['@id']             = $current_url.'#webpage';
    $data['url']             = $current_url;
    $data['inLanguage']      = get_bloginfo("language");
    $data['name']            = $title;
    $data['isPartOf']        = array('@id' => home_url('/#website'));
    if($this->thumbnail())
    $data['primaryImageOfPage'] = array('@id' => $current_url.'#primaryImage');

    $data = apply_filters('kanews_webpage_json_ld_data', $data);
    return $data;
  }

  /* Search */
  function search() {
    $data['@type'] = 'SearchAction';
    $data['target'] = home_url('?s={search_term_string}');
    $data['query-input'] = 'required name=search_term_string';

    $data = apply_filters('kanews_search_json_ld_data', $data);
    return $data;
  }

  /* Archive items */
  function archives() {
    global $wp;
    $current_url = trailingslashit(home_url($wp->request));

    $data['@type'] = 'ItemList';
    $data['itemListElement'] = [];
    $counter = 0;

    if(!is_archive() || is_post_type_archive('columist'))
    return false;

    if ( have_posts() ) {
      while ( have_posts() ) : the_post(); $counter++; global $post;
        $data['itemListElement'][] = ['type' => 'ListItem', 'position' => $counter, 'url' => get_the_permalink($post->ID)];
      endwhile;
    }

    $data['mainEntityOfPage'] = array('@id' => $current_url.'#webpage');

    $data = apply_filters('kanews_archive_items_json_ld_data', $data);
    return $data;
  }

  /* Singular */
  function posting($post = null) {
    global $wp;
    $current_url = trailingslashit(home_url($wp->request));

    $data = [];
    $post = get_post($post);

    if (empty($post) || !post_type_supports($post->post_type, 'kanews-article-json-ld') || ! is_singular() || (is_page() && !is_page_template( array( 'page.php', 'page-no-sidebar.php' ) ))) {
      return false;
    }

    $data['@id'] = "#post-{$post->ID}";
    if(is_page() || $post->post_type == 'columist') {
      $format = 'Article';
    } else {
      $format = kanews_get_option('article-json-ld-format') != '' ? kanews_get_option('article-json-ld-format') : 'NewsArticle';
    }

    $data['@type']      = $format;
    $data['headline']   = get_the_title($post).' - '.get_bloginfo('name');
    $data['url']        = get_the_permalink($post);
    $data['isPartOf']   = array('@id' => $current_url.'#webpage');
    $data['inLanguage'] = get_bloginfo("language");

    if(get_post_field('post_excerpt', $post->ID))
    $data['description'] = get_post_field('post_excerpt', $post->ID);

    $post_author = $this->get_post_author_json_ld_data($post);
    if (! empty($post_author)) {
        $data['author'] = $post_author;
    }

    $post_taxonomies = get_post_taxonomies($post);

    if (in_array('post_tag', $post_taxonomies, true)) {
      $post_tags = get_the_tags($post);
      if ($post_tags && ! is_wp_error($post_tags)) {
        $data['keywords'] = [];
        foreach ($post_tags as $post_tag) {
          $data['keywords'][] = $post_tag->name;  
        }
      }
    }
    
    if (in_array('category', $post_taxonomies, true)) {
      $data['articleSection'] = get_cat_name((int) Helper_Wp::primary_category_id($post->ID), 'category');
      
    }

    $data['datePublished']    = get_the_date('c', $post);
    $data['dateModified']     = get_the_modified_date('c', $post);
    $data['publisher']        = array('@id' => home_url('/#organization'));
    if($this->thumbnail())
    $data['image']            = array('@id' => $current_url.'#primaryImage');
    $data['mainEntityOfPage'] = array('@id' => $current_url.'#webpage');

    $data = apply_filters('kanews_article_json_ld_data', $data, $post);
    return $data;
  }

  /**
  * Get post author JSON-LD data.
  *
  * @return array
  * @since  0.2
  */
  private function get_post_author_json_ld_data($post = null)
  {
      $data = [];
      $post = get_post($post);

      if (empty($post)) {
          return $data;
      }

      $post_author = get_userdata($post->post_author);

      if (empty($post_author)) {
          return $data;
      }

      $data['@type'] = 'Person';
      $data['name'] = $post_author->display_name;
      $data['url'] = esc_url(get_author_posts_url($post_author->display_name));

      $data = apply_filters('post_author_json_ld_data', $data, $post);
      return $data;
  }

}