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

        public function __construct()
        {
            add_filter('cron_schedules', array($this, 'ccpwp_cron_schedules'));
            add_action('ccpwp_coins_autosave', array($this, 'ccpwp_cron_coins_autoupdater'));
            add_action('ccpw_coins_autosave_over250', array($this, 'do_this_3_day_after'));
            add_action('ccpw_extra_data_update', array($this, 'ccpwp_cron_extra_data_autoupdater'));

        }

        /*
        |--------------------------------------------------------------------------
        | Cron status schedule(s)
        |--------------------------------------------------------------------------
         */
        public function ccpwp_cron_schedules($schedules)
        {
            // 5 minute schedule for grabing all coins
            if (!isset($schedules["5min"])) {
                $schedules["5min"] = array(
                    'interval' => 5 * 60,
                    'display' => __('Once every 5 minutes'),
                );
            }
            if (!isset($schedules["3days"])) {
                $schedules["3days"] = array(
                    'interval' => 259200,
                    'display' => __('Once every 3 days'),
                );
            }
            
            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;
        }

        function ccpwp_cron_extra_data_autoupdater() {
       
            $settings       = get_option('openexchange-api-settings', []);
            $ccpwp_response  = isset($settings['ccpw_extra_info']) ? $settings['ccpw_extra_info'] : '';

            if (!empty($ccpwp_response) || $ccpwp_response === 'on'){
          
                if (class_exists('CCPWP_cronjob')) {
                    CCPWP_cronjob::ccpw_send_data();
                }
            }
        }

        static public function ccpw_send_data() {
            $feedback_url = CCPWP_FEEDBACK_API.'wp-json/coolplugins-feedback/v1/site';
            $extra_data_details = ccpwp_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('ccpwp-install-date');
            $unique_key     = '5';  // Ensure this key is unique per plugin to prevent collisions when site URL and install date are the same across plugins
            $site_id        = $site_url . '-' . $install_date . '-' . $unique_key;
            $initial_version = get_option('ccpwp_initial_save_version');
            $initial_version = is_string($initial_version) ? sanitize_text_field($initial_version) : 'N/A';
            $plugin_version = defined('CCPWP_VERSION') ? CCPWP_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'       => 'Cryptocurrency Price Ticker Widget PRO',
                '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('ccpw_extra_data_update')) {

                wp_schedule_event(time(), 'every_30_days', 'ccpw_extra_data_update');
            }
            $response_body  = wp_remote_retrieve_body($response);
            $decoded        = json_decode($response_body, true);
        
        }
      
        /*
        |--------------------------------------------------------------------------
        | initialize cron : MUST USE ON PLUGIN ACTIVATION
        |--------------------------------------------------------------------------
         */
        public function ccpwp_cron_job_init()
        {
            $get_license = get_option('ccpw_license_registration');
            $purchased_code = isset($get_license["ccpw-purchase-code"]) ? $get_license["ccpw-purchase-code"] : '';
            $api_option = get_option("openexchange-api-settings");
            // Do not proceed further if

            if (ccpwp_check_user()) {
                if (!class_exists('CoinMarketCap')) {
                    if (!wp_next_scheduled('ccpwp_coins_autosave')) {
                        wp_schedule_event(time(), '5min', 'ccpwp_coins_autosave');
                    }
                    if (!wp_next_scheduled('ccpw_coins_autosave_over250')) {
                        wp_schedule_event(strtotime("+5 seconds"), '3days', 'ccpw_coins_autosave_over250');
                    }
                }
            }
           
        }

        
/*
|--------------------------------------------------------------------------
| Must be run through cron
|--------------------------------------------------------------------------
 */
        public function ccpwp_cron_coins_autoupdater()
        {
            if (!class_exists('CoinMarketCap')) {
                //update coins data;
                //$api_obj=new CCPWP_api_data();
                CCPWP_api_data::ccpwp_get_selected_api_data();
            }
        }
        /*
        |--------------------------------------------------------------------------
        | grabing coin weekly price data(historical)for small charts
        |--------------------------------------------------------------------------
         */
        public function do_this_3_day_after()
        {
            if (!class_exists('CoinMarketCap')) {
                $api_option = get_option("openexchange-api-settings");
                $api_type = (isset($api_option['select_api'])) ? $api_option['select_api'] : "coingecko";

                for ($page = 2; $page <= 5; $page++) {
                    CCPWP_api_data::ccpwp_get_selected_api_data($page);

                }
                sleep(60);
                for ($page = 6; $page <= 10; $page++) {
                    CCPWP_api_data::ccpwp_get_selected_api_data($page);

                }
                if ($api_type == "coinmarketcap") {
                    CCPWP_api_data::ccpwp_get_selected_api_data(11);
                    CCPWP_api_data::ccpwp_get_selected_api_data(12);

                } else if ($api_type == "both_coinmarketcap") {
                    CCPWP_api_data::ccpwp_get_selected_api_data(11);
                    CCPWP_api_data::ccpwp_get_selected_api_data(12);

                }
                $db = new ccpwp_database();
                $db->ccpwp_refresh_db();
            }
        }

    }

    $cron_init = new CCPWP_cronjob();
}
