<?php
/**
 * The System status class.
 *
 * Used to define privacy related information
 *
 *
 * @since      9.2.1
 * @package    CartBounty Pro - Save and recover abandoned carts for WooCommerce
 * @subpackage CartBounty Pro - Save and recover abandoned carts for WooCommerce/includes
 * @author     Streamline.lv
 */
class CartBounty_Pro_System_Status{

	/**
	 * The ID of this plugin.
	 *
	 * @since    9.2.1
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    9.2.1
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    9.2.1
	 * @param    string    $plugin_name       The name of this plugin.
	 * @param    string    $version    		  The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ){
		$this->plugin_name = $plugin_name;
		$this->version = $version;
	}

	/**
	 * Output system status information
	 *
	 * @since    9.2.1
	 * @return   Array
	 */
	public function get_system_status(){

		if ( check_ajax_referer( 'get_system_status', 'nonce', false ) == false ) { //If the request does not include our nonce security check, stop executing the function
	        wp_send_json_error(esc_html__( 'Looks like you are not allowed to do this.', 'woo-save-abandoned-carts' ));
	    }

		global $wpdb;
		$carts = array();
		$all_plugins = array();
		$active_recovery = array();
		$exit_intent_options = array();
		$early_capture_options = array();
		$tab_notification_options = array();
		$settings = array();
		$missing_hooks = array();
		$interval_output = 0;
		$admin = new CartBounty_Pro_Admin(CARTBOUNTY_PRO_PLUGIN_NAME_SLUG, CARTBOUNTY_PRO_VERSION_NUMBER);
		$activecampaign = new CartBounty_Pro_ActiveCampaign();
		$getresponse = new CartBounty_Pro_GetResponse();
		$mailchimp = new CartBounty_Pro_Mailchimp();
		$automation = new CartBounty_Pro_Automation();
		$webhook = new CartBounty_Pro_Webhook();
		$license = $admin->activate_license();
		$recaptcha = $admin->get_recaptcha();
		$overrides = $admin->get_template_overrides();
		$review_data = array();
		$ip_address = '';
		$active_theme = '-';
		$active_theme_data = wp_get_theme();
		$active_plugins = (array) get_option( 'active_plugins', array() ); //Check for active plugins
		$site_wide_plugins = '-';
		$main_settings = $admin->get_settings( 'settings' );
		$ei_settings = $admin->get_settings( 'exit_intent' );
		$ec_settings = $admin->get_settings( 'early_capture' );
		$tn_settings = $admin->get_settings( 'tab_notification' );
		$misc_settings = $admin->get_settings( 'misc_settings' );
		
		if( $misc_settings['recoverable_carts'] ){
			$carts[] = 'Recoverable: '. esc_html( $misc_settings['recoverable_carts'] );
		}

		if( $misc_settings['anonymous_carts'] ){
			$carts[] = 'Anonymous: '. esc_html( $misc_settings['anonymous_carts'] );
		}

		if( $misc_settings['recovered_carts'] ){
			$carts[] = 'Recovered: '. esc_html( $misc_settings['recovered_carts'] );
		}

		if( $misc_settings['times_review_declined'] ){
			$review_data[] = 'Times declined: '. esc_html( $misc_settings['times_review_declined'] );
		}

		if($admin->is_notice_submitted('review')){
			$review_data[] = 'Submitted: True';
		}

		if($activecampaign->store_connected()){
			$active_recovery[] = 'ActiveCampaign';
			$ac_automation_id = $activecampaign->get_settings( 'automation_id' );

			if($ac_automation_id){
				$active_recovery[] = 'Automation: '. esc_html( $ac_automation_id );
			}

			$excluded_settings = $this->get_excluded_data( 'activecampaign' );
			
			if( !empty( $excluded_settings ) ){
				$active_recovery[] = implode( ', ', $excluded_settings );
			}
		}

		if($getresponse->store_connected()){
			$active_recovery[] = 'GetResponse';

			$excluded_settings = $this->get_excluded_data( 'getresponse' );
			
			if( !empty( $excluded_settings ) ){
				$active_recovery[] = implode( ', ', $excluded_settings );
			}
		}

		if($mailchimp->store_connected()){
			$active_recovery[] = 'MailChimp';

			$excluded_settings = $this->get_excluded_data( 'mailchimp' );
			
			if( !empty( $excluded_settings ) ){
				$active_recovery[] = implode( ', ', $excluded_settings );
			}
		}

		if( $automation->automation_enabled( 'wordpress' ) ){
			$active_recovery[] = 'WordPress';
			$active_recovery[] = 'Total emails sent: '. esc_html( $automation->get_stats( 'wordpress', 'send' ) );
			$active_recovery[] = 'Total emails opened: '. esc_html( $automation->get_stats( 'wordpress', 'open' ) );
			$active_recovery[] = 'Total emails clicked: '. esc_html( $automation->get_stats( 'wordpress', 'click' ) );
			
			$excluded_settings = $this->get_excluded_data( 'wordpress' );
			
			if( !empty( $excluded_settings ) ){
				$active_recovery[] = implode( ', ', $excluded_settings );
			}
		}

		if( $automation->automation_enabled( 'bulkgate' ) ){
			$bulkgate_settings = get_option( 'cartbounty_pro_bulkgate_settings' );
			$active_recovery[] = 'BulkGate';
			$active_recovery[] = 'Total messages sent' .': '. esc_html( $automation->get_stats( 'bulkgate', 'send' ) );
			$active_recovery[] = 'Total messages clicked' .': '. esc_html( $automation->get_stats( 'bulkgate', 'click' ) );
			
			if( $admin->tcpa_gdpr_confirmed( 'bulkgate' ) ){
				$active_recovery[] = 'TCPA / GDPR compliance: Confirmed';
			}

			if( isset( $bulkgate_settings[ 'enable_quiet_hours' ] ) ){ //If quiet hours enabled
				$active_recovery[] = 'Quiet hours: Enabled';
			}

			$excluded_settings = $this->get_excluded_data( 'bulkgate' );
			
			if( !empty( $excluded_settings ) ){
				$active_recovery[] = implode( ', ', $excluded_settings );
			}
		}

		if( $automation->automation_enabled( 'push_notification' ) ){
			$active_recovery[] = 'Push notification';
			$active_recovery[] = 'Total notifications sent' .': '. esc_html( $automation->get_stats( 'push_notification', 'send' ) );
			$active_recovery[] = 'Total notifications failed' .': '. esc_html( $automation->get_stats( 'push_notification', 'send_failed' ) );
			$active_recovery[] = 'Total notifications clicked' .': '. esc_html( $automation->get_stats( 'push_notification', 'click' ) );
			
			$excluded_settings = $this->get_excluded_data( 'push_notification' );
			
			if( !empty( $excluded_settings ) ){
				$active_recovery[] = implode( ', ', $excluded_settings );
			}
		}

		if($webhook->api_valid()){
			$active_recovery[] = 'Webhook';

			$excluded_settings = $this->get_excluded_data( 'webhook' );
			
			if( !empty( $excluded_settings ) ){
				$active_recovery[] = implode( ', ', $excluded_settings );
			}
		}

		if( $ei_settings['status'] ){
			$exit_intent_options[] = 'Enabled';
		}

		if( $ei_settings['test_mode'] ){
			$exit_intent_options[] = 'Test mode';
		}

		if( $ei_settings['mobile_status'] ){
			$exit_intent_options[] = 'Mobile';
		}

		if( $ec_settings['status'] ){
			$early_capture_options[] = 'Enabled';
		}
		if( $ec_settings['test_mode'] ){
			$early_capture_options[] = 'Test mode';
		}

		if( $ec_settings['mandatory'] ){
			$early_capture_options[] = 'Mandatory';
		}

		if( $tn_settings['status'] ){
			$tab_notification_options[] = 'Enabled';
		}

		if( $tn_settings['test_mode'] ){
			$tab_notification_options[] = 'Test mode';
		}

		if( $tn_settings['favicon'] ){
			$tab_notification_options[] = 'Favicon enabled';
		}

		if( $main_settings['exclude_anonymous_carts'] ){
			$settings[] = 'Exclude anonymous carts';
		}

		if( $main_settings['allowed_countries'] ){
			
			if( is_array( $main_settings['allowed_countries'] ) ){
				$countries = implode( ", ", $main_settings['allowed_countries'] );
				$settings[] = 'Allowed countries' .' ('. esc_html( $countries ) .')';
			}
		}

		if( isset( $main_settings['delete_anonymous_carts'] ) ){
			$interval_output = $main_settings['delete_anonymous_carts'] . ' ('. esc_html( $admin->convert_milliseconds_to_minutes( $main_settings['delete_anonymous_carts'] ) ) . ')';
			$settings[] = 'Delete anonymous carts: ' . $interval_output;
		}

		if( isset( $main_settings['notification_frequency'] ) ){
			$interval_output = $main_settings['notification_frequency'] . ' ('. esc_html( $admin->convert_milliseconds_to_minutes( $main_settings['notification_frequency'] ) ) . ')';
			$settings[] = 'Notification frequency: ' . $interval_output;
		}

		if( $main_settings['notification_email'] ){
			$settings[] = 'Notification emails: ' . esc_html( $main_settings['notification_email'] );
		}

		if(isset($recaptcha['status'])){
			if($recaptcha['status']){
				$settings[] = 'ReCAPTCHA enabled';
			}
		}

		if( $admin->international_phone_enabled() ){
			$settings[] = 'Enable easy international phone input';
		}

		if( $admin->recover_orders_enabled() ){
			$settings[] = 'Unfinished order recovery: Enabled';
			$unfinished_order_statuses = $admin->unfinished_order_statuses();

			if( !empty( $unfinished_order_statuses ) ){
				$settings[] = 'Unfinished order statuses: ' . implode( '; ', $unfinished_order_statuses );
			}
		}

		if( $main_settings['email_consent'] ){
			$settings[] = 'Enable email consent';
		}

		if( $main_settings['phone_consent'] ){
			$settings[] = 'Enable phone number consent';
		}

		if( $main_settings['lift_email'] ){
			$settings[] = 'Lift email field';
		}

		if( $main_settings['lift_phone'] ){
			$settings[] = 'Lift phone field';
		}

		if( $main_settings['logging_status'] ){
			$settings[] = 'Enable logging';
		}

		if( !$admin->action_scheduler_enabled() ){ //If WooCommerce Action scheduler library does not exist
			
			if(wp_next_scheduled('cartbounty_pro_notification_sendout_hook') === false){
				$missing_hooks[] = 'cartbounty_pro_notification_sendout_hook';
			}

			if(wp_next_scheduled('cartbounty_pro_sync_hook') === false){
				$missing_hooks[] = 'cartbounty_pro_sync_hook';
			}

			if(wp_next_scheduled('cartbounty_pro_remove_empty_carts_hook') === false) {
				$missing_hooks[] = 'cartbounty_pro_remove_empty_carts_hook';
			}

			if(wp_next_scheduled('cartbounty_pro_delete_anonymous_carts_hook') === false) {
				$missing_hooks[] = 'cartbounty_pro_delete_anonymous_carts_hook';
			}
		}

		if( $active_theme_data ){
			$active_theme = $active_theme_data->get( 'Name' ) . ' by ' . $active_theme_data->get( 'Author' ) . ' version ' . $active_theme_data->get( 'Version' ) . ' (' . $active_theme_data->get( 'ThemeURI' ) . ')';
		}
		
		if ( is_multisite() ) {
			$active_plugins = array_merge( $active_plugins, get_site_option( 'active_sitewide_plugins', array() ) );
		}
		
		foreach ( $active_plugins as $plugin ) {
			$plugin_data    = @get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin );
			$dirname        = dirname( $plugin );

			if ( ! empty( $plugin_data['Name'] ) ) {
				// link the plugin name to the plugin url if available
				$plugin_name = $plugin_data['Name'];
				$all_plugins[] = $plugin_name . ' by ' . $plugin_data['Author'] . ' version ' . $plugin_data['Version'];
			}
		}
		
		if ( sizeof( $all_plugins ) != 0 ) {
			$site_wide_plugins = implode( ', <br/>', $all_plugins );
		}

		if( isset( $_SERVER['SERVER_ADDR'] ) ){
			$ip_address = $_SERVER['SERVER_ADDR'];

		}elseif( isset( $_SERVER['LOCAL_ADDR'] ) ){
			$ip_address = $_SERVER['LOCAL_ADDR'];
		}

		if( $ip_address == '127.0.0.1' ){ //Usually in case of a VPS being used - try to get VPS IP address
			$ip_address = gethostbyname( $_SERVER['HTTP_HOST'] );
		}

		$environment = array(
			'WordPress address (URL)' 		=> home_url(),
			'Site address (URL)' 			=> site_url(),
			'Site IP address' 				=> $ip_address,
			'WordPress version' 			=> get_bloginfo( 'version' ),
			'WordPress multisite' 			=> (is_multisite()) ? 'Yes' : '-',
			'WooCommerce version' 			=> class_exists( 'WooCommerce' ) ? esc_html( WC_VERSION ) : '-',
			'Server info' 					=> isset( $_SERVER['SERVER_SOFTWARE'] ) ? esc_html( $_SERVER['SERVER_SOFTWARE'] ) : '',
			'PHP version' 					=> phpversion(),
			'MySQL Version' 				=> $wpdb->db_version(),
			'WordPress debug mode' 			=> ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ? 'On' : '-',
			'Action scheduler' 				=> ( $admin->action_scheduler_enabled() ) ? 'On' : '-',
			'WordPress cron' 				=> !( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ) ? 'On' : '-',
			'Language' 						=> get_locale(),
			'Default server timezone' 		=> date_default_timezone_get()
		);

		$cartbounty_settings = array(
			'CartBounty Pro version' 		=> esc_html( $this->version ),
			'License key' 					=> esc_html( $license['message'] ),
			'Saved carts' 					=> ($carts) ? implode(", ", $carts) : '-',
			'Review' 						=> ($review_data) ? implode(", ", $review_data) : '-',
			'Recovery' 						=> ($active_recovery) ? implode(", ", $active_recovery) : '-',
			'Exit Intent' 					=> ($exit_intent_options) ? implode(", ", $exit_intent_options) : '-',
			'Early capture' 				=> ($early_capture_options) ? implode(", ", $early_capture_options) : '-',
			'Tab notification' 				=> ($tab_notification_options) ? implode(", ", $tab_notification_options) : '-',
			'Settings' 						=> ($settings) ? implode(", ", $settings) : '-',
			'Missing hooks' 				=> ($missing_hooks) ? implode(", ", $missing_hooks) : '-',
			'Template overrides' 			=> ($overrides) ? implode(", ", $overrides) : '-'
		);

		$output = '<table id="cartbounty-system-report-table">';
		$output .= '<tbody>
						<tr>
							<td class="section-title">### Environment ###</td>
						</tr>';
					foreach( $environment as $key => $value ){
						$output .= '
						<tr>
							<td>'. esc_html( $key ) . ':' . '</td>
							<td>'. esc_html( $value ) .'</td>
						</tr>';
					}
		$output .= '</tbody>';
		$output .= '<tbody>
						<tr>
							<td class="section-title"></td>
						</tr>
						<tr>
							<td class="section-title">### '. CARTBOUNTY_PRO_ABBREVIATION .' ###</td>
						</tr>';
					foreach( $cartbounty_settings as $key => $value ){
						$output .= '
						<tr>
							<td>'. esc_html( $key ) . ':' . '</td>
							<td>'. esc_html( $value ) .'</td>
						</tr>';
					}
		$output .= '</tbody>';
		$output .= '<tbody>
						<tr>
							<td class="section-title"></td>
						</tr>
						<tr>
							<td class="section-title">### Themes ###</td>
						</tr>
						<tr>
							<td>Active theme:</td>
							<td>'. $active_theme .'</td>
						</tr>';
		$output .= '</tbody>';
		$output .= '<tbody>
						<tr>
							<td class="section-title"></td>
						</tr>
						<tr>
							<td class="section-title">### Plugins ###</td>
						</tr>
						<tr>
							<td>Active plugins:</td>
							<td>'. $site_wide_plugins .'</td>
						</tr>
					</tbody>';
		$output .= '</table>';

		$response = array(
			'container' => $admin->output_modal_container('report'),
			'report' 	=> $output
		);

		wp_send_json_success( $response );
	}

	/**
	 * Return excluded data depending on recovery
	 *
	 * @since    9.7.5
	 * @return   array
	 * @param    string     $recovery             Recovery type e.g. ActiveCampaign, WordPress etc.
	 */
	public function get_excluded_data( $recovery ){
		$admin = new CartBounty_Pro_Admin( CARTBOUNTY_PRO_PLUGIN_NAME_SLUG, CARTBOUNTY_PRO_VERSION_NUMBER );
		$option = $admin->get_exclusion_option_name( $recovery );
		$exclusion_settings = $admin->get_exclusion_settings( $recovery, $option );
		$active_recovery = array();

		if( !empty( $exclusion_settings['enable_exclusions'] ) ){
			$active_recovery[] = 'Exclusions: Enabled';
			
			if( !empty( $exclusion_settings['excluded_products'] ) ){
				$active_recovery[] = 'Excluded products: '. implode( '; ', $exclusion_settings['excluded_products'] );
			}

			if( !empty( $exclusion_settings['exclude_product_categories'] ) ){
				$active_recovery[] = 'Excluded categories: '. implode( '; ', $exclusion_settings['exclude_product_categories'] );
			}

			if( !empty( $exclusion_settings['excluded_emails_phones'] ) ){
				$active_recovery[] = 'Excluded emails and phones: '. $exclusion_settings['excluded_emails_phones'];
			}
		}
		return $active_recovery;
	}

}