<?php

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

class SyrusPostHandler { 

    private $request;

    public function initialize() {

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

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

    public function __call($name, $arguments) {
        $real_method = substr($name,2);

        if(!method_exists($this,$real_method))
            return null;

        unset($_POST['action']);

        $this->request = (object) $_POST;

        return call_user_func([$this,$real_method]);
    }

    public function salva_impostazioni_ads($types = ['priv']) {
        $params = $_POST;
    
        foreach($params as $key => $value){
            if(strpos($key,"codice_") !== false){
                update_option("syrus_theme_ads_".explode("codice_",$key)[1],$value);
            }
        }
    
        return wp_safe_redirect(admin_url("admin.php?page=syrus-theme-page&tab=head-footer-content"));
    }

    public function salva_robots_ads_txt($types = ['priv']) {
        $params = $_POST;

        // Mantain /r e /n
        $ads_json_string = json_encode($params['ads']);
        $robots_json_string = json_encode($params['robots']);
    
        $ads_json_string = ltrim((string) $ads_json_string,'"');
        $robots_json_string = ltrim((string) $robots_json_string,'"');
        $ads_json_string = rtrim((string) $ads_json_string,'"');
        $robots_json_string = rtrim((string) $robots_json_string,'"');
    
        update_option("syrus_theme_file_ads_txt",$ads_json_string);
        update_option("syrus_theme_file_robots_txt",$robots_json_string);
    
    
        $abilita_ads_txt = isset($params['abilita_ads_txt']) && $params['abilita_ads_txt'] == 1 ? 1 : 0;
        $abilita_robots_txt = isset($params['abilita_robots_txt']) && $params['abilita_robots_txt'] == 1 ? 1 : 0;
    
        update_option('syrus_theme_file_abilita_ads_txt',$abilita_ads_txt);
        update_option('syrus_theme_file_abilita_robots_txt',$abilita_robots_txt);
    
        return wp_safe_redirect(admin_url("admin.php?page=syrus-theme-page&tab=robots-txt-ads-txt"));
    }

    public function salva_impostazioni_generali($types = ['priv']) {
        global $syrusAssetsHandler;
        $params = $_POST;

        $js_scheme = $syrusAssetsHandler->get_js_scheme();
        $css_scheme = $syrusAssetsHandler->get_css_scheme();

        $infinite_scroll_chk = isset($params['infinite_scroll_chk']) && $params['infinite_scroll_chk'] == 1 ? 1 : 0;
        $infinite_scroll_home_chk = isset($params['infinite_scroll_home_chk']) && $params['infinite_scroll_home_chk'] == 1 ? 1 : 0;
        $span_replace_chk = isset($params['span_replace_chk']) && $params['span_replace_chk'] == 1 ? 1 : 0;
        $p_cleaner_chk = isset($params['p_cleaner_chk']) && $params['p_cleaner_chk'] == 1 ? 1 : 0;
        $http_cleaner_chk = isset($params['http_cleaner_chk']) && $params['http_cleaner_chk'] == 1 ? 1 : 0;
        $controlli_seo_chk = isset($params['controlli_seo']) && $params['controlli_seo'] != "" ? implode(',',$params['controlli_seo']) : null;
        $chatgpt_token = isset($params['chatgpt_token']) && $params['chatgpt_token'] != "" ? $params['chatgpt_token'] : "";
        $deepl_api_key = isset($params['deepl_api_key']) && $params['deepl_api_key'] != "" ? $params['deepl_api_key'] : "";
    
        update_option("syrus_theme_generali_controlli_seo",$controlli_seo_chk);
        update_option("syrus_theme_generali_infinite_scroll",$infinite_scroll_chk);
        update_option("syrus_theme_generali_infinite_scroll_home",$infinite_scroll_home_chk);
        update_option("syrus_theme_generali_span_replace",$span_replace_chk);
        update_option("syrus_theme_generali_p_cleaner",$p_cleaner_chk);
        update_option("syrus_theme_generali_http_cleaner",$http_cleaner_chk);
        update_option("syrus_theme_generali_chatgpt_token",$chatgpt_token);
        update_option("syrus_theme_generali_deepl_api_key",$deepl_api_key);

        foreach($css_scheme as $handle => $info) {
            if(!str_contains($handle, 'admin')) {
                $param = isset($params["enqueue_css_$handle"]) && $params["enqueue_css_$handle"] == 1 ? 'y' : 'n';
                update_option("syrus_theme_generali_enqueue_css_$handle",$param);
            }
        }

        foreach($js_scheme as $handle => $info) {
            if(!str_contains($handle, 'admin') && $handle != 'syrus-customizer-js') {
                $param = isset($params["enqueue_js_$handle"]) && $params["enqueue_js_$handle"] == 1 ? 'y' : 'n';
                update_option("syrus_theme_generali_enqueue_js_$handle",$param);
            }
        }
    
        return wp_safe_redirect(admin_url("admin.php?page=syrus-theme-page&tab=theme-settings"));
    }

    public function salva_impostazioni_cap_media($types = ['priv']) {
        $utenti_abilitati = $_POST['utenti'] ?: [];

        $tutti_gli_utenti = get_users();
    
    
        if(isset($_POST['reset']) && $_POST['reset'] == 1){
    
            foreach($tutti_gli_utenti as $user){
                $user_obj = new WP_User($user->ID);
                $ruolo_utente = $user->roles[0];
    
                $user_obj->add_cap("syrus_theme_upload_files");
    
                if($ruolo_utente == "administrator")
                    continue;
                
                
                $user_obj->remove_cap('syrus_theme_upload_files');
        
            }
    
            return wp_safe_redirect(admin_url("admin.php?page=syrus-theme-page&tab=rules-upload-media"));
        }
    
    
    
        foreach($tutti_gli_utenti as $user){
            $user_obj = new WP_User($user->ID);
            $ruolo_utente = $user->roles[0];
            
            
            if($ruolo_utente == "administrator"){
                $user_obj->add_cap("syrus_theme_upload_files");
                continue;
            }
    
            
            $user_obj->remove_cap('syrus_theme_upload_files');
    
            if(!in_array($user->ID,$utenti_abilitati))
                continue;
            
            $user_obj->add_cap("syrus_theme_upload_files");
        }
        
        return wp_safe_redirect(admin_url("admin.php?page=syrus-theme-page&tab=rules-upload-media"));
    }

    public function salva_impostazioni_social($types = ['priv']) {
        $params = $_POST;

        $username_twitter = isset($params['twitter_username']) && $params['twitter_username'] != "" ? $params['twitter_username'] : null;
    
        update_option("syrus_theme_social_twitter_username",$username_twitter);
        return wp_safe_redirect(admin_url("admin.php?page=syrus-theme-page&tab=social"));
    }

    public function dismiss_notice_syrus($types = ['priv']) {
        update_option('syrus_theme_notice_dismiss',1);
        return wp_safe_redirect($_SERVER['HTTP_REFERER']);
    }

    public function salva_impostazioni_layout($types = ['priv']) {
        update_option("syrus_theme_layout",$_POST['layout']);
        return wp_safe_redirect($_SERVER['HTTP_REFERER']);
    }

    public function close_comments_on_older_posts($types = ['priv']) {
        $nonce = $_REQUEST['_wpnonce'];
        $check = wp_verify_nonce($nonce, 'close_comments_on_older_posts');
        
        if(!$check)
            return wp_die(esc_html('There was an error validating the request', 'syrus'), esc_html('Validation error', 'syrus'));

        $current_date = current_datetime()->format('Y-m-d H:i:s');
        $one_month_ago = gmdate('Y-m-d H:i:s', strtotime($current_date . ' -1 month'));
    
        $query = new WP_Query([
            'posts_per_page'    => 60,
            'post_type'         => 'post',
            'post_status'       => 'publish',
            'comment_status'    => 'open',
            'date_query'        => [
                'before'    => $one_month_ago,
                'inclusive' => true,
            ]
        ]);

        if($query->have_posts()) {
            foreach($query->posts as $post) {
                $post = (array) $post;
                $post['comment_status'] = 'closed';
                wp_update_post($post);
            }
        }

        wp_reset_postdata();

        return wp_safe_redirect($_REQUEST['_wp_http_referer']);
    }

    public function remove_revisions_on_older_posts($types = ['priv']) {
        $nonce = $_REQUEST['_wpnonce'];
        $check = wp_verify_nonce($nonce, 'remove_revisions_on_older_posts');

        if(!$check)
            return wp_die(esc_html('There was an error validating the request', 'syrus'), esc_html('Validation error', 'syrus'));

        $current_date = current_datetime()->format('Y-m-d H:i:s');
        $one_month_ago = gmdate('Y-m-d H:i:s', strtotime($current_date . ' -1 month'));

        $query = new WP_Query([
            'posts_per_page'    => 60,
            'post_type'         => 'revision',
            'post_status'       => 'inherit',
            'date_query'        => [
                'before'    => $one_month_ago,
                'inclusive' => true,
            ]
        ]);

        if($query->have_posts()) {
            foreach($query->posts as $post) {
                wp_delete_post($post->ID, true);
            }
        }

        wp_reset_postdata();

        return wp_safe_redirect($_REQUEST['_wp_http_referer']);
    }

    public function remove_spam_and_pending_comments($types = ['priv']) {
        $nonce = $_REQUEST['_wpnonce'];
        $check = wp_verify_nonce($nonce, 'remove_spam_and_pending_comments');

        if(!$check)
            return wp_die(esc_html('There was an error validating the request', 'syrus'), esc_html('Validation error', 'syrus'));

        $spam_and_pending_comments = new WP_Comment_Query();
        $spam_and_pending_comments = $spam_and_pending_comments->query([
            'type'      => 'comment',
            'status'    => ['hold', 'spam'],
        ]);

        foreach($spam_and_pending_comments as $comment) {
            wp_delete_comment($comment->comment_ID, true);
        }

        return wp_safe_redirect($_REQUEST['_wp_http_referer']);
    }

    public function save_whatsapp_settings($types = ['priv']) {
        $nonce = $_REQUEST['_wpnonce'];
        $check = wp_verify_nonce($nonce, 'save_whatsapp_settings');

        if(!$check)
            return wp_die(esc_html('There was an error validating the request', 'syrus'), esc_html('Validation error', 'syrus'));

        $wa_settings = [];
        $wa_settings['thumbnail_image'] = isset($_POST['thumbnail_image']) ? $_POST['thumbnail_image'] : null;
        $wa_settings['enable_popup_mobile'] = isset($_POST['enable_popup_mobile']) ? true : false;
        $wa_settings['enable_popup_desktop'] = isset($_POST['enable_popup_desktop']) ? true : false;
        $wa_settings['sender_name'] = isset($_POST['sender_name']) ? sanitize_text_field($_POST['sender_name']) : null;
        $message_content = isset($_POST['message_content']) ? $_POST['message_content'] : null;
        $wa_settings['message_content'] = $message_content ? wp_kses($message_content, [
            'a'         => [
                'id'    => true,
                'href'  => true,
                'title' => true,
            ],
            'br'        => [],
            'strong'    => [],
            'b'         => [],
            'i'         => [],
            'u'         => [],
            'p'         => [],
            'h1'        => [],
            'h2'        => [],
            'h3'        => [],
            'h4'        => [],
            'h5'        => [],
            'h6'        => [],
        ]) : null;

        $whatsapp_number = isset($_POST['whatsapp_number']) ? $_POST['whatsapp_number'] : null;
        $whatsapp_number = $whatsapp_number ? str_replace(['+', ' '] , ['', ''], $whatsapp_number) : null;
        $wa_settings['whatsapp_number'] = $whatsapp_number;
        $wa_settings['message_delay'] = isset($_POST['message_delay']) && is_numeric($_POST['message_delay']) ? (int) ($_POST['message_delay'] * 1000) : null;
        $wa_settings['enable_popup_delay_mobile'] = isset($_POST['enable_popup_delay_mobile']) ? true : false;
        $wa_settings['popup_delay_mobile'] = $wa_settings['enable_popup_delay_mobile'] && isset($_POST['popup_delay_mobile']) && is_numeric($_POST['popup_delay_mobile']) ? (int) ($_POST['popup_delay_mobile'] * 1000) : null;


        update_option("syrus_theme_whatsapp_settings", serialize($wa_settings));
        
        return wp_safe_redirect($_REQUEST['_wp_http_referer']);
    }

}