<?php

if(!defined('ABSPATH'))
    exit;

class Syrus {

    public function __construct() {

    }

    public function initialize() {
        $this->add_actions();
        $this->add_filters();

        $this->initAjaxHandler();
        $this->initPostHandler();
        // $this->make_WordPress_happy();

        $this->initSettings();
        $this->initDeepL();
    }

    private function add_actions() {
        global $syrusActions;

        if(!isset($syrusActions)) {
            $syrusActions = new SyrusActions();
            $syrusActions->initialize();
        }

        return $syrusActions;
    }

    private function add_filters() {
        global $syrusFilters;

        if(!isset($syrusFilters)) {
            $syrusFilters = new SyrusFilters();
            $syrusFilters->initialize();
        }

        return $syrusFilters;
    }

    private function initPostHandler() {
        global $syrusPostHandler;
        $syrusPostHandler = new SyrusPostHandler();
        $syrusPostHandler->initialize();
    }

    private function initAjaxHandler() {
        global $syrusAjaxHandler;
        $syrusAjaxHandler = new SyrusAjaxHandler();
        $syrusAjaxHandler->initialize();
    }

    private function initSettings() {
        global $syrusSettings;
        $syrusSettings = new SyrusSettings();
        $syrusSettings->initalize();
    }

    private function initDeepL() {
        global $syrusDeepL;
        $api_key = $this->get_option('generali', 'deepl_api_key');
        
        if(!empty($api_key)) {
            $syrusDeepL = SyrusDeepL::getInstance($api_key);
            
            if(is_admin()) {
                add_action('admin_enqueue_scripts', function($hook) {
                    global $post;
                    
                    if(!$hook == 'post-new.php' && !$hook == 'post.php') {
                        return;
                    }
                    
                    if(!$post || $post->post_type !== 'post') {
                        return;
                    }
                    
                    wp_enqueue_script(
                        'syrus-deepl-js',
                        SYRUS_THEME_URI . '/js/admin/SyrusDeepL.class.js',
                        ['jquery'],
                        '1.0.0',
                        true
                    );
                    
                    wp_localize_script('syrus-deepl-js', 'syrus_deepl_args', [
                        'ajax_url' => admin_url('admin-ajax.php')
                    ]);
                });
            }
        }
    }

    public function get_css_dir() {
        return SYRUS_THEME_URI . '/css/';
    }

    public function get_js_dir() {
        return SYRUS_THEME_URI . '/js/';
    }

    public function get_img_dir($img_name = ""){
        $default = SYRUS_THEME_URI . '/assets/img/';
      
        if(!$img_name)
          return $default;
      
        return $default.$img_name;
    }

    public function get_option($context,$opt,$print = false){
        $option = get_option('syrus_theme_'.$context.'_'.$opt);
    
        if($opt == "robots_txt" || $opt == "ads_txt"){
            $option = '"'.$option.'"';
            $option = json_decode($option);
        }
        
        $option_clean = "";

        if($option) 
            $option_clean = str_replace('\"','"',$option);
        
        if($option_clean)
            $option_clean = str_replace("\'","'",$option_clean);
    
        if(!$print)
            return $option_clean;
        
        echo $option_clean;
    }

    public function get_template_parts($file = "") {

      if($file == "")
        return null;

      $file_path = SYRUS_THEME_PATH . "/template-parts/" . $file . ".php";

      if(!file_exists($file_path)) {
          _e("Page does not exists!",'syrus');
          return false;
      }
    
      return $file_path;

    }

    public function get_template_parts_admin($file = ""){

        if($file == "")
          return null;

        $file_path = SYRUS_THEME_PATH . "/template-parts/wp-admin/" . $file . ".php";
        
        if(!file_exists($file_path)) {
            _e("Page does not exists!",'syrus');
            return false;
        }
      
        return $file_path;
    }

    public function show_virtual_ads_txt() {
        if($this->get_option("file",'abilita_ads_txt') != 1)
            return true;
    
      $ads_txt = $this->get_option("file","ads_txt");
      
      echo $ads_txt;
      header('Content-type: text/plain');
      header('Content-disposition: inline');

      status_header(200);
    }

    public function _includi($percorso_file, $variabili = array(), $stampa = false){
        $output = NULL;
        if(file_exists($percorso_file)){
            extract($variabili);
            ob_start();
            include $percorso_file;
            $output = ob_get_clean();
        }
        if ($stampa) {
            print $output;
        }
        return $output;
    }

    public function has_nav_menu($menu){
        $menu_locations = get_nav_menu_locations();
        $menu_id = isset($menu_locations[$menu]) ? $menu_locations[$menu] : 0;
      
        if($menu_id == 0)
          return false;
        
        return true;
    }
      
    public function get_current_main_menu_name(){
        $menu_id = get_nav_menu_locations()['syrus-theme-main-menu'];
        return wp_get_nav_menu_object($menu_id)->name;
    }

    public function has_footer_menu($menu){
      $menu_locations = get_nav_menu_locations();
      $menu_id = isset($menu_locations['syrus-theme-footer-menu']) ? $menu_locations['syrus-theme-footer-menu'] : 0;
    
      if($menu_id == 0)
        return false;
      
      return true;
    }
      
    public function get_current_footer_menu_name(){
        $menu_id = get_nav_menu_locations()['syrus-theme-footer-menu'];
        return wp_get_nav_menu_object($menu_id)->name;
    }


    public function thumb_img($params = []){

        $img_size = isset($params["img_container_size"]) && $params["img_container_size"] == "12" ? "full" : "large";
      
        $img_container_col = isset($params["img_container_size"]) ? $params["img_container_size"] : "6";
        $img_col_order = isset($params['alternate']) && $params['alternate'] ? 2 : 1;
      
        $with_link = isset($params['with_link']) && $params['with_link'] ? true : false;
        $lazy_loadig = isset($params['lazy_loading']) && $params['lazy_loading'] ? true : false;
      
        if(!wp_is_mobile() && is_single()){
          $img_size = "full";
          $img_container_col = "12";
        }
      
        if(wp_is_mobile()){
          $img_size = "medium";
        }
      
        if(wp_is_mobile() && is_single()){
          $img_size = "large";
        }
      
        $args = [
          'img-size' => $img_size,
          'img-container-col' => $img_container_col,
          'img-col-order' => $img_col_order,
          'with_link' => $with_link,'lazy_loading' => $lazy_loadig
        ];
        
        
        return get_template_part('template-parts/template-part','thumb-img',$args);
    }

    public function post_reading_time() {
        $words = explode(' ',strip_tags(get_the_content()));
        $numWords = count($words);
        $readingSpeed = 200; // parole al minuto
        $timeInMinutes = $numWords / $readingSpeed;
        $minutes = floor($timeInMinutes);
        $seconds = round(($timeInMinutes - $minutes) * 60);
        $tempo_lettura = $minutes."m ".$seconds."s"; 
        $show = sanitize_text_field(get_theme_mod('reading-time'));
        if(!$show || $show == "yes") { ?>
      
          <span class="reading-time">
              <span class="dashicons dashicons-clock"></span>
              <?php echo $tempo_lettura ?>
          </span>
    <?php } }

    public function post_author(){ ?>

        <span class="news-author">
            <span class="news-author-by">By</span>
            <?php the_author(); ?>
        </span>
    <?php }

    public function post_category_list($no_link = true){
        $category_list = get_the_category_list(' ');
        $category_list_no_link = get_the_category();
    
        if($category_list && $category_list_no_link){ 
    
        $kses_data = wp_kses_data($category_list);
    
        if($kses_data != "")
            $replace = str_replace('href','title="'.preg_replace('/<[^>]*>/', '',$kses_data).'" href',$kses_data); 
    
        if(is_category())
            $replace = $category_list_no_link[0]->name;
        ?>
    
        <div class="news-category <?php echo wp_is_mobile() ? 'is-mobile' : ''; ?>">
            <?php if(!$no_link) { ?>
            <?php echo $replace; ?>
            <?php } else { ?>
            <?php foreach($category_list_no_link as $cat) { ?> 
                <?php echo "<p>".$cat->name."</p>" ?>
            <?php } ?> 
            <?php } ?>
        </div>
        
        <?php }else{ ?>
        <br>
        <?php }  
    }

    public function post_excerpt() {
        $parole_da_mostrare = 20;
        $p = get_post();
        $excerpt = wp_trim_words($p->post_content,$parole_da_mostrare); ?>
      
        <p class="news-excerpt"><?php echo esc_html($excerpt); ?></p>
      
    <?php }

    public function footer() {
        $current_layout = get_option('syrus_theme_layout',"");

        $footer = $current_layout && $current_layout != "1" ? "footer-" . $current_layout : "footer"; 

        $args = [
          'text_color_footer_menu' => sanitize_text_field(get_theme_mod('text-color-footer-menu','#bde7ff')) ?: '#bde7ff',
        ];
      
        return get_template_part('template-parts/template-part',$footer,$args);
    }

    public function get_network_syrus_sites() {
        $sites = [
          (object) array(
            'domain' => "syrus.blog",
            'lang' => "it",
            'country' => "Italy"
          ),
          (object) array(
            'domain' => "syrus.today",
            'lang' => "us",
            'country' => "United States",
          ),
          (object) array(
            'domain' => "syrus.dev",
            'lang' => "fr",
            'country' => "France",
          ),
          (object) array(
            'domain' => "syrus.es",
            'lang' => "es",
            'country' => "Spain",
          ),
          (object) array(
            'domain' => "syrus.com.br",
            'lang' => "br",
            'country' => "Brazil",
          ),
          (object) array(
            'domain' => "syrus.jp",
            'lang' => "jp",
            'country' => "Japan",
          ),
          (object) array(
            'domain' => "syrus.com.ru",
            'lang' => "ru",
            'country' => "Russia",
          ),
          (object) array(
            'domain' => "syrus.ae",
            'lang' => "ae",
            'country' => "United Arab Emirates",
          ),
          (object) array(
            'domain' => "syrus.online",
            'lang' => "de",
            'country' => "Germany",
          ),
          (object) array(
            'domain' => "syrus.gr",
            'lang' => "el",
            'country' => "Greece",
          ),
          (object) array(
            'domain' => "syrus.ro",
            'lang' => "ro",
            'country' => "Romania",
          ),
        ];
      
        return $sites;
    }

    public function get_categories_for_sidebar(){
        $cats = get_categories();
        $to_return = [];
      
        foreach($cats as $cat){
          $n_post = count(get_posts([
            'numberposts' => 10,
            'category' => $cat->term_id
          ]));
      
          if($n_post == 10)
            $to_return[] = $cat;
        }
      
        return $to_return;
    }

    public function get_directories_for_sidebar() {
      $menu_locations = get_nav_menu_locations();
      $menu_id = isset($menu_locations['syrus-theme-directories-menu']) ? $menu_locations['syrus-theme-directories-menu'] : 0;

      $menu_items = $menu_id ? wp_get_nav_menu_items($menu_locations['syrus-theme-directories-menu']) : [];
      $menu_items = is_array($menu_items) ? $menu_items : [];

      return $menu_items;
    }

    public function get_custom_logo_url() {
        return get_header_image() ?: $this->get_img_dir('blog-header.png');
    }

    public function get_blog_logo_url() {
      $custom_logo_id = get_theme_mod( 'custom_logo' );
      $image = $custom_logo_id ? wp_get_attachment_image_src( $custom_logo_id , 'full' ) : [$this->get_img_dir('main-menu-img.png')];
      return $image[0];
    }

    public function get_current_layout() {
      return (int) get_option('syrus_theme_layout',1);
    }

    public function topnav(){
        $current_layout = get_option('syrus_theme_layout',"");

        $topnav = $current_layout && $current_layout != "1" ? "topnav-" . $current_layout : "topnav"; 
        $main_menu_img = sanitize_text_field(get_theme_mod('custom_logo')) ? wp_get_attachment_image_src( sanitize_text_field(get_theme_mod('custom_logo')) , 'full' ) : null;

        if($main_menu_img && isset($main_menu_img[0]))
            $main_menu_img = $main_menu_img[0];


        $args = [
          'bg_color_after_main_menu' => sanitize_text_field(get_theme_mod('bg-color-after-main-menu','orange')) ?: 'orange',
          'background_color_motto' => sanitize_text_field(get_theme_mod('background-color-motto','#e5e8ef')) ?: '#e5e8ef',
          'text_color_motto' => sanitize_text_field(get_theme_mod('text-color-motto','#000000')) ?: '#000000',
          'set_motto' => sanitize_text_field(get_bloginfo('description')),
          'bg_color_logo' => sanitize_text_field(get_theme_mod('bg-color-logo','#fff')) ?: "#fff",
          'set_image' => $this->get_custom_logo_url(),
          'bg_color_main_menu' => sanitize_text_field(get_theme_mod('bg-color-main-menu','#333743')) ?: '#333743',
          'main_menu_img' => $main_menu_img,
          'text_color_main_menu' => sanitize_text_field(get_theme_mod('text-color-main-menu','#cedce9')) ?: '#cedce9',
        ];

        if($current_layout == 2) {
            $args['logo_img'] = $this->get_blog_logo_url();
        }
      
        return get_template_part('template-parts/template-part',$topnav,$args);
    }

    public function preload_resources(){
        $current_page = get_query_var('paged');
        global $wp_query;
        
        if($current_page == 0)
          $current_page = 1;
      
        $resource_to_preload = [
          ['type' => "font",'href' =>  SYRUS_THEME_URI.'/fonts/Montserrat.ttf']
        ];
      
        if(is_home()){
          $img_size = wp_is_mobile() ? "medium" : "large";
      
          $posts = get_posts($args = array(
            'paged' => $current_page,
            'posts_per_page' => 10,
            'ignore_sticky_posts' => 1,
            'post_type' => "post",
            'post_status' => "publish" 
          ));
      
          foreach($posts as $p){
            $img_href = get_the_post_thumbnail_url($p->ID,$img_size);
      
            if(!$img_href)
                continue;
      
            $resource_to_preload[] = ['type' => "image",'href' => get_the_post_thumbnail_url($p->ID,$img_size)];
          }
      
          $resource_to_preload[] = ['type' => "image",'href' => get_the_post_thumbnail_url($wp_query->posts[0]->ID,$img_size)];
        }
      
        if(is_single()){
          $img_size = wp_is_mobile() ? "large" : "full";
          $resource_to_preload[] = ['type' => "image",'href' => get_the_post_thumbnail_url(get_the_ID(),$img_size)];
        }
      
        if(is_category()){
          echo '<!-- PRELOAD CATEGORY -->';
        }
      
        if(is_search()){
          echo '<!-- PRELOAD SEARCH -->';
        }
      
        foreach($resource_to_preload as $res){
          echo '<link rel="preload" as="'.$res['type'].'" href="'.$res['href'].'"  crossorigin="anonymous">';
        }
    }

    public function get_theme_version() {
        $theme = wp_get_theme();

        if($theme->parent())
            $theme = $theme->parent();

        return $theme->Version;
    }

    public function is_ai_plugin_active() {
      $plugins = get_option('active_plugins',[]);
      return in_array('syrus-ai/syrus-ai.php',$plugins);
    }

    public function template_admin_tab($tab, $layout = null) {
        $path = null;

        if($tab === "layouts" && $layout) {
            $path = $this->get_template_parts_admin('layouts/customize-layout-' . $layout);
        } else {
            $path = $this->get_template_parts_admin('tabs/tab-' . $tab);
        }


        return include_once $path;
    }

    public function make_WordPress_happy() {
        add_editor_style();

        comments_template();
      
        comment_form();
      
        register_block_style();
      
        register_block_pattern();
      
        paginate_comments_links();
      
        wp_enqueue_script('comment-reply');
    }

    public function get_posts_table_info() {
        global $wpdb;
        $tablename = $wpdb->prefix . 'posts';

        $size = 0;
	      $rows = $wpdb->get_results( 'SHOW TABLE STATUS', ARRAY_A );

        foreach($rows as $row) {
            if($row['Name'] === $wpdb->prefix . 'posts') {
                $size = (int) ($row['Data_length'] + $row['Index_length']);
                break;
            }
        }

      	$rows = $wpdb->get_results( "SELECT COUNT(*) AS total FROM $tablename", ARRAY_N );
        $total_records = (int) $rows[0][0];

        return [
            'size'          => $size / 1024,
            'total_records' => $total_records,
            'record_size'   => $size / $total_records / 1024, 
        ];
    }
}
