<?php

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


if(!class_exists('Atlt_Dashboard')){
    class Atlt_Dashboard{

        /**
         * Init
         * @var object
         */
        private static $init;

        private static $cpt_dashboard_data = null;
        private static $cpt_review_notice_dismissed = null;

        private static function get_cpt_dashboard_data() {
            if (self::$cpt_dashboard_data === null) {
                self::$cpt_dashboard_data = get_option('cpt_dashboard_data', array());
            }
            return self::$cpt_dashboard_data;
        }

        private static function update_cpt_dashboard_data($data) {
            self::$cpt_dashboard_data = $data;
            update_option('cpt_dashboard_data', $data, false);
        }

        private static function get_cpt_review_notice_dismissed() {
            if (self::$cpt_review_notice_dismissed === null) {
                self::$cpt_review_notice_dismissed = get_option('cpt_review_notice_dismissed', array());
            }
            return self::$cpt_review_notice_dismissed;
        }

        private static function update_cpt_review_notice_dismissed($data) {
            self::$cpt_review_notice_dismissed = $data;
            update_option('cpt_review_notice_dismissed', $data);
        }

        /**
         * Instance
         * @return object
         */
        public static function instance(){
            if(!isset(self::$init)){
                self::$init = new self();
            }
            return self::$init;
        }

        public function __construct(){
            add_action('wp_ajax_atlt_hide_review_notice', array($this, 'atlt_hide_review_notice'));
        }

        /**
         * Store options
         * @param string $plugin_name
         * @param string $prefix
         * @param array $data
         * @return void
         */
        public static function store_options($prefix='', $unique_key='', $old_data='update', array $data = array()){
            if(!empty($prefix) && isset($data['string_count']) && isset($data['character_count'])){
                $prefix = sanitize_key($prefix);
                $atlt_all_data = self::get_cpt_dashboard_data();
                
                if(isset($atlt_all_data[$prefix])){
                    $data_update = false;
                    foreach($atlt_all_data[$prefix] as $key => $translate_data){
                        if(!empty($unique_key) && isset($translate_data[$unique_key]) && 
                        sanitize_text_field($translate_data[$unique_key]) === sanitize_text_field($data[$unique_key]) && 
                        sanitize_text_field($translate_data['service_provider']) === sanitize_text_field($data['service_provider']) &&
                        sanitize_text_field($translate_data['target_language']) === sanitize_text_field($data['target_language']) &&
                        sanitize_text_field($translate_data['source_language']) === sanitize_text_field($data['source_language'])
                        ){
                            
                            if($old_data=='update'){
                                $data['string_count'] = absint($data['string_count']) + absint($translate_data['string_count']);
                                $data['character_count'] = absint($data['character_count']) + absint($translate_data['character_count']);
                                $data['time_taken'] = absint($data['time_taken']) + absint($translate_data['time_taken']);
                            }
                            
                            foreach($data as $id => $value){
                                $atlt_all_data[$prefix][$key][sanitize_key($id)] = sanitize_text_field($value);
                            }
                            $data_update = true;
                        }
                    }

                    if(!$data_update){
                        $atlt_all_data[$prefix][] = array_map('sanitize_text_field', $data);
                    }
                }else{
                    $atlt_all_data[$prefix][] = array_map('sanitize_text_field', $data);
                }

                self::update_cpt_dashboard_data($atlt_all_data);
            }
        }

        /**
         * Get translation data
         * @param string $prefix
         * @return array
         */
        public static function get_translation_data($prefix, $key_exists=array()){
            $prefix = sanitize_key($prefix);
            $atlt_all_data = self::get_cpt_dashboard_data();
            $data = array();

            if(isset($atlt_all_data[$prefix])){
                $total_string_count = 0;
                $total_character_count = 0;

                foreach($atlt_all_data[$prefix] as $key => $value){

                    $continue=false;
                    foreach($key_exists as $key_exists_key => $key_exists_value){
                        if(!isset($value[$key_exists_key]) || (isset($value[$key_exists_key]) && $value[$key_exists_key] !== $key_exists_value)){
                            $continue=true;
                            break;
                        }
                    }

                    if($continue){
                        continue;
                    }

                    $total_string_count += isset($value['string_count']) ? absint($value['string_count']) : 0;
                    $total_character_count += isset($value['character_count']) ? absint($value['character_count']) : 0;
                }

                $data = array(
                    'prefix' => $prefix,
                    'data' => array_map(function($item) {
                        return array_map('sanitize_text_field', $item);
                    }, $atlt_all_data[$prefix]),
                    'total_string_count' => $total_string_count,
                    'total_character_count' => $total_character_count,
                );
            }else{
                $data = array(
                    'prefix' => $prefix,
                    'total_string_count' => 0,
                    'total_character_count' => 0,
                );
            }

            return $data;
        }

        public static function ctp_enqueue_assets(){
            if(function_exists('wp_style_is') && !wp_style_is('atlt-review-style', 'enqueued')){
                $plugin_url = plugin_dir_url(__FILE__);
                wp_enqueue_style('atlt-review-style', esc_url($plugin_url.'assets/css/cpt-dashboard.css'), array(), '1.0.0', 'all');
                wp_enqueue_script('atlt-review-script', esc_url($plugin_url.'assets/js/cpt-dashboard.js'), array('jquery'), '1.0.0', true);
            }
        }

        public static function format_number_count($number){
            $number = absint($number);
            if ($number >= 1000000) {
                return round($number / 1000000, 1) . 'M';
            } elseif ($number >= 1000) {
                return round($number / 1000, 1) . 'K';
            }
            return $number;
        }

        /**
         * Render the dashboard footer on all admin tabs.
         */
        public static function render_footer() {
            $file_prefix  = 'admin/atlt-dashboard/views/';
            $footer_file  = ATLT_PATH . $file_prefix . 'footer.php';
            $real_footer_path   = realpath($footer_file);
            $expected_base_path = realpath(ATLT_PATH . $file_prefix);

            if (
                $real_footer_path &&
                $expected_base_path &&
                strpos($real_footer_path, $expected_base_path) === 0 &&
                file_exists($footer_file)
            ) {
                require_once $footer_file;
            }
        }

        public static function review_notice($prefix, $plugin_name, $url){
            if(self::atlt_hide_review_notice_status($prefix)){
                return;
            }
            
            $translation_data = self::get_translation_data($prefix);
            
            $total_character_count = is_array($translation_data) && isset($translation_data['total_character_count']) ? $translation_data['total_character_count'] : 0;
            
            if($total_character_count < 50000){ 
                return;
            }

            $total_character_count = self::format_number_count($total_character_count);

            add_action('admin_enqueue_scripts', array(self::class, 'ctp_enqueue_assets'));

            

            // Sanitize dynamic pieces before composing the message
            $plugin_name = sanitize_text_field($plugin_name);

            
            $message = sprintf(
                  // phpcs:ignore WordPress.WP.I18n.TextDomainMismatch
                /* translators: %d: number of seconds */  __('Thanks for using <b>%1$s</b>! You have translated <b>%2$s</b> characters so far using our plugin!<br>Please give us a quick rating, it works as a boost for us to keep working on more <a style="text-decoration: none;" href="%3$s" target="_blank" rel="noopener noreferrer"><b>Cool Plugins</b></a>!', 'cp-notice'),
                $plugin_name,
                $total_character_count,
                esc_url('https://coolplugins.net/')
            );

            $prefix = sanitize_key($prefix);
            $url = esc_url($url);
            $plugin_name = sanitize_text_field($plugin_name);

            $render_notice = function() use ($message, $prefix, $url) {
                echo wp_kses_post(self::build_review_notice_html($message, $prefix, $url));
            };

            add_action('admin_notices', $render_notice);
            add_action('atlt_display_admin_notices', $render_notice);
        }

        private static function build_review_notice_html($message, $prefix, $url){
            $html= '<div class="notice notice-info cpt-review-notice is-dismissible">';
            $html .= '<div class="cpt-review-notice-content"><p>'.$message.'</p><div class="atlt-review-notice-dismiss" data-prefix="'.esc_attr($prefix).'" data-nonce="'.esc_attr(wp_create_nonce('atlt_hide_review_notice')).'"><a href="'.esc_url($url).'" target="_blank" class="button button-primary">'.esc_html__('Rate Now!', 'automatic-translator-addon-for-loco-translate') . ' ★★★★★</a><button class="button cpt-already-reviewed">'.esc_html__('Already Reviewed', 'automatic-translator-addon-for-loco-translate').'</button><button class="button cpt-not-interested">'.esc_html__('Not Interested', 'automatic-translator-addon-for-loco-translate').'</button></div></div></div>';
            
            return $html;
        }

        public static function atlt_hide_review_notice_status($prefix){
            $review_notice_dismissed = self::get_cpt_review_notice_dismissed();
            return isset($review_notice_dismissed[$prefix]) ? $review_notice_dismissed[$prefix] : false;
        }

        public function atlt_hide_review_notice(){
            if ( ! current_user_can( 'manage_options' ) ) {
                wp_send_json_error('Unauthorized', 403);
            }
            $nonce  = isset($_POST['nonce']) ? sanitize_text_field( wp_unslash($_POST['nonce']) ) : '';
            if ( ! wp_verify_nonce( $nonce, 'atlt_hide_review_notice' ) ) {
                wp_send_json_error('Invalid nonce');
            }
            
            $prefix = isset($_POST['prefix']) ? sanitize_key( wp_unslash($_POST['prefix']) ) : '';
            if ( empty( $prefix ) ) {
                wp_send_json_error('Missing prefix', 400);
            }
            $review_notice_dismissed = self::get_cpt_review_notice_dismissed();
            $review_notice_dismissed[$prefix] = true;
            self::update_cpt_review_notice_dismissed($review_notice_dismissed);
            wp_send_json_success();
        }
    }
}
