<?php
/**
 * Core Logic for CleanView.
 *
 * @package PureDash
 */

namespace PureDash;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class Core
 */
class Core {

	/**
	 * Constructor.
	 */
	public function __construct() {
		// Kill Switch: Emergency Disable (defined in wp-config.php)
		if ( defined( 'PUREDASH_DISABLE' ) && PUREDASH_DISABLE ) {
			return;
		}

		add_action( 'admin_init', array( $this, 'handle_safe_mode_toggle' ) ); // Safe Mode Toggle Handler
		add_action( 'admin_notices', array( $this, 'display_safe_mode_notice' ) ); // Safe Mode persistent notice
		add_action( 'admin_menu', array( $this, 'hide_blocked_menus' ), 999 ); // PHP-level menu removal
		add_action( 'wp_before_admin_bar_render', array( $this, 'hide_blocked_admin_bar_nodes_php' ), 999 ); // Admin bar sync synchronization
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );

		add_action( 'admin_bar_menu', array( $this, 'admin_bar_menu' ), 100 );
		add_action( 'wp_ajax_puredash_save_block', array( $this, 'ajax_save_block' ) );
		add_action( 'wp_ajax_puredash_delete_block', array( $this, 'ajax_delete_block' ) );
		add_action( 'wp_ajax_puredash_update_block_label', array( $this, 'ajax_update_block_label' ) );
	}

	/**
	 * Enqueue scripts and styles.
	 */
	public function enqueue_assets() {
		// Only load on backend
		if ( ! is_admin() ) {
			return;
		}

		// CSS
		wp_enqueue_style( 'puredash-styles', PUREDASH_URL . 'assets/puredash-styles.css', array(), PUREDASH_VERSION );

		// JS
		wp_enqueue_script( 'puredash-modal', PUREDASH_URL . 'assets/puredash-modal.js', array(), PUREDASH_VERSION, true );
		wp_enqueue_script( 'puredash-engine', PUREDASH_URL . 'assets/puredash-engine.js', array( 'puredash-modal' ), PUREDASH_VERSION, true );

		// Inline blocking CSS (anciennement dans inject_styles via admin_head)
		$inline_css = $this->get_blocking_css();
		if ( $inline_css ) {
			wp_add_inline_style( 'puredash-styles', $inline_css );
		}

		// Localize Script
		$blacklist = get_option( 'puredash-cleaner_blacklist', array() );

		wp_localize_script(
			'puredash-engine',
			'puredashConfig',
			array(
				'nonce'     => wp_create_nonce( 'puredash_nonce' ),
				'ajaxUrl'   => admin_url( 'admin-ajax.php' ),
				'pluginUrl' => PUREDASH_URL,
				'whitelist' => $this->get_whitelist(),
				'safeMode'  => $this->is_safe_mode(),
				'blocked'   => $blacklist,
				'i18n'      => array(
					'confirmTitle' => esc_html__( 'Hide Element', 'puredash-cleaner' ),
					'confirm'      => esc_html__( 'Hide Element', 'puredash-cleaner' ),
					'cancel'       => esc_html__( 'Cancel', 'puredash-cleaner' ),
					'preview'      => esc_html__( 'Preview', 'puredash-cleaner' ),
					'restore'      => esc_html__( 'Restore', 'puredash-cleaner' ),
					'label'        => esc_html__( 'Label (for your reference)', 'puredash-cleaner' ),
					'sessionOnly'  => esc_html__( 'Hide temporarily (Reload to reset)', 'puredash-cleaner' ),
				),
			)
		);
	}



	/**
	 * Sanitize a CSS selector for safe output in a stylesheet context.
	 *
	 * Strips characters that could break out of the CSS selector context and
	 * inject arbitrary rules ({, }, ;) or HTML (</style>). Valid CSS selector
	 * characters (>, +, ~, :, [, ], ., #, etc.) are preserved.
	 *
	 * @param string $selector Raw CSS selector value.
	 * @return string Sanitized selector.
	 */
	private function sanitize_css_selector( $selector ) {
		// Remove HTML tags (covers </style> injection attempts).
		$selector = wp_strip_all_tags( $selector );
		// Strip characters that break out of selector context into CSS rules.
		$selector = preg_replace( '/[{};]/', '', $selector );
		return trim( $selector );
	}

	/**
	 * Calcule le CSS de blocage (extrait de l'ancienne méthode inject_styles).
	 *
	 * @return string CSS ou chaîne vide.
	 */
	private function get_blocking_css() {

		// Safety check: Safe Mode
		if ( $this->is_safe_mode() ) {
			return '';
		}

		$blacklist = get_option( 'puredash-cleaner_blacklist', array() );

		if ( empty( $blacklist ) || ! is_array( $blacklist ) ) {
			return '';
		}

		$selectors = array();

		// Hide for all users, no role filtering.
		foreach ( $blacklist as $entry ) {
			$selectors[] = $this->sanitize_css_selector( $entry['selector'] );
		}

		if ( empty( $selectors ) ) {
			return '';
		}

		// Debug Log
		$debug_comment = '';
		if ( defined( 'PUREDASH_DEBUG' ) && PUREDASH_DEBUG ) {
			$debug_comment = '/* cleanview Active Selectors: ' . esc_html( implode( ', ', $selectors ) ) . ' */';
		}

		// Group selectors - aggressive CSS to prevent gaps
		$hide_css = 'display: none !important; visibility: hidden !important; height: 0 !important; min-height: 0 !important; max-height: 0 !important; margin: 0 !important; padding: 0 !important; overflow: hidden !important; opacity: 0 !important; pointer-events: none !important;';

		$css = implode( ', ', array_unique( $selectors ) ) . ' { ' . $hide_css . ' }';

		// Safeguard: Never hide cleanview controls even if a broad selector matches them
		// Increase specificity using html body prefix
		$safeguard  = 'html body #wpadminbar #wp-admin-bar-cleanview-parent, html body #wpadminbar #wp-admin-bar-cleanview-toggle, html body .toplevel_page_puredash-cleaner { opacity: 1 !important; pointer-events: auto !important; visibility: visible !important; }';
		$safeguard .= 'html body .puredash-modal-overlay, html body .cleanview-toast-container { opacity: 1 !important; pointer-events: auto !important; visibility: visible !important; }';

		return $debug_comment . $css . $safeguard;
	}

	/**
	 * Display a persistent notice when Safe Mode is active.
	 */
	public function display_safe_mode_notice() {
		if ( ! $this->is_safe_mode() ) {
			return;
		}

		?>
		<div class="notice notice-warning" style="border-left-color: #f56e28; background-color: #fff8e1;">
			<p>
				<span class="dashicons dashicons-shield-alt" style="color: #f56e28; vertical-align: middle; margin-right: 5px;"></span>
				<strong><?php esc_html_e( 'PureDash Cleaner Safe Mode Active:', 'puredash-cleaner' ); ?></strong>
				<?php esc_html_e( 'All element blocks are temporarily disabled for troubleshooting.', 'puredash-cleaner' ); ?>
				<a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin.php?action=puredash_toggle_safe_mode' ), 'puredash_toggle_safe_mode' ) ); ?>" style="margin-left: 10px; font-weight: bold; color: #d63638;">
					<?php esc_html_e( 'Exit Safe Mode', 'puredash-cleaner' ); ?>
				</a>
			</p>
		</div>
		<?php
	}

	/**
	 * Remove blocked menu items from the sidebar via PHP for extra robustness.
	 * This works in addition to CSS hiding to ensure the menu is truly gone from the global $menu / $submenu.
	 */
	public function hide_blocked_menus() {
		// Safety check: Safe Mode
		if ( $this->is_safe_mode() ) {
			return;
		}

		$blacklist = get_option( 'puredash-cleaner_blacklist', array() );
		if ( empty( $blacklist ) || ! is_array( $blacklist ) ) {
			return;
		}

		foreach ( $blacklist as $entry ) {
			// Skip if no target URL saved (only menu items saved with target_url can be physically removed)
			if ( empty( $entry['target_url'] ) ) {
				continue;
			}

			$target_url = $entry['target_url'];

			// Safeguard: Never hide puredash-cleaner from the admin menu via this logic
			if ( 'puredash-cleaner' === $target_url || false !== strpos( $target_url, 'page=puredash-cleaner' ) ) {
				continue;
			}

			// 1. Attempt to remove as top-level menu
			remove_menu_page( $target_url );

			// 2. Attempt to remove as submenu item
			// We try common parents as we don't always know the exact parent slug stored by WP
			$common_parents = array(
				'index.php',
				'edit.php',
				'upload.php',
				'edit.php?post_type=page',
				'edit.php?post_type=post',
				'edit-comments.php',
				'themes.php',
				'plugins.php',
				'users.php',
				'tools.php',
				'options-general.php',
			);

			foreach ( $common_parents as $parent ) {
				remove_submenu_page( $parent, $target_url );
			}
		}
	}

	/**
	 * Remove menu items from the admin bar if their target URL is blocked.
	 * This mirrors the sidebar menu blocking logic to the top admin bar.
	 */
	public function hide_blocked_admin_bar_nodes_php() {
		// Safety check: Safe Mode
		if ( $this->is_safe_mode() ) {
			return;
		}

		$blacklist = get_option( 'puredash-cleaner_blacklist', array() );
		if ( empty( $blacklist ) || ! is_array( $blacklist ) ) {
			return;
		}

		$blocked_slugs = array();

		foreach ( $blacklist as $entry ) {
			if ( empty( $entry['target_url'] ) ) {
				continue;
			}

			$blocked_slugs[] = html_entity_decode( $entry['target_url'] );
		}

		if ( empty( $blocked_slugs ) ) {
			return;
		}

		global $wp_admin_bar;
		if ( ! is_object( $wp_admin_bar ) ) {
			return;
		}

		$nodes = $wp_admin_bar->get_nodes();
		if ( ! is_array( $nodes ) ) {
			return;
		}

		foreach ( $nodes as $node ) {
			if ( empty( $node->href ) || '#' === $node->href ) {
				continue;
			}

			// Safeguard: Never remove puredash-cleaner node from admin bar
			if ( 'cleanview-parent' === $node->id || 'cleanview-toggle' === $node->id ) {
				continue;
			}

			// Extract slug from node URL
			$node_url   = html_entity_decode( $node->href );
			$node_query = wp_parse_url( $node_url, PHP_URL_QUERY );
			$node_slug  = '';

			if ( $node_query ) {
				parse_str( $node_query, $node_params );
				if ( isset( $node_params['page'] ) ) {
					$node_slug = $node_params['page'];
				}
			}

			// If no 'page=' param, use the basename (e.g. tools.php)
			if ( ! $node_slug ) {
				$node_path = wp_parse_url( $node_url, PHP_URL_PATH );
				$node_slug = basename( $node_path );
			}

			foreach ( $blocked_slugs as $blocked_slug ) {
				if ( $node_slug === $blocked_slug ) {
					$wp_admin_bar->remove_node( $node->id );
					break;
				}
			}
		}
	}

	/**
	 * Add toggle to Admin Bar.
	 *
	 * @param WP_Admin_Bar $wp_admin_bar Admin bar instance.
	 */
	public function admin_bar_menu( $wp_admin_bar ) {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$blacklist    = get_option( 'puredash-cleaner_blacklist', array() );
		$has_blocks   = ! empty( $blacklist ) && is_array( $blacklist );
		$parent_class = $has_blocks ? 'cleanview-active-blocks' : '';

		// Parent Node
		$wp_admin_bar->add_node(
			array(
				'id'    => 'cleanview-parent',
				'title' => '<span class="ab-icon dashicons dashicons-visibility"></span> ' . esc_html__( 'PureDash Cleaner', 'puredash-cleaner' ),
				'href'  => admin_url( 'options-general.php?page=puredash-cleaner' ),
				'meta'  => array(
					'class' => $parent_class,
				),
			)
		);

		// Child Node: Toggle
		$wp_admin_bar->add_node(
			array(
				'parent' => 'cleanview-parent',
				'id'     => 'cleanview-toggle',
				'title'  => esc_html__( 'Toggle Zen Mode', 'puredash-cleaner' ),
				'href'   => '#',
				'meta'   => array(
					'class'   => 'cleanview-toggle-btn',
					'onclick' => 'return false;', // Handled by JS
				),
			)
		);

		// Child Node: Settings
		$wp_admin_bar->add_node(
			array(
				'parent' => 'cleanview-parent',
				'id'     => 'cleanview-settings',
				'title'  => esc_html__( 'Settings', 'puredash-cleaner' ),
				'href'   => admin_url( 'options-general.php?page=puredash-cleaner' ),
			)
		);

		// Child Node: Safe Mode Toggle (secured with nonce)
		if ( current_user_can( 'manage_options' ) ) {
			$is_safe_mode = $this->is_safe_mode();
			$toggle_url   = wp_nonce_url(
				admin_url( 'admin.php?action=puredash_toggle_safe_mode' ),
				'puredash_toggle_safe_mode'
			);

			$safe_mode_text = $is_safe_mode ? esc_html__( 'Exit Safe Mode', 'puredash-cleaner' ) : esc_html__( 'Activate Safe Mode', 'puredash-cleaner' );

			$wp_admin_bar->add_node(
				array(
					'parent' => 'cleanview-parent',
					'id'     => 'cleanview-safe-mode',
					'title'  => $safe_mode_text,
					'href'   => $toggle_url,
					'meta'   => array( 'class' => $is_safe_mode ? '' : 'cleanview-danger-item' ),
				)
			);
		}

		// Child Node: Reset All (Danger)
		$reset_url = wp_nonce_url( admin_url( 'admin-post.php?action=puredash_reset_all' ), 'puredash_reset_all' );
		$wp_admin_bar->add_node(
			array(
				'parent' => 'cleanview-parent',
				'id'     => 'cleanview-reset-all',
				'title'  => esc_html__( 'Reset All Settings', 'puredash-cleaner' ),
				'href'   => $reset_url,
				'meta'   => array(
					'class'   => 'cleanview-danger-item',
					'onclick' => 'return confirm("' . esc_js( esc_html__( 'Are you sure you want to reset all PureDash Cleaner settings? This cannot be undone.', 'puredash-cleaner' ) ) . '");',
				),
			)
		);
	}

	/**
	 * AJAX: Save a blocked selector.
	 */
	public function ajax_save_block() {
		check_ajax_referer( 'puredash_nonce', 'security' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized', 'puredash-cleaner' ) ) );
		}

		// Check if settings are locked
		if ( $this->is_settings_locked() ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Settings are locked. Modifications are disabled.', 'puredash-cleaner' ) ) );
		}

		$selector = isset( $_POST['selector'] ) ? sanitize_text_field( wp_unslash( $_POST['selector'] ) ) : '';
		$label    = isset( $_POST['label'] ) ? sanitize_text_field( wp_unslash( $_POST['label'] ) ) : '';
		$category = isset( $_POST['category'] ) ? sanitize_key( wp_unslash( $_POST['category'] ) ) : 'other';

		// Strict Sanitization for CSS Selector (allows '>', ':', '[]', etc.)
		$selector = preg_replace( '/<\/style>/i', '', $selector );
		$selector = trim( wp_strip_all_tags( $selector ) );

		$target_url = isset( $_POST['target_url'] ) ? sanitize_text_field( wp_unslash( $_POST['target_url'] ) ) : '';

		if ( empty( $selector ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Invalid selector', 'puredash-cleaner' ) ) );
		}

		// Conflict Check
		$blacklist = get_option( 'puredash-cleaner_blacklist', array() );

		// Ensure $blacklist is always an array (fix for PHP 8+ count() TypeError)
		if ( ! is_array( $blacklist ) ) {
			$blacklist = array();
		}

		// Store with Hash for uniqueness
		$hash = md5( $selector );

		if ( isset( $blacklist[ $hash ] ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Selector already blocked', 'puredash-cleaner' ) ) );
		}

		$blacklist[ $hash ] = array(
			'selector'   => $selector,
			'label'      => $label ? $label : $selector,
			'category'   => $category,
			'created_at' => current_time( 'mysql' ),
			'user_id'    => get_current_user_id(),
			'target_url' => $target_url,
		);

		update_option( 'puredash-cleaner_blacklist', $blacklist );

		wp_send_json_success(
			array(
				'id'       => $hash,
				'selector' => $selector,
			)
		);
	}

	/**
	 * AJAX: Delete a blocked selector.
	 */
	public function ajax_delete_block() {
		// Not implemented in spec fully but needed for settings page management
		check_ajax_referer( 'puredash_nonce', 'security' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized', 'puredash-cleaner' ) ) );
		}

		// Check if settings are locked
		if ( $this->is_settings_locked() ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Settings are locked. Modifications are disabled.', 'puredash-cleaner' ) ) );
		}

		$hash      = isset( $_POST['id'] ) ? sanitize_text_field( wp_unslash( $_POST['id'] ) ) : '';
		$blacklist = get_option( 'puredash-cleaner_blacklist', array() );

		if ( isset( $blacklist[ $hash ] ) ) {
			unset( $blacklist[ $hash ] );
			update_option( 'puredash-cleaner_blacklist', $blacklist );
			wp_send_json_success();
		}

		wp_send_json_error( array( 'message' => esc_html__( 'Block not found', 'puredash-cleaner' ) ) );
	}

	/**
	 * AJAX: Update label for an existing block.
	 */
	public function ajax_update_block_label() {
		check_ajax_referer( 'puredash_nonce', 'security' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Unauthorized', 'puredash-cleaner' ) ) );
		}

		if ( $this->is_settings_locked() ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Settings are locked. Modifications are disabled.', 'puredash-cleaner' ) ) );
		}

		$hash  = isset( $_POST['id'] ) ? sanitize_text_field( wp_unslash( $_POST['id'] ) ) : '';
		$label = isset( $_POST['label'] ) ? sanitize_text_field( wp_unslash( $_POST['label'] ) ) : '';

		if ( empty( $hash ) || empty( $label ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Invalid data provided.', 'puredash-cleaner' ) ) );
		}

		$blacklist = get_option( 'puredash-cleaner_blacklist', array() );

		if ( ! isset( $blacklist[ $hash ] ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Block not found', 'puredash-cleaner' ) ) );
		}

		$blacklist[ $hash ]['label'] = $label;
		update_option( 'puredash-cleaner_blacklist', $blacklist );

		wp_send_json_success( array( 'message' => esc_html__( 'Label updated successfully.', 'puredash-cleaner' ) ) );
	}

	/**
	 * Handle Safe Mode toggle action (secured with nonce).
	 */
	public function handle_safe_mode_toggle() {
		if ( ! isset( $_GET['action'] ) || 'puredash_toggle_safe_mode' !== $_GET['action'] ) {
			return;
		}

		// Verify nonce
		check_admin_referer( 'puredash_toggle_safe_mode' );

		// Verify permissions
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'puredash-cleaner' ) );
		}

		// Toggle Safe Mode in user meta
		$user_id = get_current_user_id();
		$current = get_user_meta( $user_id, 'puredash_safe_mode', true );
		update_user_meta( $user_id, 'puredash_safe_mode', ! $current );

		// Redirect back, ensuring we remove the URL parameter if present
		$redirect_url = wp_get_referer() ? wp_get_referer() : admin_url();
		$redirect_url = remove_query_arg( 'puredash_safe_mode', $redirect_url );

		wp_safe_redirect( $redirect_url );
		exit;
	}

	/**
	 * Check if Safe Mode is active for current user.
	 *
	 * @return bool
	 */
	public function is_safe_mode() {
		if ( '1' === filter_input( INPUT_GET, 'puredash_safe_mode', FILTER_SANITIZE_FULL_SPECIAL_CHARS ) ) {
			return true;
		}

		$user_id = get_current_user_id();
		return (bool) get_user_meta( $user_id, 'puredash_safe_mode', true );
	}

	/**
	 * Get whitelisted selectors that cannot be blocked.
	 *
	 * @return array
	 */
	private function get_whitelist() {
		return array(
			'#wpadminbar',
			'#wp-admin-bar-my-account',
			'#adminmenu',
			'#adminmenumain',
			'.toplevel_page_puredash-cleaner',
			'#wpfooter',
			'#wpbody-content > .wrap',
			'.wrap > h1',
			'#wpbody',
			'.puredash-modal',
		);
	}

	/**
	 * Check if settings are locked via PUREDASH_LOCK_SETTINGS constant.
	 *
	 * @return bool True if settings are locked, false otherwise.
	 */
	private function is_settings_locked() {
		return defined( 'PUREDASH_LOCK_SETTINGS' ) && PUREDASH_LOCK_SETTINGS;
	}
}
