<?php
#require_once '../rover-shared.php';
#require_once '../rover-common.php';
#require_once '../rover-database.php';

require_once 'rover-admin-callbacks.php';
require_once 'rover-dashboard.php';
require_once 'rover-panel-setup.php';
require_once 'rover-panel-styling.php';
require_once 'rover-panel-lead-generation.php';
require_once 'rover-panel-seo.php';
require_once 'rover-panel-migrate-ds.php';
require_once 'rover-panel-social.php';

class Rover_IDX_ADMINBASE
	{
	private Rover_IDX $rover_idx;

	public function __construct(Rover_IDX $rover_idx)
		{
		$this->rover_idx										= $rover_idx;

		$this->admin_init();

		$callbacks												= new Rover_IDX_ADMINCALLBACKS($this->rover_idx);
		}

	public function admin_init()	{

#		$this->rover_idx->COMMON->error_log(__FILE__, __FUNCTION__, __LINE__,		'this is the admin panel');

		if (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], 'customize.php') !== false)
			return false;

		add_action('admin_menu',								[ $this, 'admin_menu' ] );
		add_action('admin_enqueue_scripts', 					[ ( $this->rover_idx->COMMON ), 'css_and_js_admin' ], 99 );
#		add_action('enqueue_block_editor_assets', 				[ ( $this->rover_idx->COMMON ), 'load_blocks' ] );

		#	The 'block_categories' filter has been deprecated in WordPress 5.8 and replaced by 'block_categories_all'.
		if ( version_compare( $GLOBALS['wp_version'], '5.8-alpha-1', '<' ) )
			add_filter( 'block_categories',						[ $this, 'add_block_categories' ] );
		else
			add_filter( 'block_categories_all',					[ $this, 'add_block_categories' ] );

		add_action('update_option_permalink_structure',			[ $this, 'update_permalink' ] );

		add_filter('plugin_action_links',						[ $this, 'roveridx_plugin_action_links' ], 10, 2 );

		add_action( 'wp_dashboard_setup', 						[ $this, 'dashboard_active_summary' ] );
		add_action( 'wp_dashboard_setup', 						[ $this, 'dashboard_visitor_activity' ] );
		add_action( 'wp_dashboard_setup', 						[ $this, 'dashboard_mail' ] );

		add_action( 'wp_ajax_rover_idx_block_refresh',			[ $this, 'block_shortcode_refresh_callback' ] );

		add_filter( 'admin_body_class', 						[ $this, 'admin_body_class' ] );

		register_setting( 'roveridx_region_options', 			roverOPTIONS::REGIONS, [ $this, 'validate_options' ] );
		register_setting( 'roveridx_theming_options',			roverOPTIONS::THEME );
		register_setting( 'roveridx_seo_options',				roverOPTIONS::SEO );
		register_setting( 'roveridx_social_options',			roverOPTIONS::SOCIAL );

		add_action( 'upgrader_process_complete',				[ $this,	'idx_upgrade_completed'], 10, 2);

		if (count($this->rover_idx->all_selected_regions) == 0)
			add_action('admin_notices',							[ $this, 'admin_notice_no_region_set' ] );

		add_action('admin_notices',								[ $this, 'admin_notice_permalink_unsupported' ] );
		add_action('admin_notices',								[ $this, 'admin_notice_plugin_upgraded'] );

		add_action('admin_notices',								[ $this, 'admin_notice_hosting_cache_notice'] );
		add_action('wp_ajax_rover_dismiss_hosting_notice',		[ $this, 'admin_notice_dismiss_hosting_notice'] );

		if ($this->has_unmigrated_diverse_solutions('notice'))
			add_action('admin_notices',							[ $this, 'admin_notice_diverse_solutions_migration' ] );


#		https://andidittrich.com/2015/05/howto-upgrade-notice-for-wordpress-plugins.html
#
#		add_action('in_plugin_update_message-rover-idx/roveridx.php', function( $currentPluginMetadata, $newPluginMetadata ) {
#
#			if (isset($newPluginMetadata->upgrade_notice) && strlen(trim($newPluginMetadata->upgrade_notice)) > 0){
#				echo '<p style="background-color: #d54e21; padding: 10px; color: #f9f9f9; margin-top: 10px"><strong>Important Upgrade Notice:</strong> ';
#				echo esc_html($newPluginMetadata->upgrade_notice), '</p>';
#				}
#			}, 10, 2);

#		require_once '../widgets/_init.php';
		$widgets												= new Rover_IDX_Widgets($this->rover_idx);
		$widgets->init_widgets();
		}

	public function admin_menu() {

		add_menu_page(
				'Rover IDX Real Estate Solution - Management Page',
				'Rover IDX',
				'manage_options',
				roverKEYS::IDX_PLUGIN_NAME,
				function() {
					$Rover_IDX_ADMINSETUP						= new Rover_IDX_ADMINSETUP($this->rover_idx);

					$Rover_IDX_ADMINSETUP->roveridx_panel_setup_form();
					},
				ROVER_IDX_PLUGIN_URL.'/images/roverLogo16.png',
				$position = null
				);
		add_submenu_page(
				roverKEYS::IDX_PLUGIN_NAME,						#	$parent_slug,
				'Rover IDX Look and Feel',						#	$page_title,
				'Customize',									#	$menu_title,
				'edit_posts',									#	$capability,
				roverKEYS::IDX_PLUGIN_NAME.'-customize',		#	$menu_slug,
				function() {
					$Rover_IDX_ADMINCUSTOMIZE					= new Rover_IDX_ADMINCUSTOMIZE($this->rover_idx);

					$Rover_IDX_ADMINCUSTOMIZE->roveridx_panel_styling_form();
					},
				);
		add_submenu_page(
				roverKEYS::IDX_PLUGIN_NAME,						#	$parent_slug,
				'Rover IDX Lead Panel',							#	$page_title,
				'Lead Generation',								#	$menu_title,
				'manage_options',								#	$capability,
				roverKEYS::IDX_PLUGIN_NAME.'-lead-generation',	#	$menu_slug,
				function() {
					$Rover_IDX_ADMINLEADGEN						= new Rover_IDX_ADMINLEADGEN($this->rover_idx);

					$Rover_IDX_ADMINLEADGEN->roveridx_panel_lead_form();
					}
				);
		add_submenu_page(
				roverKEYS::IDX_PLUGIN_NAME,						#	$parent_slug,
				'Rover IDX SEO Panel',							#	$page_title,
				'SEO',											#	$menu_title,
				'manage_options',								#	$capability,
				roverKEYS::IDX_PLUGIN_NAME.'-seo',				#	$menu_slug,
				function() {
					$Rover_IDX_ADMINSEO							= new Rover_IDX_ADMINSEO($this->rover_idx);

					$Rover_IDX_ADMINSEO->roveridx_panel_seo_form();
					}
				);
		add_submenu_page(
				roverKEYS::IDX_PLUGIN_NAME,						#	$parent_slug,
				'Rover IDX Social Panel',						#	$page_title,
				'Social',										#	$menu_title,
				'edit_posts',									#	$capability,
				roverKEYS::IDX_PLUGIN_NAME.'-social',			#	$menu_slug,
				function() {
					$Rover_IDX_ADMINSOCIAL						= new Rover_IDX_ADMINSOCIAL($this->rover_idx);

					$Rover_IDX_ADMINSOCIAL->roveridx_social_panel_form();
					}
				);

		if ($this->has_unmigrated_diverse_solutions('menu'))
			{
			add_submenu_page(
				roverKEYS::IDX_PLUGIN_NAME,						#	$parent_slug,
				'Rover IDX Migrate Diverse Solutions',			#	$page_title,
				'Migrate DS',									#	$menu_title,
				'edit_posts',									#	$capability,
				roverKEYS::IDX_PLUGIN_NAME.'-migrate-ds',		#	$menu_slug,
				'roveridx_migrate_ds_panel_form'
				);
			}

		global $submenu;
		if ( isset( $submenu[roverKEYS::IDX_PLUGIN_NAME] ) )
			$submenu[roverKEYS::IDX_PLUGIN_NAME][0][0] = __( 'General', roverKEYS::IDX_PLUGIN_NAME );
		}

	public function idx_upgrade_completed($upgrader_object, $options)	{

		$our_plugin					= plugin_basename( __FILE__ );

		if(
			$options['action'] == 'update' &&
			$options['type'] == 'plugin' &&
			isset($options['plugins'])
			)
			{
			#	Iterate through the plugins being updated and check if ours is there
			foreach( $options['plugins'] as $plugin ) {
				if ($plugin == $our_plugin) {
					#	Set a transient to record that our plugin has just been updated
					set_transient( 'idx_plugin_updated', 1 );
					}
				}
			}
		}

	public function admin_notice_permalink_unsupported()	{

		$ps				= get_option('permalink_structure');
		if (empty($ps))
			{
			$class		= 'notice notice-warning rover-notice is-dismissible';
			$message	= 'Rover IDX does not support the \"?p=123\" WP Permalink structure.  Please choose a different permalink setting so Rover Dynamic Pages display correctly.';

			printf( '<div class="%1$s"><p>%2$s</p></div>', $class, $message );
			}

		}

	public function admin_notice_plugin_upgraded() {

		if( get_transient( 'idx_plugin_updated' ) ) {
			echo '<div class="notice notice-success">' . __( 'Thanks for updating', 'wp-upe' ) . '</div>';
			delete_transient( 'idx_plugin_updated' );

			#	Plugin has been upgraded.  Convert dynamic (on-the-fly) Login / Register
			#	menu generation into actual menu items in the actual meny
			if (!isset($this->roveridx_theming['menu_has_been_added']))
				{
				require_once '../rover-menus.php';

				$menus								= new Rover_IDX_Menus($this->rover_idx);
				return $menus->add_login_menu_from_v3_settings();
				}
			}
		}

	public function admin_notice_hosting_cache_notice()	{

		#	Only show on relevant admin pages
		$screen					= get_current_screen();
		if (!$screen || !in_array($screen->id, ['dashboard', 'toplevel_page_rover-idx'], true)) {
			return;
			}

		#	Only show to admins
		if (!current_user_can('manage_options')) {
			return;
			}

		#	Detect hosting
		$host					= false;
		if (function_exists('is_wpe') || defined('WPE_APIKEY') || class_exists('WpeCommon')) {
			$host				= 'wpengine';
			}
		else if (defined('KINSTA_CACHE_ZONE') || defined('KINSTAMU_VERSION') || class_exists('Kinsta\Cache')) {
			$host				= 'kinsta';
			}
		else if (defined('FLYWHEEL_CONFIG_DIR') || (isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'Flywheel') !== false)) {
			$host				= 'flywheel';
			}
		else if (isset($_SERVER['cw_allowed_ip']) || file_exists('/home/master/applications')) {
			$host				= 'cloudways';
			}
		else if (defined('WPCOMSH_VERSION') || defined('AT_STARTER_PLAN') || (isset($_SERVER['HTTP_X_WPCOM_REQUEST']) && !empty($_SERVER['HTTP_X_WPCOM_REQUEST']))) {
			$host				= 'wordpresscom';
			}

		if (!$host) {
			return;
			}

		#	Check if dismissed
		$dismissed				= get_option('rover_hosting_cache_notices_dismissed', []);
		if (!empty($dismissed[$host])) {
			return;
			}

		#	Paths to exclude
		$paths					= [
								'/rover-control-panel',
								'/rover-login-panel',
								'/rover-custom-listing-panel',
								];
		$paths_formatted		= implode("\n\t", array_map(function($p) { return "- Path: {$p}*"; }, $paths));

		#	Host configurations
		$hosts					= [
								'wpengine'			=> [
													'name'			=> 'WP Engine',
													'support_url'	=> 'https://my.wpengine.com/support',
													'self_service'	=> false,
													],
								'kinsta'			=> [
													'name'			=> 'Kinsta',
													'support_url'	=> 'https://my.kinsta.com/',
													'self_service'	=> false,
													],
								'flywheel'			=> [
													'name'			=> 'Flywheel',
													'support_url'	=> 'https://app.getflywheel.com/',
													'self_service'	=> false,
													],
								'cloudways'			=> [
													'name'			=> 'Cloudways',
													'support_url'	=> 'https://platform.cloudways.com/',
													'self_service'	=> true,
													],
								'wordpresscom'		=> [
													'name'			=> 'WordPress.com',
													'support_url'	=> 'https://wordpress.com/help/contact',
													'self_service'	=> false,
													],
								];

		$config				= $hosts[$host];
		$nonce				= wp_create_nonce('rover_dismiss_hosting_notice');

		#	Support message for hosts requiring contact
		$support_message	= "Hi,

We're using the Rover IDX plugin which includes dynamic panels that should not be cached.

Could you please add cache exclusions for:

	{$paths_formatted}

Thank you!";

		#	Self-service instructions for Cloudways
		$cloudways_instructions = "To exclude Rover IDX panels from Varnish cache:

	1. Log in to your Cloudways Platform
	2. Go to Applications - Select your application
	3. Click 'Application Settings' - 'Varnish Settings'
	4. Click 'Add New Exclusion' for each path:
	- Type: URL | Value: /rover-control-panel*
	- Type: URL | Value: /rover-login-panel*
	- Type: URL | Value: /rover-custom-listing-panel*
	5. Save your changes

	The exclusions should take effect within a few minutes.";

		?>
		<div class="notice notice-warning is-dismissible" id="rover-hosting-notice">
			<h3 style="margin-top: 0.5em;">
				Rover IDX: <?php echo esc_html($config['name']); ?> Cache Configuration Required
			</h3>

			<p>
				Your site is hosted on <strong><?php echo esc_html($config['name']); ?></strong>, which uses
				server-level caching. Rover IDX panels require dynamic content and must be excluded
				from cache to function properly.
			</p>

			<?php if ($config['self_service']) : ?>
				<details style="margin: 1em 0; padding: 1em; background: #f9f9f9; border-left: 4px solid #dba617;">
					<summary style="cursor: pointer; font-weight: 600;">Click to view step-by-step instructions</summary>
					<pre style="margin-top: 1em; white-space: pre-wrap; font-family: monospace; font-size: 12px; background: #fff; padding: 1em; border: 1px solid #ddd;"><?php echo esc_html($cloudways_instructions); ?></pre>
				</details>

				<p>
					<a href="<?php echo esc_url($config['support_url']); ?>" target="_blank" class="button button-primary">
						Open Cloudways Dashboard
					</a>
					<button type="button" class="button rover-dismiss-hosting-cache-btn" style="margin-left: 10px;">
						I've configured this - Dismiss
					</button>
				</p>
			<?php else : ?>
				<p><strong>Please contact <?php echo esc_html($config['name']); ?> support</strong> and send them the following message:</p>

				<textarea readonly rows="10" id="rover-support-message" style="width: 100%; max-width: 600px; font-family: monospace; font-size: 12px; background: #f9f9f9; border: 1px solid #ddd; padding: 10px;"><?php echo esc_textarea($support_message); ?></textarea>

				<p>
					<button type="button" class="button" id="rover-copy-hosting-cache-btn">Copy to Clipboard</button>
					<a href="<?php echo esc_url($config['support_url']); ?>" target="_blank" class="button button-primary" style="margin-left: 5px;">
						Open <?php echo esc_html($config['name']); ?> Support
					</a>
					<button type="button" class="button rover-dismiss-hosting-cache-btn" style="margin-left: 10px;">
						I've contacted support - Dismiss
					</button>
				</p>
			<?php endif; ?>
		</div>

		<script>
		document.getElementById('rover-copy-hosting-cache-btn')?.addEventListener('click', function() {
			navigator.clipboard.writeText(document.getElementById('rover-support-message').value);
			this.textContent = 'Copied!';
			setTimeout(() => this.textContent = 'Copy to Clipboard', 2000);
		});

		document.querySelectorAll('.rover-dismiss-hosting-cache-btn').forEach(btn => {
			btn.addEventListener('click', function() {
				fetch(ajaxurl, {
					method: 'POST',
					headers: {'Content-Type': 'application/x-www-form-urlencoded'},
					body: 'action=rover_dismiss_hosting_notice&host=<?php echo esc_attr($host); ?>&idx_hosting_nonce=<?php echo esc_attr($nonce); ?>'
				}).then(() => document.getElementById('rover-hosting-notice')?.remove());
			});
		});
		</script>
		<?php
		}

	function admin_notice_dismiss_hosting_notice() {

		check_ajax_referer('rover_dismiss_hosting_notice', 'idx_hosting_nonce');

		if (!current_user_can('manage_options')) {
			wp_die('Unauthorized', 403);
		}

		$host			= sanitize_key($_POST['host'] ?? '');
		if (!in_array($host, array_keys($hosts), true)) {
			wp_die('Invalid host', 400);
		}

		$dismissed		= get_option('rover_hosting_cache_notices_dismissed', []);
		$dismissed[$host] = true;
		update_option('rover_hosting_cache_notices_dismissed', $dismissed);

		wp_die('OK');
		}

	public function admin_notice_diverse_solutions_migration()	{

		$class			= 'notice notice-info rover-notice rover-notice-ds is-dismissible';
		$message		= array();
		$message[]		= '<a href="admin.php?page=rover-panel-migrate-ds">Click here</a> to migrate your <strong>Diverse Solutions</strong> IDX pages to <strong>Rover IDX</strong> pages';
		$message[]		= 'All meta and settings will be maintained, and the DS IDX Data Filters will be converted to the appropriate Rover IDX shortcode.';

		printf( '<div class="%1$s"><p>%2$s</p></div>', $class, implode('<br>', $message) );
		}

	public function admin_notice_no_region_set()	{

		$class			= 'notice notice-warning rover-notice is-dismissible';
		$message		= 'Rover IDX - Please <a href="'.admin_url('admin.php?page=rover-idx').'">select an MLS region</a>.';

		printf( '<div class="%1$s"><p>%2$s</p></div>', $class, $message );
		}

	public function admin_body_class($classes) {

		return $classes.' rover-enabled rover-wp-repo';
		}

	public function update_permalink()	{

		$perm								= get_option('permalink_structure');
		$url_ends_with_slash				= ($perm && substr($perm, -1) != '/')
													? false
													: true;

		$this->rover_idx->update_region_settings(__FUNCTION__, __LINE__, 'url_ends_with_slash', $url_ends_with_slash);
		}

	public function add_block_categories($categories)	{

		$categories[] = [
			'slug'  => 'rover-idx-data-blocks',
			'title' => \sprintf(
				\__( '%1$s Blocks', 'rover-idx' ),
				'Rover IDX'
			),
		];

		return $categories;
		}

	private function has_unmigrated_diverse_solutions($check_for = null)	{

		global								$wpdb;

		$ds									= get_option('roveridx_has_diverse_solutions');
		if ($ds == 'no')
			return false;

		if ($check_for === 'notice')
			{
			if (get_option('roveridx_dismissed_diverse_solutions') == 'yes')
				return false;
			}

		$one_row	= $wpdb->get_row( "SELECT * FROM $wpdb->posts
									WHERE post_type = 'ds-idx-listings-page'
									AND post_status = 'publish'" );

		if (is_null($one_row))
			{
			update_option( 'roveridx_has_diverse_solutions', 'no' );
			return false;
			}

		return true;
		}

	public function dashboard_active_summary()	{

		$dash								= new Rover_IDX_Dashboard($this->rover_idx);

		wp_add_dashboard_widget(
					'idx_dashboard_active',							#	Widget slug
					'Rover IDX - Active Listings',					#	Title
					[ $dash, 'dashboard_active_summary' ]			#	Display function
					);

		}

	public function dashboard_visitor_activity()			{

		$dash								= new Rover_IDX_Dashboard($this->rover_idx);

		wp_add_dashboard_widget(
					'idx_dashboard_activity',						#	Widget slug
					'Rover IDX - Visitor Activity',					#	Title
					[ $dash, 'dashboard_activity' ]					#	Display function
					);

		}

	public function dashboard_mail()			{

		$dash								= new Rover_IDX_Dashboard($this->rover_idx);

		wp_add_dashboard_widget(
					'idx_dashboard_mail',							#	Widget slug
					'Rover IDX - Mail',								#	Title
					[ $dash, 'dashboard_mail' ]						#	Display function
					);

		}

	public function block_shortcode_refresh_callback()		{

		if ( current_user_can('edit_posts') )
			{
			$rover_content					= $this->rover_idx->CONTENT->rover_content(
																	'ROVER_COMPONENT_LISTINGS',
																	array_merge(
																		array(
																			'region'	=> $this->rover_idx->get_first_region(),
																			'regions'	=> implode(',', array_keys($this->rover_idx->all_selected_regions))
																			),
																		$_POST,
																		)
																	);

			$this->rover_idx->COMMON->error_log(__FILE__, __FUNCTION__, __LINE__, 'returning ['.print_r($rover_content, true).']');

			exit(json_encode(array(
					"success"		=> true,
					"html"			=> $rover_content['the_html']
					)));
			}
		}

	public function roveridx_plugin_action_links( $links, $file ) {	// Display a Settings link on the main Plugins page

		if ( $file == plugin_basename( __FILE__ ) ) {
			$roveridx_links = '<a href="'.get_admin_url().'options-general.php?page=rover-idx/roveridx.php">'.__('Settings').'</a>';
			#	make the 'Settings' link appear first
			array_unshift( $links, $roveridx_links );
			}

		return $links;
		}

	public function validate_options($input) {				#	Sanitize and validate input. Accepts an array, return a sanitized array.
		#	strip html from textboxes
		#	$input['textarea_one'] =  wp_filter_nohtml_kses($input['textarea_one']);	// Sanitize textarea input (strip html tags, and escape characters)
		#	$input['txt_one'] =  wp_filter_nohtml_kses($input['txt_one']); 				#	Sanitize textbox input (strip html tags, and escape characters)
		return $input;
		}
	}

?>