<?php

class MainWP_BackUp_WordPress_Plugin {

	private $option_handle = 'mainwp_backupwp_plugin_option';
	private $option = array();
	private static $order = '';
	private static $orderby = '';
	//Singleton
	private static $instance = null;

	static function get_instance() {
		if ( null == MainWP_BackUp_WordPress_Plugin::$instance ) {
			MainWP_BackUp_WordPress_Plugin::$instance = new MainWP_BackUp_WordPress_Plugin();
		}
		return MainWP_BackUp_WordPress_Plugin::$instance;
	}

	public function __construct() {
		$this->option = get_option( $this->option_handle );
	}

	public function admin_init() {
		add_action( 'wp_ajax_mainwp_backupwp_active_plugin', array( $this, 'active_plugin' ) );
		add_action( 'wp_ajax_mainwp_backupwp_upgrade_plugin', array( $this, 'upgrade_plugin' ) );
		add_action( 'wp_ajax_mainwp_backupwp_showhide_plugin', array( $this, 'showhide_plugin' ) );
	}

	public function get_option( $key = null, $default = '' ) {
		if ( isset( $this->option[ $key ] ) ) {
			return $this->option[ $key ];
		}
		return $default;
	}

	public function set_option( $key, $value ) {
		$this->option[ $key ] = $value;
		return update_option( $this->option_handle, $this->option );
	}

	public static function gen_plugin_dashboard_tab( $websites ) {
		?>
		<div class="ui segment">
		<table id="mainwp-backupwordpress-sites-table" class="ui single line table" style="width:100%">
			<thead>
				<tr>
					<th class="no-sort collapsing check-column"><span class="ui checkbox"><input type="checkbox"></span></th>
					<th><?php _e( 'Site', 'mainwp-backupwordpress-extension' ); ?></th>
					<th class="no-sort collapsing"><i class="sign in icon"></i></th>
					<th><?php _e( 'URL', 'mainwp-backupwordpress-extension' ); ?></th>
					<th><?php _e( 'Version', 'mainwp-backupwordpress-extension' ); ?></th>
					<th><?php _e( 'Hidden', 'mainwp-backupwordpress-extension' ); ?></th>
					<th><?php _e( 'Settings', 'mainwp-backupwordpress-extension' ); ?></th>
					<th class="no-sort collapsing"><?php _e( '', 'mainwp-backupwordpress-extension' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php
				if ( is_array( $websites ) && count( $websites ) > 0 ) {
					self::get_plugin_dashboard_table_row( $websites );
				}
				?>
			</tbody>
			<tfoot>
				<tr>
					<th class="no-sort collapsing check-column"><span class="ui checkbox"><input type="checkbox"></span></th>
					<th><?php _e( 'Site', 'mainwp-backupwordpress-extension' ); ?></th>
					<th class="no-sort collapsing"><i class="sign in icon"></i></th>
					<th><?php _e( 'URL', 'mainwp-backupwordpress-extension' ); ?></th>
					<th><?php _e( 'Version', 'mainwp-backupwordpress-extension' ); ?></th>
					<th><?php _e( 'Hidden', 'mainwp-backupwordpress-extension' ); ?></th>
					<th><?php _e( 'Settings', 'mainwp-backupwordpress-extension' ); ?></th>
					<th class="no-sort collapsing"><?php _e( '', 'mainwp-backupwordpress-extension' ); ?></th>
				</tr>
			</tfoot>
		</table>
	</div>
		<script type="text/javascript">
		jQuery( '#mainwp-backupwordpress-sites-table' ).DataTable( {
			"stateSave": true,
			"stateDuration": 0, // forever
			"scrollX": true,
			"colReorder" : {
				fixedColumnsLeft: 1,
				fixedColumnsRight: 1
			},
			"lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ],
			"columnDefs": [ { "targets": 'no-sort', "orderable": false } ],
			"order": [ [ 1, "asc" ] ],
			"language": { "emptyTable": "No websites were found with the BackUpWordPress plugin installed." },
			"drawCallback": function( settings ) {
				jQuery('#mainwp-backupwordpress-sites-table .ui.checkbox').checkbox();
				jQuery( '#mainwp-backupwordpress-sites-table .ui.dropdown').dropdown();
				jQuery( '.mwp_backupwp_showhide_plugin' ).on('click', function () {
					mainwp_backupwp_plugin_showhide_start_specific( jQuery( this ), false );
					return false;
				} );
			},
		} );
		</script>
		<?php
	}

	public static function get_plugin_dashboard_table_row( $websites ) {
		$plugin_name = 'BackUpWordPress';
		$location = 'tools.php?page=backupwordpress';
		$globalPremium = get_option( 'mainwp_backupwp_general_is_premium', 0 );

		foreach ( $websites as $website ) {
			$website_id = intval($website['id']);

			$class_active = ( isset( $website['backupwp_active'] ) && ! empty( $website['backupwp_active'] ) ) ? '' : 'negative';
			$class_update = ( isset( $website['backupwp_upgrade'] ) ) ? 'warning' : '';
			$class_update = ( 'negative' == $class_active) ? 'negative' : $class_update;

			$version = '';
			$plugin_slug = $website['plugin_slug'];

			if ( isset( $website['backupwp_upgrade'] ) ) {
				if ( isset( $website['backupwp_upgrade']['new_version'] ) ) {
					$version = $website['backupwp_upgrade']['new_version'];
				}
				if ( isset( $website['backupwp_upgrade']['plugin'] ) ) {
					$plugin_slug = $website['backupwp_upgrade']['plugin'];
				}
			}
			$plugin_slug = esc_html( $plugin_slug );

			//echo var_dump( $website );
			?>
			<tr class="<?php echo $class_active . ' ' . $class_update; ?>" website-id="<?php echo $website_id; ?>" plugin-name="<?php echo $plugin_name; ?>" plugin-slug="<?php echo $plugin_slug; ?>" version="<?php echo ( isset( $website['backupwp_plugin_version'] ) ) ? esc_html( $website['backupwp_plugin_version'] ) : 'N/A'; ?>">
				<td class="check-column"><span class="ui checkbox"><input type="checkbox" name="checked[]"></span></td>
				<td class="website-name"><a href="admin.php?page=managesites&dashboard=<?php echo $website_id; ?>"><?php echo stripslashes( $website['name'] ); ?></a></td>
				<td><a target="_blank" href="admin.php?page=SiteOpen&newWindow=yes&websiteid=<?php echo $website_id; ?>"><i class="sign in icon"></i></a></td>
				<td><a href="<?php echo $website['url']; ?>" target="_blank"><?php echo $website['url']; ?></a></td>
				<td><span class="updating"></span> <?php echo ( isset( $website['backupwp_upgrade'] ) ) ? '<i class="exclamation circle icon"></i>' : ''; ?> <?php echo ( isset( $website['backupwp_plugin_version'] ) ) ? esc_html( $website['backupwp_plugin_version'] ) : 'N/A'; ?></td>
				<td><span class="visibility"></span> <span class="wp-backupwp-visibility"><?php echo ( 1 == $website['hide_backupwp'] ) ? __( 'Yes', 'mainwp-backupwordpress-extension' ) : __( 'No', 'mainwp-backupwordpress-extension' ); ?></span></td>
				<td><?php echo ( $website['isOverride'] ? __( 'Individual', 'mainwp-backupwordpress-extension' ) : __( 'General', 'mainwp-backupwordpress-extension' ) ); ?></td>
				<td>
					<div class="ui right pointing dropdown icon mini basic green button" style="z-index:999">
						<a href="javascript:void(0)"><i class="ellipsis horizontal icon"></i></a>
						<div class="menu">
							<a class="item" href="admin.php?page=managesites&dashboard=<?php echo $website_id; ?>"><?php _e( 'Overview', 'mainwp-backupwordpress-extension' ); ?></a>
							<a class="item" href="admin.php?page=managesites&id=<?php echo $website_id; ?>"><?php _e( 'Edit', 'mainwp-backupwordpress-extension' ); ?></a>
							<a class="item" href="admin.php?page=SiteOpen&newWindow=yes&websiteid=<?php echo $website_id; ?>&location=<?php echo base64_encode( $location ); ?>" target="_blank"><?php _e( 'Open BackUpWordPress', 'mainwp-backupwordpress-extension' ); ?></a>
							<?php if ( 1 == $website['hide_backupwp'] ) : ?>
							<a class="item mwp_backupwp_showhide_plugin" href="#" showhide="show"><?php _e( 'Unhide Plugin', 'mainwp-backupwordpress-extension' ); ?></a>
							<?php else : ?>
							<a class="item mwp_backupwp_showhide_plugin" href="#" showhide="hide"><?php _e( 'Hide Plugin', 'mainwp-backupwordpress-extension' ); ?></a>
							<?php endif; ?>
							<?php if ( isset( $website['backupwp_active'] ) && empty( $website['backupwp_active'] ) ) : ?>
							<a class="item mwp_backupwp_active_plugin" href="#"><?php _e( 'Activate Plugin', 'mainwp-backupwordpress-extension' ); ?></a>
							<?php else : ?>
							<a class="item" href="admin.php?page=ManageSitesBackUpWordPress&id=<?php echo $website_id; ?>"><?php _e( 'Backup Now', 'mainwp-backupwordpress-extension' ); ?></a>
							<?php endif; ?>
							<?php if ( isset( $website['backupwp_upgrade'] ) ) : ?>
							<a class="item mwp_backupwp_upgrade_plugin" href="#"><?php _e( 'Update Plugin', 'mainwp-backupwordpress-extension' ); ?></a>
							<?php endif; ?>
						</div>
					</div>
        </td>
      </tr>
			<?php
		}
	}

	public function get_backupwp_websites() {
		global $mainWPBackUpWordPressExtensionActivator;
		$websites = apply_filters( 'mainwp-getsites', $mainWPBackUpWordPressExtensionActivator->get_child_file(), $mainWPBackUpWordPressExtensionActivator->get_child_key(), null );
		$sites_ids = array();
		if ( is_array( $websites ) ) {
			foreach ( $websites as $site ) {
				$sites_ids[] = $site['id'];
			}
			unset( $websites );
		}
		$option = array(
			'plugin_upgrades' => true,
			'plugins' => true,
		);
		$dbwebsites = apply_filters( 'mainwp-getdbsites', $mainWPBackUpWordPressExtensionActivator->get_child_file(), $mainWPBackUpWordPressExtensionActivator->get_child_key(), $sites_ids, array(), $option );
		$backupDataSites = array();
		if ( count( $sites_ids ) > 0 ) {
			$backupDataSites = MainWP_BackUp_WordPress_DB::get_instance()->get_backupwps_data( $sites_ids );
		}
		return MainWP_BackUp_WordPress_Plugin::get_instance()->get_websites_with_backupwp_data( $dbwebsites, $backupDataSites );
	}

	public function get_websites_with_backupwp_data( $websites, $plugin_data_sites = array() ) {
		$sites_updraft = array();
		if ( is_array( $websites ) ) {
			foreach ( $websites as $website ) {
				if ( $website && $website->plugins != '' ) {
					$plugins = json_decode( $website->plugins, 1 );
					if ( is_array( $plugins ) && count( $plugins ) != 0 ) {
						foreach ( $plugins as $plugin ) {
							if ( ('backupwordpress/backupwordpress.php' == $plugin['slug']) ) {
								$site = MainWP_BackUp_WordPress_Utility::map_site( $website, array( 'id' ) );
								if ( ! $plugin['active'] ) {
									continue; }

								$data = array( 'id' => $website->id );
								$plugintDS = isset( $plugin_data_sites[ $site['id'] ] ) ? $plugin_data_sites[ $site['id'] ] : array();
								if ( ! is_array( $plugintDS ) ) {
									$plugintDS = array(); }
								$data['lastbackup_gmttime'] = isset( $plugintDS['lastbackup_gmttime'] ) ? $plugintDS['lastbackup_gmttime'] : 0;
								$data['isOverride'] = isset( $plugintDS['override'] ) ? $plugintDS['override'] : 0;
								//$data['mwp_backupwp_is_premium'] = isset($plugintDS['mwp_backupwp_is_premium']) ? $plugintDS['mwp_backupwp_is_premium'] : "";
								$sites_updraft[ $website->id ] = $data;
								break;
							}
						}
					}
				}
			}
		}

		return $sites_updraft;
	}

	public function get_websites_with_the_plugin( $websites, $selected_group = 0, $plugin_data_sites = array() ) {
		$websites_backupwp = array();

		$pluginHide = $this->get_option( 'hide_the_plugin' );

		if ( ! is_array( $pluginHide ) ) {
			$pluginHide = array(); }
		$_text = __( 'Nothing currently scheduled', 'mainwp-backupwordpress-extension' );
		if ( is_array( $websites ) && count( $websites ) ) {
			if ( empty( $selected_group ) ) {
				foreach ( $websites as $website ) {
					if ( $website && $website->plugins != '' ) {
						$plugins = json_decode( $website->plugins, 1 );
						if ( is_array( $plugins ) && count( $plugins ) != 0 ) {
							foreach ( $plugins as $plugin ) {
								if ( ('backupwordpress/backupwordpress.php' == $plugin['slug']) ) {
									$site = MainWP_BackUp_WordPress_Utility::map_site( $website, array( 'id', 'name', 'url' ) );
									if ( $plugin['active'] ) {
										$site['backupwp_active'] = 1; } else {
										$site['backupwp_active'] = 0; }
										// get upgrade info
										$site['backupwp_plugin_version'] = $plugin['version'];
										$site['plugin_slug'] = $plugin['slug'];
										$plugin_upgrades = json_decode( $website->plugin_upgrades, 1 );
										if ( is_array( $plugin_upgrades ) && count( $plugin_upgrades ) > 0 ) {
											if ( isset( $plugin_upgrades['backupwordpress/backupwordpress.php'] ) ) {
												$upgrade = $plugin_upgrades['backupwordpress/backupwordpress.php'];
												if ( isset( $upgrade['update'] ) ) {
													$site['backupwp_upgrade'] = $upgrade['update'];
												}
											}
										}

										$site['hide_backupwp'] = 0;
										if ( isset( $pluginHide[ $website->id ] ) && $pluginHide[ $website->id ] ) {
											$site['hide_backupwp'] = 1;
										}

										$plugintDS = isset( $plugin_data_sites[ $site['id'] ] ) ? $plugin_data_sites[ $site['id'] ] : array();
										if ( ! is_array( $plugintDS ) ) {
											$plugintDS = array(); }

										//$site['isPremium'] = isset($plugintDS['is_premium']) ? $plugintDS['is_premium'] : 0;
										$site['isOverride'] = isset( $plugintDS['override'] ) ? $plugintDS['override'] : 0;
										$websites_backupwp[] = $site;
										break;
								}
							}
						}
					}
				}
			} else {
				global $mainWPBackUpWordPressExtensionActivator;

				$group_websites = apply_filters( 'mainwp-getdbsites', $mainWPBackUpWordPressExtensionActivator->get_child_file(), $mainWPBackUpWordPressExtensionActivator->get_child_key(), array(), array( $selected_group ) );
				$sites = array();
				foreach ( $group_websites as $site ) {
					$sites[] = $site->id;
				}
				foreach ( $websites as $website ) {
					if ( $website && $website->plugins != '' && in_array( $website->id, $sites ) ) {
						$plugins = json_decode( $website->plugins, 1 );
						if ( is_array( $plugins ) && count( $plugins ) != 0 ) {
							foreach ( $plugins as $plugin ) {
								if ( ('backupwordpress/backupwordpress.php' == $plugin['slug']) ) {
									$site = MainWP_BackUp_WordPress_Utility::map_site( $website, array( 'id', 'name', 'url' ) );
									if ( $plugin['active'] ) {
										$site['backupwp_active'] = 1; } else {
										$site['backupwp_active'] = 0; }
										$site['backupwp_plugin_version'] = $plugin['version'];
										// get upgrade info
										$plugin_upgrades = json_decode( $website->plugin_upgrades, 1 );
										if ( is_array( $plugin_upgrades ) && count( $plugin_upgrades ) > 0 ) {
											if ( isset( $plugin_upgrades['backupwordpress/backupwordpress.php'] ) ) {
												$upgrade = $plugin_upgrades['backupwordpress/backupwordpress.php'];
												if ( isset( $upgrade['update'] ) ) {
													$site['backupwp_upgrade'] = $upgrade['update'];
												}
											}
										}
										$site['hide_backupwp'] = 0;
										if ( isset( $pluginHide[ $website->id ] ) && $pluginHide[ $website->id ] ) {
											$site['hide_backupwp'] = 1;
										}

										$plugintDS = isset( $plugin_data_sites[ $site['id'] ] ) ? $plugin_data_sites[ $site['id'] ] : array();
										if ( ! is_array( $plugintDS ) ) {
											$plugintDS = array(); }

										//$site['isPremium'] = $plugintDS['is_premium'];
										$site['isOverride'] = $plugintDS['override'];
										$websites_backupwp[] = $site;
										break;
								}
							}
						}
					}
				}
			}
		}

		// if search action
		$search_sites = array();
		if ( isset( $_GET['s'] ) && ! empty( $_GET['s'] ) ) {
			$find = trim( $_GET['s'] );
			foreach ( $websites_backupwp as $website ) {
				if ( stripos( $website['name'], $find ) !== false || stripos( $website['url'], $find ) !== false ) {
					$search_sites[] = $website;
				}
			}
			$websites_backupwp = $search_sites;
		}
		unset( $search_sites );

		return $websites_backupwp;
	}

	public static function gen_actions_row() {
		?>
		<div class="mainwp-actions-bar">
			<div class="ui grid">
				<div class="ui two column row">
					<div class="ui mini form column">
						<select class="ui dropdown" id="mwp_backupwp_plugin_action">
							<option value="-1"><?php _e( 'Bulk Actions', 'mainwp-backupwordpress-extension' ); ?></option>
							<option value="activate-selected"><?php _e( 'Activate', 'mainwp-backupwordpress-extension' ); ?></option>
							<option value="update-selected"><?php _e( 'Update', 'mainwp-backupwordpress-extension' ); ?></option>
							<option value="hide-selected"><?php _e( 'Hide', 'mainwp-backupwordpress-extension' ); ?></option>
							<option value="show-selected"><?php _e( 'Unhide', 'mainwp-backupwordpress-extension' ); ?></option>
            </select>
						<input type="button" value="<?php _e( 'Apply' ); ?>" class="ui basic mini button action" id="backupwp_plugin_doaction_btn" name="backupwp_plugin_doaction_btn">
						<?php do_action( 'ithemes_backupwp_actions_bar_right' ); ?>
	        </div>
					<div class="right aligned column">
						<?php do_action( 'ithemes_backupwp_actions_bar_right' ); ?>
	        </div>
        </div>
			</div>
		</div>
		<?php
	}

	public function active_plugin() {
		$_POST['websiteId'] = $_POST['backupwpRequestSiteID'];
		do_action( 'mainwp_activePlugin' );
		die();
	}

	public function upgrade_plugin() {
		$_POST['websiteId'] = $_POST['backupwpRequestSiteID'];
		do_action( 'mainwp_upgradePluginTheme' );
		die();
	}

	public function showhide_plugin() {
		$siteid = isset( $_POST['backupwpRequestSiteID'] ) ? $_POST['backupwpRequestSiteID'] : null;
		$showhide = isset( $_POST['showhide'] ) ? $_POST['showhide'] : null;
		if ( null !== $siteid && null !== $showhide ) {
			global $mainWPBackUpWordPressExtensionActivator;
			$post_data = array(
			'mwp_action' => 'set_showhide',
				'showhide' => $showhide,
			);
			$information = apply_filters( 'mainwp_fetchurlauthed', $mainWPBackUpWordPressExtensionActivator->get_child_file(), $mainWPBackUpWordPressExtensionActivator->get_child_key(), $siteid, 'backup_wp', $post_data );

			if ( is_array( $information ) && isset( $information['result'] ) && 'SUCCESS' === $information['result'] ) {
				$hide_backupwp = $this->get_option( 'hide_the_plugin' );
				if ( ! is_array( $hide_backupwp ) ) {
					$hide_backupwp = array(); }
				$hide_backupwp[ $siteid ] = ('hide' === $showhide) ? 1 : 0;
				$this->set_option( 'hide_the_plugin', $hide_backupwp );
			}
			die( json_encode( $information ) );
		}
		die();
	}
}
