<?php

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

class SyrusAjaxHandler { 

    function initialize() {

        $methods = get_class_methods($this);
        array_shift($methods); // Rimuovo initialize()
        array_shift($methods); // Rimuovo return_response()

        foreach($methods as $key => $method) {
            $method_obj = new ReflectionMethod($this,$method);
            $parameters = $method_obj->getParameters();
            $ajax_types = $parameters[0]->getDefaultValue();
            $method_slug = str_replace('_','-',$method);
      
            if(count($ajax_types) == 0 || in_array('priv',$ajax_types)) // Loggato
              add_action('wp_ajax_' . $method_slug,[$this,$method]);
            
            if(in_array('no_priv',$ajax_types)) // Non loggato
              add_action('wp_ajax_nopriv_' . $method_slug,[$this,$method]);
          }     
    }

    public static function return_response($params = []) {
        echo json_encode($params);
        wp_die();
    }

    public function infinite_scroll_new_post($types = ['priv','no_priv']) {
        global $syrus;
        $id_ultimo_articolo = $_POST['ultimo_articolo'];
        $id_articoli_presenti = $_POST['id_articoli']; 
      
        $ultimo_post = get_post($id_ultimo_articolo);
      
        $post = get_posts(array(
          'posts_per_page' => 1,
          'orderby' => 'date',
          'order' => "DESC",
          'exclude' => $id_articoli_presenti,
        ));
      
        if(!isset($post[0]))
          wp_send_json_error("Nessun post");
      
        $ajax_post = $post[0];
      
        global $post;
        $post = $ajax_post;
        setup_postdata($post);
      
        $path = SYRUS_THEME_PATH . "/template-parts/template-part-single-post.php";
        $html = $syrus->_includi($path,compact('ajax_post'));

        wp_send_json_success($html);
    }

    public function infinite_scroll_new_posts_in_home($types = ['priv','no_priv']) {
        global $syrus;
        $page = $_POST['page'];
        $current_page = $page + 1;
        set_query_var('paged',$current_page);
      
        $args = [
          'paged' => $current_page,
          'posts_per_page' => get_option('posts_per_page') ?: 10,
          'ignore_sticky_posts' => 1,
          'post_type' => "post",
          'post_status' => "publish",
          'is_ajax' => true,
        ];
      
        $the_query = new WP_Query( $args );
        set_query_var('the_query',$the_query);
      
        $path = SYRUS_THEME_PATH."/template-parts/template-part-home.php";
        $html = $syrus->_includi($path,compact('the_query','args'));
        $post_finiti = !$the_query->have_posts() ? true : false;
      
        wp_send_json_success(['html' => $html,'post_finiti' => $post_finiti]);
    }

    public function deepl_translate_content($types = ['priv']) {
        global $syrus, $syrusDeepL;
        
        if(!current_user_can('edit_posts')) {
            wp_send_json_error(['message' => 'Unauthorized']);
        }
        
        $content = isset($_POST['content']) ? $_POST['content'] : '';
        $source_lang = isset($_POST['source_lang']) ? sanitize_text_field($_POST['source_lang']) : null;
        $target_lang = isset($_POST['target_lang']) ? sanitize_text_field($_POST['target_lang']) : 'EN-US';
        $preserve_formatting = isset($_POST['preserve_formatting']) && $_POST['preserve_formatting'] == 1;
        
        if(empty($content)) {
            wp_send_json_error(['message' => 'Content is empty']);
        }
        
        if(!isset($syrusDeepL) || !$syrusDeepL->hasApiKey()) {
            wp_send_json_error(['message' => 'DeepL API key not configured']);
        }
        
        $options = [
            'preserve_formatting' => $preserve_formatting,
            'tag_handling' => 'html'
        ];
        
        $result = $syrusDeepL->translate($content, $target_lang, $source_lang, $options);
        
        if(isset($result['error']) && $result['error']) {
            wp_send_json_error(['message' => $result['message']]);
        }
        
        if(isset($result['success']) && $result['success']) {
            wp_send_json_success([
                'text' => $result['text'],
                'detected_source_language' => $result['detected_source_language'] ?? null
            ]);
        }
        
        wp_send_json_error(['message' => 'Translation failed']);
    }

}