<?php
if (!defined('ABSPATH')) {
    exit();
}

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

        public function __construct() {
           
       
          // Register cron jobs
            add_filter('cron_schedules', array($this, 'twae_cron_schedules'));
            add_action('twae_extra_data_update', array($this, 'twae_cron_extra_data_autoupdater'));
            
            // Add debug action for testing
            if (defined('WP_DEBUG') && WP_DEBUG) {
                add_action('wp_ajax_twae_debug_cron', array($this, 'twae_debug_cron_status'));
            }
        }
        
        function twae_cron_extra_data_autoupdater() {
       
                if (class_exists('TWAE_cronjob')) {
                    TWAE_cronjob::twae_send_data();
                }

        }
        	static public function twae_get_user_info() {
		global $wpdb;
	
		// Server and WP environment details
		$server_info = [
			'server_software'        => isset($_SERVER['SERVER_SOFTWARE']) ? sanitize_text_field($_SERVER['SERVER_SOFTWARE']) : 'N/A',
			'mysql_version'          => $wpdb ? sanitize_text_field($wpdb->get_var("SELECT VERSION()")) : 'N/A',
			'php_version'            => sanitize_text_field(phpversion() ?: 'N/A'),
			'wp_version'             => sanitize_text_field(get_bloginfo('version') ?: 'N/A'),
			'wp_debug'               => (defined('WP_DEBUG') && WP_DEBUG) ? 'Enabled' : 'Disabled',
			'wp_memory_limit'        => sanitize_text_field(ini_get('memory_limit') ?: 'N/A'),
			'wp_max_upload_size'     => sanitize_text_field(ini_get('upload_max_filesize') ?: 'N/A'),
			'wp_permalink_structure' => sanitize_text_field(get_option('permalink_structure') ?: 'Default'),
			'wp_multisite'           => is_multisite() ? 'Enabled' : 'Disabled',
			'wp_language'            => sanitize_text_field(get_option('WPLANG') ?: get_locale()),
			'wp_prefix'              => isset($wpdb->prefix) ? sanitize_key($wpdb->prefix) : 'N/A',
		];
	
		// Theme details
		$theme = wp_get_theme();
		$theme_data = [
			'name'      => sanitize_text_field($theme->get('Name')),
			'version'   => sanitize_text_field($theme->get('Version')),
			'theme_uri' => esc_url($theme->get('ThemeURI')),
		];
	

		if (!function_exists('get_plugins')) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}
		if (!function_exists('get_plugin_data')) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}
	

		$plugin_data = [];
		$active_plugins = get_option('active_plugins', []);
	
		foreach ($active_plugins as $plugin_path) {
			$plugin_file = WP_PLUGIN_DIR . '/' . ltrim($plugin_path, '/');
	
			if (file_exists($plugin_file)) {

				$plugin_info = get_plugin_data($plugin_file, false, false);
				$plugin_url = !empty($plugin_info['PluginURI']) ? esc_url($plugin_info['PluginURI']) : (!empty($plugin_info['AuthorURI']) ? esc_url($plugin_info['AuthorURI']) : 'N/A');
				$plugin_data[] = [
					'name'       => sanitize_text_field($plugin_info['Name']),
					'version'    => sanitize_text_field($plugin_info['Version']),
					'plugin_uri' => !empty($plugin_url) ? $plugin_url : 'N/A',
				];
			}
		}
	
		return [
			'server_info'   => $server_info,
			'extra_details' => [
				'wp_theme'       => $theme_data,
				'active_plugins' => $plugin_data,
			],
		];
	}
           
       static public function twae_send_data() {
                   
            $feedback_url = TWAE_FEEDBACK_API_PRO.'wp-json/coolplugins-feedback/v1/site';

       
            
            $extra_data_details = TWAE_cronjob::twae_get_user_info();


            $server_info    = $extra_data_details['server_info'];
            $extra_details  = $extra_data_details['extra_details'];
            $site_url       = get_site_url();
            $install_date   = get_option('twae-pro-install-date');
            $uni_id         = '51';
            $site_id        = $site_url . '-' . $install_date . '-' . $uni_id;
            $initial_version = get_option('twae_pro_initial_save_version');
            $initial_version = is_string($initial_version) ? sanitize_text_field($initial_version) : 'N/A';
            $plugin_version = defined('TWAE_PRO_VERSION') ? TWAE_PRO_VERSION : 'N/A';
            $admin_email    = sanitize_email(get_option('admin_email') ?: 'N/A');
            
            $post_data = array(

                'site_id'           => md5($site_id),
                'plugin_version'    => $plugin_version,
                'plugin_name'       => 'Timeline Widget Pro For Elementor',
                'plugin_initial'    => $initial_version,
                'email'             => $admin_email,
                'site_url'          => esc_url_raw($site_url),
                'server_info'       => $server_info,
                'extra_details'     => $extra_details,
            );
            
            $response = wp_remote_post($feedback_url, array(

                'method'    => 'POST',
                'timeout'   => 30,
                'headers'   => array(
                    'Content-Type' => 'application/json',
                ),
                'body'      => wp_json_encode($post_data),
            ));

            
            if (is_wp_error($response)) {
                 return;
            }
            
            $response_body  = wp_remote_retrieve_body($response);
            $decoded        = json_decode($response_body, true);
            if (!wp_next_scheduled('twae_extra_data_update')) {
                wp_schedule_event(time(), 'every_30_days', 'twae_extra_data_update');
            }
        }
          
        /**
         * Debug cron status (only available in debug mode)
         */
        public function twae_debug_cron_status() {
            if (!current_user_can('manage_options')) {
                wp_die('Unauthorized');
            }
            
            $cron_status = array(
                'next_scheduled' => wp_next_scheduled('twae_extra_data_update'),
                'opt_in_status' => get_option('cpfm_opt_in_choice_cool-timeline'),
                'cron_jobs' => _get_cron_array(),
                'current_time' => current_time('timestamp'),
                'gmt_time' => time()
            );
            
            wp_send_json($cron_status);
        }
        
        /**
         * Cron status schedule(s).
         */
        public function twae_cron_schedules($schedules)
        {
            // 30days schedule for update information
            if (!isset($schedules['every_30_days'])) {

                $schedules['every_30_days'] = array(
                    'interval' => 30 * 24 * 60 * 60, // 2,592,000 seconds
                    'display'  => __('Once every 30 days'),
                );
            }

            return $schedules;
        }

      
    }

    $cron_init = new TWAE_cronjob();
}
